1
//! Reads a finished unit's globals back out of its instance and makes them
2
//! the session's values (plan 0014 PERSIST): the values the next unit's
3
//! symbol table holds for them.
4

            
5
use nomiscript::{
6
    Carried, Expr, Fraction, Number, PROLOGUE_DONE_EXPORT, PairElement, Rebind, StructId,
7
    SymbolTable, UnitSlot, WasmType, global_export_name,
8
};
9
use wasmtime::{AnyRef, AsContextMut, Instance, Rooted, Val};
10

            
11
use crate::checked_ref::CheckedAnyRef;
12

            
13
use super::carry_list::read_list;
14
use super::decode::{EvalValue, decode_anyref, decode_commodity};
15
use super::heap::{MAX_REACHED, settle_heap};
16
use super::structure::{
17
    CLOSURE_ENV, CLOSURE_SITE, InstanceMode, holds_unconstant, instance_identity, is_compound_money,
18
};
19
use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
20
use super::{EngineError, classify_runtime_error, resolve_type_handles};
21
use tracing::warn;
22

            
23
/// How a unit ended, which decides what its globals hold.
24
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25
pub enum UnitEnd {
26
    Returned,
27
    /// An uncaught `$nomi_error`: every dynamic binding was unwound.
28
    Raised,
29
    /// A trap, fuel, epoch or host error: no cleanup ran, so a special bound
30
    /// inside the trap holds the binding's value, which `Rebind` undoes.
31
    Trapped,
32
}
33

            
34
impl UnitEnd {
35
    /// The end of a unit whose call failed with `err`.
36
    #[must_use]
37
35911
    pub fn of_failure(err: &wasmtime::Error) -> Self {
38
35911
        match classify_runtime_error(err) {
39
31540
            EngineError::ScriptRaised { .. } => Self::Raised,
40
4371
            _ => Self::Trapped,
41
        }
42
35911
    }
43
}
44

            
45
/// Takes the unit's manifest and settles each slot it wrote: one none of whose
46
/// flags is 1 never got the unit's value and is put back as it was before the
47
/// unit, a function or layout keeps the last definition that ran, and a cell
48
/// that got a value carries the one its instance holds, or, when the unit
49
/// trapped inside a binding of it, the one outside the binding; one only a
50
/// DEFVAR of it reached stays declared special and unbound. Never fails the
51
/// unit that ran: a cell that cannot be read becomes an opaque global, loud
52
/// when a later unit reads it, and the cause is logged. The session heap is
53
/// settled only once the unit's instance prologue ran to its end.
54
707096
pub fn carry_globals(
55
707096
    mut store: impl AsContextMut,
56
707096
    instance: &Instance,
57
707096
    symbols: &mut SymbolTable,
58
707096
    end: UnitEnd,
59
707096
) {
60
707096
    let slots = symbols.take_unit_slots();
61
707096
    let holds_instances = symbols.instances().next().is_some();
62
717232
    let handles = match holds_instances || slots.iter().any(|slot| slot.cell.is_some()) {
63
250784
        true => resolve_type_handles(&mut store, instance)
64
            .inspect_err(|err| warn!(%err, "carrying unit globals: no type handles"))
65
            .ok(),
66
456312
        false => None,
67
    };
68
707096
    for slot in slots {
69
677703
        match slot.cell {
70
244231
            Some(cell) => carry_cell(
71
244231
                &mut store,
72
244231
                instance,
73
244231
                symbols,
74
244231
                handles.as_ref(),
75
244231
                &slot,
76
244231
                cell,
77
244231
                end,
78
244231
            ),
79
            None => {
80
433472
                let last = slot
81
433472
                    .flags
82
433472
                    .iter()
83
433702
                    .rposition(|&flag| ran(&mut store, instance, flag));
84
433472
                symbols.settle(&slot.name, slot.slot, last);
85
            }
86
        }
87
    }
88
707096
    let settles = holds_instances || handles.is_some();
89
707096
    if settles && prologue_done(&mut store, instance) {
90
250782
        settle_heap(&mut store, instance, symbols, handles.as_ref(), MAX_REACHED);
91
456314
    }
92
707096
}
93

            
94
/// Settles a cell: its first flag says it holds a value, the later ones that a
95
/// DEFVAR of it ran, which declares it special even when nothing bound it.
96
244231
fn carry_cell(
97
244231
    mut store: impl AsContextMut,
98
244231
    instance: &Instance,
99
244231
    symbols: &mut SymbolTable,
100
244231
    handles: Option<&TypeHandles>,
101
244231
    slot: &UnitSlot,
102
244231
    (global, ty): (u32, WasmType),
103
244231
    end: UnitEnd,
104
244231
) {
105
244231
    let outer = outer_binding(&mut store, instance, slot.rebind, end);
106
244231
    let (bound_flag, declaring) = slot.flags.split_first().unzip();
107
244231
    let bound = match outer {
108
1044
        Some((_, bound)) => bound,
109
243187
        None => bound_flag.is_some_and(|&flag| ran(&mut store, instance, flag)),
110
    };
111
244231
    let declaring = declaring.unwrap_or_default();
112
244231
    let declared = declaring
113
244231
        .iter()
114
35720
        .any(|&flag| ran(&mut store, instance, flag));
115
244231
    match (bound, declared) {
116
        (true, _) => {
117
238541
            let cell = (outer.map_or(global, |(outer, _)| outer), ty);
118
238541
            let carried = match handles {
119
                None => opaque("unreadable"),
120
238541
                Some(handles) => read_global(&mut store, instance, symbols, cell, handles)
121
1
                    .inspect_err(|err| warn!(%err, name = %slot.name, "carrying unit global"))
122
1
                    .unwrap_or_else(|_| opaque("unreadable")),
123
            };
124
238541
            symbols.carry(&slot.name, carried);
125
238541
            if !declared && !declaring.is_empty() {
126
1150
                symbols.restore_declaration(&slot.name, true);
127
237391
            }
128
        }
129
1960
        (false, true) => symbols.declare_unbound(&slot.name),
130
3730
        (false, false) => symbols.settle(&slot.name, slot.slot, None),
131
    }
132
244231
}
133

            
134
/// Puts back every slot a unit wrote when it compiled but never ran: its
135
/// instantiation failed, or an interrupt stopped it before its call.
136
1525
pub fn carry_not_run(symbols: &mut SymbolTable) {
137
1525
    for slot in symbols.take_unit_slots() {
138
385
        symbols.settle(&slot.name, slot.slot, None);
139
    }
140
1525
}
141

            
142
/// The global holding a rebound special's value outside every binding, and
143
/// whether it was bound there, when the unit trapped inside a binding of it.
144
244231
fn outer_binding(
145
244231
    mut store: impl AsContextMut,
146
244231
    instance: &Instance,
147
244231
    rebind: Option<Rebind>,
148
244231
    end: UnitEnd,
149
244231
) -> Option<(u32, bool)> {
150
244231
    let rebind = rebind.filter(|_| end == UnitEnd::Trapped)?;
151
1276
    let depth = read_i32(&mut store, instance, rebind.depth)?;
152
1276
    let bound = read_i32(&mut store, instance, rebind.outer_bound)?;
153
1276
    (depth > 0).then_some((rebind.outer, bound == 1))
154
244231
}
155

            
156
/// Whether the unit's instance prologue ran to its end: before that the
157
/// instance globals are null, and settling would drop every carried instance.
158
250784
fn prologue_done(mut store: impl AsContextMut, instance: &Instance) -> bool {
159
250784
    instance
160
250784
        .get_global(&mut store, PROLOGUE_DONE_EXPORT)
161
250784
        .map(|global| global.get(&mut store))
162
250784
        .and_then(|value| value.i32())
163
250784
        == Some(1)
164
250784
}
165

            
166
/// Whether the flag `flag` says its slot got the unit's value; a flag the
167
/// instance does not hold counts as set.
168
712609
fn ran(store: impl AsContextMut, instance: &Instance, flag: u32) -> bool {
169
712609
    read_i32(store, instance, flag).is_none_or(|ran| ran == 1)
170
712609
}
171

            
172
715161
fn read_i32(mut store: impl AsContextMut, instance: &Instance, idx: u32) -> Option<i32> {
173
715161
    instance
174
715161
        .get_global(&mut store, &global_export_name(idx))
175
715159
        .map(|global| global.get(&mut store))
176
715159
        .and_then(|value| value.i32())
177
715161
}
178

            
179
238541
fn read_global(
180
238541
    mut store: impl AsContextMut,
181
238541
    instance: &Instance,
182
238541
    symbols: &SymbolTable,
183
238541
    (idx, ty): (u32, WasmType),
184
238541
    handles: &TypeHandles,
185
238541
) -> wasmtime::Result<Carried> {
186
238541
    let export = global_export_name(idx);
187
238541
    let val = instance
188
238541
        .get_global(&mut store, &export)
189
1
        .ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{export}`")))?
190
238540
        .get(&mut store);
191
238540
    carried_value(&mut store, (symbols, handles), ty, val)
192
238541
}
193

            
194
240384
fn carried_value<S: AsContextMut>(
195
240384
    store: &mut S,
196
240384
    (symbols, handles): (&SymbolTable, &TypeHandles),
197
240384
    ty: WasmType,
198
240384
    val: Val,
199
240384
) -> wasmtime::Result<Carried> {
200
240384
    match (ty, val) {
201
180520
        (WasmType::I32, Val::I32(n)) => Ok(constant(EvalValue::I32(n))),
202
694
        (WasmType::Bool, Val::I32(n)) => Ok(constant(truth(n))),
203
        (WasmType::Closure(_), Val::AnyRef(Some(any))) => {
204
25896
            read_closure(store, (symbols, handles), &any)
205
        }
206
        (WasmType::Closure(_), _) => Ok(opaque("closure")),
207
7
        (WasmType::Commodity, Val::AnyRef(Some(any))) => Ok(read_money(&mut *store, &any)),
208
        (WasmType::EntityRef(_), _) => Ok(opaque("entity")),
209
        (WasmType::StructRef(id), Val::AnyRef(Some(any))) => {
210
10483
            let (serial, _) = instance_identity(&mut *store, &any)?;
211
10483
            Ok(Carried::Constant(Expr::Instance(serial, id)))
212
        }
213
462
        (_, Val::AnyRef(None)) => Ok(constant(EvalValue::Nil)),
214
22322
        (ty, Val::AnyRef(Some(any))) => Ok(read_ref(&mut *store, (symbols, handles), any, ty)),
215
        (ty, _) => Err(wasmtime::Error::msg(format!(
216
            "global of type {ty} holds a value of another kind"
217
        ))),
218
    }
219
240384
}
220

            
221
/// A closure as the lambda its source and captured values make; one whose
222
/// source was not kept, or that captures a value no constant holds, is opaque.
223
39354
pub(super) fn read_closure<S: AsContextMut>(
224
39354
    store: &mut S,
225
39354
    (symbols, handles): (&SymbolTable, &TypeHandles),
226
39354
    any: &Rooted<AnyRef>,
227
39354
) -> wasmtime::Result<Carried> {
228
39354
    let closure = any.checked_struct(&mut *store)?;
229
39354
    let site = closure.field(&mut *store, CLOSURE_SITE)?.i32();
230
39354
    let Some(source) = site.and_then(|site| symbols.closure_source(site)) else {
231
1037
        return Ok(opaque("closure"));
232
    };
233
38317
    let env = closure.field(&mut *store, CLOSURE_ENV)?;
234
38317
    let mut values = Vec::with_capacity(source.fields().len());
235
38317
    for (field, (_, ty)) in source.fields().iter().enumerate() {
236
1844
        let Val::AnyRef(Some(env)) = &env else {
237
            return Ok(opaque("closure"));
238
        };
239
1844
        let captured = env.checked_struct(&mut *store)?.field(&mut *store, field)?;
240
1844
        match capture_value(store, (symbols, handles), *ty, captured)? {
241
1842
            Some(value) => values.push(value),
242
2
            None => return Ok(opaque("closure")),
243
        }
244
    }
245
38315
    Ok(Carried::Constant(source.lambda(values)))
246
39354
}
247

            
248
/// The constant a captured variable is carried as; none for one that is not
249
/// constant.
250
1844
fn capture_value<S: AsContextMut>(
251
1844
    store: &mut S,
252
1844
    context: (&SymbolTable, &TypeHandles),
253
1844
    ty: WasmType,
254
1844
    captured: Val,
255
1844
) -> wasmtime::Result<Option<Expr>> {
256
1844
    Ok(carried_value(store, context, ty, captured)?.into_constant())
257
1844
}
258

            
259
1900
fn truth(raw: i32) -> EvalValue {
260
1900
    match raw {
261
1330
        0 => EvalValue::Nil,
262
570
        _ => EvalValue::T,
263
    }
264
1900
}
265

            
266
/// Atomic money is a typed constant; compound money has no host form.
267
7
fn read_money(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> Carried {
268
7
    match decode_commodity(&mut store, any) {
269
4
        Ok(value) => constant(value),
270
3
        Err(_) => opaque("money"),
271
    }
272
7
}
273

            
274
24968
pub(super) fn read_ref<S: AsContextMut>(
275
24968
    store: &mut S,
276
24968
    (symbols, handles): (&SymbolTable, &TypeHandles),
277
24968
    any: Rooted<AnyRef>,
278
24968
    ty: WasmType,
279
24968
) -> Carried {
280
24968
    match unconstant_kind(&mut *store, &any, ty, handles) {
281
        Ok(Some("list")) => {
282
11389
            read_list(store, (symbols, handles), &any).unwrap_or_else(|_| opaque("oversized"))
283
        }
284
231
        Ok(Some(kind)) => opaque(kind),
285
13348
        Ok(None) => decode_anyref(&mut *store, any, ty, handles, InstanceMode::Identity)
286
13348
            .map_or_else(|_| opaque("oversized"), constant),
287
        Err(_) => opaque("oversized"),
288
    }
289
24968
}
290

            
291
/// The name of the kind of `any` when a constant cannot hold it, or anything
292
/// it holds.
293
24968
fn unconstant_kind(
294
24968
    mut store: impl AsContextMut,
295
24968
    any: &Rooted<AnyRef>,
296
24968
    ty: WasmType,
297
24968
    handles: &TypeHandles,
298
24968
) -> wasmtime::Result<Option<&'static str>> {
299
24968
    let (kind, elem) = match ty {
300
        WasmType::AnyRef => (
301
4765
            classify_anyref(&mut store, *any, handles)?,
302
4765
            PairElement::AnyRef,
303
        ),
304
15651
        WasmType::PairRef(elem) => (AnyRefKind::Pair, elem),
305
4552
        _ => return Ok(None),
306
    };
307
20416
    match kind {
308
        AnyRefKind::Commodity => {
309
2
            Ok(is_compound_money(store.as_context_mut(), any)?.then_some("money"))
310
        }
311
        AnyRefKind::Entity(_) => Ok(Some("entity")),
312
230
        AnyRefKind::Closure(_) | AnyRefKind::Other => Ok(Some("closure")),
313
        AnyRefKind::Pair => {
314
15767
            let unconstant = holds_unconstant(store.as_context_mut(), *any, elem, handles, 0)?;
315
15767
            Ok(unconstant.then_some("list"))
316
        }
317
4417
        _ => Ok(None),
318
    }
319
24968
}
320

            
321
2290
pub(super) fn opaque(type_name: &str) -> Carried {
322
2290
    Carried::Opaque(type_name.to_string())
323
2290
}
324

            
325
353035
fn constant(value: EvalValue) -> Carried {
326
353035
    match top_constant(value) {
327
353035
        Some(expr) => Carried::Constant(expr),
328
        None => opaque("unreadable"),
329
    }
330
353035
}
331

            
332
/// A global's value as the constant a DEFVAR of it would bind.
333
3547933
pub(super) fn top_constant(value: EvalValue) -> Option<Expr> {
334
3547933
    match value {
335
        EvalValue::Ratio { numer, denom } => {
336
9501
            Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
337
        }
338
3800
        EvalValue::Symbol(name) => Some(match name.strip_prefix(':') {
339
2280
            Some(keyword) => Expr::Keyword(keyword.to_string()),
340
1520
            None => Expr::quoted(Expr::Symbol(name)),
341
        }),
342
3534632
        other => member_constant(other).map(|member| match member {
343
7795
            Expr::List(_) => Expr::quoted(member),
344
3526455
            plain => plain,
345
3534250
        }),
346
    }
347
3547933
}
348

            
349
/// A list member as the constant it was read from.
350
119073491
fn member_constant(value: EvalValue) -> Option<Expr> {
351
119073491
    match value {
352
2281
        EvalValue::Nil => Some(Expr::Nil),
353
570
        EvalValue::T => Some(Expr::T),
354
117418187
        EvalValue::I32(n) => Some(Expr::Number(Number::Index(i64::from(n)))),
355
        EvalValue::Ratio { numer, denom } => {
356
4
            Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
357
        }
358
7790
        EvalValue::String(text) => Some(Expr::String(text)),
359
        EvalValue::Symbol(name) => Some(match name.strip_prefix(':') {
360
            Some(keyword) => Expr::Keyword(keyword.to_string()),
361
            None => Expr::Symbol(name),
362
        }),
363
7795
        EvalValue::List(items) => items
364
7795
            .into_iter()
365
7795
            .map(member_constant)
366
7795
            .collect::<Option<Vec<_>>>()
367
7795
            .map(Expr::List),
368
9
        money @ EvalValue::Commodity { .. } => Some(Expr::RuntimeValue(money.into())),
369
1636473
        EvalValue::Instance { serial, layout } => Some(Expr::Instance(serial, StructId(layout))),
370
        EvalValue::Bytes(_)
371
        | EvalValue::Closure { .. }
372
        | EvalValue::Condition
373
        | EvalValue::Opaque
374
382
        | EvalValue::Struct(_) => None,
375
    }
376
119073491
}