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

            
6
use crate::ast::{Expr, StructId, WasmType};
7

            
8
use super::closures::ClosureSource;
9
use super::entry::Symbol;
10
use super::rebind::Rebind;
11
use 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)]
16
pub 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)]
26
pub(crate) struct Written {
27
    symbol: Option<Symbol>,
28
    layout: Option<StructId>,
29
    pub(super) special: bool,
30
    pub(super) created: bool,
31
}
32

            
33
impl Written {
34
4579
    pub(super) fn holds_value(&self) -> bool {
35
4579
        self.symbol
36
4579
            .as_ref()
37
834
            .is_some_and(|symbol| symbol.value().is_some())
38
4579
    }
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)]
44
pub(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)]
54
pub 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

            
62
impl 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
2341829
    pub(crate) fn snapshot_pre_unit(&self, names: impl IntoIterator<Item = String>) {
66
2341829
        let mut book = super::homes::locked(&self.homes);
67
2341829
        for name in names {
68
4214361
            let written = self.written(&name);
69
4214361
            book.pre_unit.entry(name).or_insert(written);
70
        }
71
2341829
    }
72

            
73
6863401
    fn written(&self, name: &str) -> Written {
74
6863401
        let mut symbol = self.symbols.get(name).cloned();
75
6863401
        if let (Some(live), Some(restored)) = (symbol.as_mut(), self.restored_function(name))
76
5625
            && live.is_local_function()
77
        {
78
5625
            live.function.clone_from(restored);
79
6857776
        }
80
6863401
        Written {
81
6863401
            symbol,
82
6863401
            layout: self.structs.id(name),
83
6863401
            special: self.special_names.contains(name),
84
6863401
            created: self.created_globals.contains(name),
85
6863401
        }
86
6863401
    }
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
2649040
    pub(crate) fn note_definition(&self, name: &str, slot: Slot, flag: u32) {
91
2649040
        let written = self.written(name);
92
2649040
        super::homes::locked(&self.homes)
93
2649040
            .definitions
94
2649040
            .entry((name.to_string(), slot))
95
2649040
            .or_default()
96
2649040
            .push(Version { flag, written });
97
2649040
    }
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
2141123
    pub(crate) fn finish_unit(&mut self, closures: Vec<ClosureSource>) {
103
2141123
        let book = super::homes::locked(&self.homes);
104
2141123
        let slots = book
105
2141123
            .definitions
106
2141123
            .iter()
107
2263719
            .map(|((name, slot), versions)| {
108
2263719
                let cell = self.cell_of(name, *slot);
109
                UnitSlot {
110
2263719
                    name: name.clone(),
111
2263719
                    slot: *slot,
112
2480821
                    flags: versions.iter().map(|version| version.flag).collect(),
113
2263719
                    cell,
114
2263719
                    rebind: cell.and_then(|(global, _)| book.rebinds.get(&global).copied()),
115
                }
116
2263719
            })
117
            .collect();
118
2141123
        let pre_unit = book.pre_unit.clone();
119
2141123
        let versions = book.definitions.clone();
120
2141123
        drop(book);
121
2141123
        self.unit_slots = slots;
122
2141123
        self.unit_closures = closures;
123
2141123
        self.forget_runtime_lexicals();
124
2141123
        self.unit_pre = pre_unit;
125
2141123
        self.unit_versions = versions;
126
2141123
    }
127

            
128
2263719
    fn cell_of(&self, name: &str, slot: Slot) -> Option<(u32, WasmType)> {
129
2263719
        match (slot, self.symbols.get(name)?.value()?) {
130
558954
            (Slot::Value, Expr::WasmGlobal(idx, ty)) => Some((*idx, *ty)),
131
60505
            _ => None,
132
        }
133
2263719
    }
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
1442305
    pub fn take_unit_slots(&mut self) -> Vec<UnitSlot> {
138
1442305
        std::mem::take(&mut self.unit_slots)
139
1442305
    }
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
857176
    pub fn settle(&mut self, name: &str, slot: Slot, ran: Option<usize>) {
146
857176
        let kept = ran.and_then(|at| self.unit_versions.get(&(name.to_string(), slot))?.get(at));
147
857176
        let unrun = kept.is_none();
148
857176
        let Written { symbol, layout, .. } = match kept {
149
841777
            Some(version) => version.written.clone(),
150
15399
            None => self.unit_pre.get(name).cloned().unwrap_or_default(),
151
        };
152
857176
        match slot {
153
58034
            Slot::Layout => self.put_back_layout(name, layout),
154
            Slot::Function => {
155
734450
                self.put_back_symbol(name, slot, symbol);
156
734450
                if let Some(function) = self.symbols.get_mut(name) {
157
730706
                    function.forget_runtime_lexicals();
158
3744
                }
159
            }
160
            Slot::Value => {
161
64692
                self.put_back_symbol(name, slot, symbol);
162
64692
                if unrun {
163
9988
                    self.restore_declaration(name, false);
164
54704
                }
165
            }
166
        }
167
857176
    }
168

            
169
799142
    fn put_back_symbol(&mut self, name: &str, slot: Slot, previous: Option<Symbol>) {
170
799142
        let mut restored = self
171
799142
            .symbols
172
799142
            .remove(name)
173
            .unwrap_or_else(|| Symbol::bare(name));
174
799142
        match slot {
175
734450
            Slot::Function => restored.function = previous.and_then(|symbol| symbol.function),
176
64692
            _ => restored.value = previous.and_then(|symbol| symbol.value),
177
        }
178
799142
        self.reinstate(name, (!restored.is_bare()).then_some(restored));
179
799142
    }
180

            
181
58034
    fn put_back_layout(&mut self, name: &str, layout: Option<StructId>) {
182
58034
        match layout {
183
57617
            Some(id) => self.structs.restore(name, id),
184
417
            None => self.structs.forget(name),
185
        }
186
58034
    }
187

            
188
799142
    fn reinstate(&mut self, name: &str, restored: Option<Symbol>) {
189
799142
        match restored {
190
            Some(symbol) => {
191
789573
                self.symbols.insert(name.to_string(), symbol);
192
            }
193
            None => {
194
9569
                self.special_names.remove(name);
195
9569
                self.created_globals.remove(name);
196
            }
197
        }
198
799142
    }
199
}
200

            
201
#[cfg(test)]
202
#[path = "definitions_tests.rs"]
203
mod tests;