Skip to main content

nomiscript/runtime/symbol/
instances.rs

1//! The session's struct instances (rstruct S5): a global that holds a struct
2//! carries an [`Expr::Instance`] leaf, and the instance's field constants live
3//! here, so aliasing, mutation through an unwritten global and cycles survive
4//! from one unit to the next.
5
6use std::cell::RefCell;
7use std::collections::{BTreeMap, BTreeSet};
8
9use crate::ast::{Expr, StructId};
10
11use super::carry::Carried;
12use super::table::SymbolTable;
13
14/// A live instance: its layout and the constant of each field.
15#[derive(Clone, Debug, PartialEq)]
16pub struct StructInstance {
17    pub layout: StructId,
18    pub fields: Vec<Expr>,
19}
20
21#[derive(Clone, Debug, Default, PartialEq)]
22pub(crate) struct InstanceHeap {
23    instances: BTreeMap<u32, StructInstance>,
24    next_serial: u32,
25}
26
27/// What a host read of one instance after a unit: its fields, or `None` when
28/// it holds a value no constant holds (a closure, an entity, compound money).
29pub type Found = BTreeMap<u32, Option<StructInstance>>;
30
31/// The serials of the instances `expr` mentions.
32fn mentioned(expr: &Expr) -> Vec<u32> {
33    let found = RefCell::new(Vec::new());
34    expr.any_form(|form| {
35        if let Expr::Instance(serial, _) = form {
36            found.borrow_mut().push(*serial);
37        }
38        false
39    });
40    found.into_inner()
41}
42
43impl SymbolTable {
44    /// The serial the next unit's first new instance takes.
45    #[must_use]
46    pub fn next_serial(&self) -> u32 {
47        self.instances.next_serial
48    }
49
50    /// The live instances, by serial.
51    pub fn instances(&self) -> impl Iterator<Item = (u32, &StructInstance)> {
52        self.instances
53            .instances
54            .iter()
55            .map(|(serial, instance)| (*serial, instance))
56    }
57
58    /// Replaces the heap with what a host read after a unit. An instance that
59    /// is opaque, or reaches one or one never read, is dropped and so is every
60    /// global that reaches it, loud when a later unit reads it; an instance no
61    /// global or carried closure reaches is swept. The serial counter never
62    /// goes back.
63    pub fn settle_instances(&mut self, found: Found, next_serial: u32) {
64        let usable = usable(found);
65        self.demote_unreachable(&usable);
66        self.instances.instances = self.swept(usable);
67        self.instances.next_serial = self.instances.next_serial.max(next_serial);
68    }
69
70    fn global_values(&self) -> impl Iterator<Item = (&String, &Expr)> {
71        self.symbols
72            .iter()
73            .filter_map(|(name, symbol)| symbol.value().map(|value| (name, value)))
74    }
75
76    fn demote_unreachable(&mut self, usable: &BTreeMap<u32, StructInstance>) {
77        let lost: Vec<(String, &'static str)> = self
78            .global_values()
79            .filter(|(_, value)| {
80                mentioned(value)
81                    .iter()
82                    .any(|serial| !usable.contains_key(serial))
83            })
84            .map(|(name, value)| match value {
85                Expr::Lambda(..) => (name.clone(), "closure"),
86                _ => (name.clone(), "struct"),
87            })
88            .collect();
89        for (name, type_name) in lost {
90            self.carry(&name, Carried::Opaque(type_name.to_string()));
91        }
92    }
93
94    fn swept(&self, mut usable: BTreeMap<u32, StructInstance>) -> BTreeMap<u32, StructInstance> {
95        let mut marked = BTreeSet::new();
96        let mut pending: Vec<u32> = self
97            .global_values()
98            .flat_map(|(_, value)| mentioned(value))
99            .collect();
100        while let Some(serial) = pending.pop() {
101            if marked.insert(serial)
102                && let Some(instance) = usable.get(&serial)
103            {
104                pending.extend(instance.fields.iter().flat_map(mentioned));
105            }
106        }
107        usable.retain(|serial, _| marked.contains(serial));
108        usable
109    }
110}
111
112/// The instances every field of which is a constant of live instances.
113fn usable(found: Found) -> BTreeMap<u32, StructInstance> {
114    let mut usable: BTreeMap<u32, StructInstance> = found
115        .into_iter()
116        .filter_map(|(serial, instance)| instance.map(|instance| (serial, instance)))
117        .collect();
118    loop {
119        let dangling: Vec<u32> = usable
120            .iter()
121            .filter(|(_, instance)| {
122                instance
123                    .fields
124                    .iter()
125                    .flat_map(mentioned)
126                    .any(|serial| !usable.contains_key(&serial))
127            })
128            .map(|(serial, _)| *serial)
129            .collect();
130        if dangling.is_empty() {
131            return usable;
132        }
133        for serial in dangling {
134            usable.remove(&serial);
135        }
136    }
137}
138
139#[cfg(test)]
140#[path = "instances_tests.rs"]
141mod tests;