Skip to main content

nomiscript/runtime/symbol/
definitions.rs

1//! What a unit wrote and whether each write ran (plan 0014 PERSIST): every
2//! definition form of a slot has an exported i32 flag that is 1 once it ran.
3//! A host keeps the last definition whose flag is 1, or puts the slot back
4//! from the snapshot taken before the unit.
5
6use crate::ast::{Expr, StructId, WasmType};
7
8use super::closures::ClosureSource;
9use super::entry::Symbol;
10use super::rebind::Rebind;
11use super::table::SymbolTable;
12
13/// Which slot of a name a definition fills: a variable's value, the function
14/// (or macro) it names, or the field layout of the structure it names.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
16pub enum Slot {
17    Value,
18    Function,
19    Layout,
20}
21
22/// Everything a definer writes under one name: its symbol, the field layout
23/// of the structure of that name, and whether it was declared special or
24/// created by a `SETF`.
25#[derive(Clone, Debug, Default)]
26pub(crate) struct Written {
27    symbol: Option<Symbol>,
28    layout: Option<StructId>,
29    pub(super) special: bool,
30    pub(super) created: bool,
31}
32
33impl Written {
34    pub(super) fn holds_value(&self) -> bool {
35        self.symbol
36            .as_ref()
37            .is_some_and(|symbol| symbol.value().is_some())
38    }
39}
40
41/// One definition form of a slot in the unit being compiled: the flag it sets
42/// once it ran, and what it wrote.
43#[derive(Clone, Debug)]
44pub(super) struct Version {
45    flag: u32,
46    written: Written,
47}
48
49/// A slot the finished unit wrote: `flags` are the exported i32 globals, one
50/// per definition form in text order, each 1 once that form ran, `cell` the
51/// global a value slot holds its value in at run time, `rebind` the globals
52/// that say which value it holds outside a binding when a binder rebinds it.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct UnitSlot {
55    pub name: String,
56    pub slot: Slot,
57    pub flags: Vec<u32>,
58    pub cell: Option<(u32, WasmType)>,
59    pub rebind: Option<Rebind>,
60}
61
62impl SymbolTable {
63    /// Records the symbols the unit is about to write as they stand before
64    /// it, so a slot the unit never wrote can be put back.
65    pub(crate) fn snapshot_pre_unit(&self, names: impl IntoIterator<Item = String>) {
66        let mut book = super::homes::locked(&self.homes);
67        for name in names {
68            let written = self.written(&name);
69            book.pre_unit.entry(name).or_insert(written);
70        }
71    }
72
73    fn written(&self, name: &str) -> Written {
74        let mut symbol = self.symbols.get(name).cloned();
75        if let (Some(live), Some(restored)) = (symbol.as_mut(), self.restored_function(name))
76            && live.is_local_function()
77        {
78            live.function.clone_from(restored);
79        }
80        Written {
81            symbol,
82            layout: self.structs.id(name),
83            special: self.special_names.contains(name),
84            created: self.created_globals.contains(name),
85        }
86    }
87
88    /// Records the flag global that tells whether the definition form of
89    /// `name` in `slot` that just compiled has run, with what it wrote.
90    pub(crate) fn note_definition(&self, name: &str, slot: Slot, flag: u32) {
91        let written = self.written(name);
92        super::homes::locked(&self.homes)
93            .definitions
94            .entry((name.to_string(), slot))
95            .or_default()
96            .push(Version { flag, written });
97    }
98
99    /// Writes the manifest of the unit that just compiled, and keeps the
100    /// pre-unit snapshot its slots are put back from. Called once, after the
101    /// unit's module validates, with the source of the closures it created.
102    pub(crate) fn finish_unit(&mut self, closures: Vec<ClosureSource>) {
103        let book = super::homes::locked(&self.homes);
104        let slots = book
105            .definitions
106            .iter()
107            .map(|((name, slot), versions)| {
108                let cell = self.cell_of(name, *slot);
109                UnitSlot {
110                    name: name.clone(),
111                    slot: *slot,
112                    flags: versions.iter().map(|version| version.flag).collect(),
113                    cell,
114                    rebind: cell.and_then(|(global, _)| book.rebinds.get(&global).copied()),
115                }
116            })
117            .collect();
118        let pre_unit = book.pre_unit.clone();
119        let versions = book.definitions.clone();
120        drop(book);
121        self.unit_slots = slots;
122        self.unit_closures = closures;
123        self.forget_runtime_lexicals();
124        self.unit_pre = pre_unit;
125        self.unit_versions = versions;
126    }
127
128    fn cell_of(&self, name: &str, slot: Slot) -> Option<(u32, WasmType)> {
129        match (slot, self.symbols.get(name)?.value()?) {
130            (Slot::Value, Expr::WasmGlobal(idx, ty)) => Some((*idx, *ty)),
131            _ => None,
132        }
133    }
134
135    /// Takes the manifest of the unit that just compiled; a host that never
136    /// takes it leaves it to expire when the next unit starts.
137    pub fn take_unit_slots(&mut self) -> Vec<UnitSlot> {
138        std::mem::take(&mut self.unit_slots)
139    }
140
141    /// Settles `slot` of `name` once the unit ended: definition form `ran`
142    /// of the slot, the last whose flag was 1, is kept, or for `None` the
143    /// slot is put back as it stood before the unit. The other slots stay as
144    /// the unit made them.
145    pub fn settle(&mut self, name: &str, slot: Slot, ran: Option<usize>) {
146        let kept = ran.and_then(|at| self.unit_versions.get(&(name.to_string(), slot))?.get(at));
147        let unrun = kept.is_none();
148        let Written { symbol, layout, .. } = match kept {
149            Some(version) => version.written.clone(),
150            None => self.unit_pre.get(name).cloned().unwrap_or_default(),
151        };
152        match slot {
153            Slot::Layout => self.put_back_layout(name, layout),
154            Slot::Function => {
155                self.put_back_symbol(name, slot, symbol);
156                if let Some(function) = self.symbols.get_mut(name) {
157                    function.forget_runtime_lexicals();
158                }
159            }
160            Slot::Value => {
161                self.put_back_symbol(name, slot, symbol);
162                if unrun {
163                    self.restore_declaration(name, false);
164                }
165            }
166        }
167    }
168
169    fn put_back_symbol(&mut self, name: &str, slot: Slot, previous: Option<Symbol>) {
170        let mut restored = self
171            .symbols
172            .remove(name)
173            .unwrap_or_else(|| Symbol::bare(name));
174        match slot {
175            Slot::Function => restored.function = previous.and_then(|symbol| symbol.function),
176            _ => restored.value = previous.and_then(|symbol| symbol.value),
177        }
178        self.reinstate(name, (!restored.is_bare()).then_some(restored));
179    }
180
181    fn put_back_layout(&mut self, name: &str, layout: Option<StructId>) {
182        match layout {
183            Some(id) => self.structs.restore(name, id),
184            None => self.structs.forget(name),
185        }
186    }
187
188    fn reinstate(&mut self, name: &str, restored: Option<Symbol>) {
189        match restored {
190            Some(symbol) => {
191                self.symbols.insert(name.to_string(), symbol);
192            }
193            None => {
194                self.special_names.remove(name);
195                self.created_globals.remove(name);
196            }
197        }
198    }
199}
200
201#[cfg(test)]
202#[path = "definitions_tests.rs"]
203mod tests;