1use nomiscript::{
6 Carried, Expr, Fraction, Number, PROLOGUE_DONE_EXPORT, PairElement, Rebind, StructId,
7 SymbolTable, UnitSlot, WasmType, global_export_name,
8};
9use wasmtime::{AnyRef, AsContextMut, Instance, Rooted, Val};
10
11use crate::checked_ref::CheckedAnyRef;
12
13use super::carry_list::read_list;
14use super::decode::{EvalValue, decode_anyref, decode_commodity};
15use super::heap::{MAX_REACHED, settle_heap};
16use super::structure::{
17 CLOSURE_ENV, CLOSURE_SITE, InstanceMode, holds_unconstant, instance_identity, is_compound_money,
18};
19use super::type_handles::{AnyRefKind, TypeHandles, classify_anyref};
20use super::{EngineError, classify_runtime_error, resolve_type_handles};
21use tracing::warn;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum UnitEnd {
26 Returned,
27 Raised,
29 Trapped,
32}
33
34impl UnitEnd {
35 #[must_use]
37 pub fn of_failure(err: &wasmtime::Error) -> Self {
38 match classify_runtime_error(err) {
39 EngineError::ScriptRaised { .. } => Self::Raised,
40 _ => Self::Trapped,
41 }
42 }
43}
44
45pub fn carry_globals(
55 mut store: impl AsContextMut,
56 instance: &Instance,
57 symbols: &mut SymbolTable,
58 end: UnitEnd,
59) {
60 let slots = symbols.take_unit_slots();
61 let holds_instances = symbols.instances().next().is_some();
62 let handles = match holds_instances || slots.iter().any(|slot| slot.cell.is_some()) {
63 true => resolve_type_handles(&mut store, instance)
64 .inspect_err(|err| warn!(%err, "carrying unit globals: no type handles"))
65 .ok(),
66 false => None,
67 };
68 for slot in slots {
69 match slot.cell {
70 Some(cell) => carry_cell(
71 &mut store,
72 instance,
73 symbols,
74 handles.as_ref(),
75 &slot,
76 cell,
77 end,
78 ),
79 None => {
80 let last = slot
81 .flags
82 .iter()
83 .rposition(|&flag| ran(&mut store, instance, flag));
84 symbols.settle(&slot.name, slot.slot, last);
85 }
86 }
87 }
88 let settles = holds_instances || handles.is_some();
89 if settles && prologue_done(&mut store, instance) {
90 settle_heap(&mut store, instance, symbols, handles.as_ref(), MAX_REACHED);
91 }
92}
93
94fn carry_cell(
97 mut store: impl AsContextMut,
98 instance: &Instance,
99 symbols: &mut SymbolTable,
100 handles: Option<&TypeHandles>,
101 slot: &UnitSlot,
102 (global, ty): (u32, WasmType),
103 end: UnitEnd,
104) {
105 let outer = outer_binding(&mut store, instance, slot.rebind, end);
106 let (bound_flag, declaring) = slot.flags.split_first().unzip();
107 let bound = match outer {
108 Some((_, bound)) => bound,
109 None => bound_flag.is_some_and(|&flag| ran(&mut store, instance, flag)),
110 };
111 let declaring = declaring.unwrap_or_default();
112 let declared = declaring
113 .iter()
114 .any(|&flag| ran(&mut store, instance, flag));
115 match (bound, declared) {
116 (true, _) => {
117 let cell = (outer.map_or(global, |(outer, _)| outer), ty);
118 let carried = match handles {
119 None => opaque("unreadable"),
120 Some(handles) => read_global(&mut store, instance, symbols, cell, handles)
121 .inspect_err(|err| warn!(%err, name = %slot.name, "carrying unit global"))
122 .unwrap_or_else(|_| opaque("unreadable")),
123 };
124 symbols.carry(&slot.name, carried);
125 if !declared && !declaring.is_empty() {
126 symbols.restore_declaration(&slot.name, true);
127 }
128 }
129 (false, true) => symbols.declare_unbound(&slot.name),
130 (false, false) => symbols.settle(&slot.name, slot.slot, None),
131 }
132}
133
134pub fn carry_not_run(symbols: &mut SymbolTable) {
137 for slot in symbols.take_unit_slots() {
138 symbols.settle(&slot.name, slot.slot, None);
139 }
140}
141
142fn outer_binding(
145 mut store: impl AsContextMut,
146 instance: &Instance,
147 rebind: Option<Rebind>,
148 end: UnitEnd,
149) -> Option<(u32, bool)> {
150 let rebind = rebind.filter(|_| end == UnitEnd::Trapped)?;
151 let depth = read_i32(&mut store, instance, rebind.depth)?;
152 let bound = read_i32(&mut store, instance, rebind.outer_bound)?;
153 (depth > 0).then_some((rebind.outer, bound == 1))
154}
155
156fn prologue_done(mut store: impl AsContextMut, instance: &Instance) -> bool {
159 instance
160 .get_global(&mut store, PROLOGUE_DONE_EXPORT)
161 .map(|global| global.get(&mut store))
162 .and_then(|value| value.i32())
163 == Some(1)
164}
165
166fn ran(store: impl AsContextMut, instance: &Instance, flag: u32) -> bool {
169 read_i32(store, instance, flag).is_none_or(|ran| ran == 1)
170}
171
172fn read_i32(mut store: impl AsContextMut, instance: &Instance, idx: u32) -> Option<i32> {
173 instance
174 .get_global(&mut store, &global_export_name(idx))
175 .map(|global| global.get(&mut store))
176 .and_then(|value| value.i32())
177}
178
179fn read_global(
180 mut store: impl AsContextMut,
181 instance: &Instance,
182 symbols: &SymbolTable,
183 (idx, ty): (u32, WasmType),
184 handles: &TypeHandles,
185) -> wasmtime::Result<Carried> {
186 let export = global_export_name(idx);
187 let val = instance
188 .get_global(&mut store, &export)
189 .ok_or_else(|| wasmtime::Error::msg(format!("module does not export `{export}`")))?
190 .get(&mut store);
191 carried_value(&mut store, (symbols, handles), ty, val)
192}
193
194fn carried_value<S: AsContextMut>(
195 store: &mut S,
196 (symbols, handles): (&SymbolTable, &TypeHandles),
197 ty: WasmType,
198 val: Val,
199) -> wasmtime::Result<Carried> {
200 match (ty, val) {
201 (WasmType::I32, Val::I32(n)) => Ok(constant(EvalValue::I32(n))),
202 (WasmType::Bool, Val::I32(n)) => Ok(constant(truth(n))),
203 (WasmType::Closure(_), Val::AnyRef(Some(any))) => {
204 read_closure(store, (symbols, handles), &any)
205 }
206 (WasmType::Closure(_), _) => Ok(opaque("closure")),
207 (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 let (serial, _) = instance_identity(&mut *store, &any)?;
211 Ok(Carried::Constant(Expr::Instance(serial, id)))
212 }
213 (_, Val::AnyRef(None)) => Ok(constant(EvalValue::Nil)),
214 (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}
220
221pub(super) fn read_closure<S: AsContextMut>(
224 store: &mut S,
225 (symbols, handles): (&SymbolTable, &TypeHandles),
226 any: &Rooted<AnyRef>,
227) -> wasmtime::Result<Carried> {
228 let closure = any.checked_struct(&mut *store)?;
229 let site = closure.field(&mut *store, CLOSURE_SITE)?.i32();
230 let Some(source) = site.and_then(|site| symbols.closure_source(site)) else {
231 return Ok(opaque("closure"));
232 };
233 let env = closure.field(&mut *store, CLOSURE_ENV)?;
234 let mut values = Vec::with_capacity(source.fields().len());
235 for (field, (_, ty)) in source.fields().iter().enumerate() {
236 let Val::AnyRef(Some(env)) = &env else {
237 return Ok(opaque("closure"));
238 };
239 let captured = env.checked_struct(&mut *store)?.field(&mut *store, field)?;
240 match capture_value(store, (symbols, handles), *ty, captured)? {
241 Some(value) => values.push(value),
242 None => return Ok(opaque("closure")),
243 }
244 }
245 Ok(Carried::Constant(source.lambda(values)))
246}
247
248fn capture_value<S: AsContextMut>(
251 store: &mut S,
252 context: (&SymbolTable, &TypeHandles),
253 ty: WasmType,
254 captured: Val,
255) -> wasmtime::Result<Option<Expr>> {
256 Ok(carried_value(store, context, ty, captured)?.into_constant())
257}
258
259fn truth(raw: i32) -> EvalValue {
260 match raw {
261 0 => EvalValue::Nil,
262 _ => EvalValue::T,
263 }
264}
265
266fn read_money(mut store: impl AsContextMut, any: &Rooted<AnyRef>) -> Carried {
268 match decode_commodity(&mut store, any) {
269 Ok(value) => constant(value),
270 Err(_) => opaque("money"),
271 }
272}
273
274pub(super) fn read_ref<S: AsContextMut>(
275 store: &mut S,
276 (symbols, handles): (&SymbolTable, &TypeHandles),
277 any: Rooted<AnyRef>,
278 ty: WasmType,
279) -> Carried {
280 match unconstant_kind(&mut *store, &any, ty, handles) {
281 Ok(Some("list")) => {
282 read_list(store, (symbols, handles), &any).unwrap_or_else(|_| opaque("oversized"))
283 }
284 Ok(Some(kind)) => opaque(kind),
285 Ok(None) => decode_anyref(&mut *store, any, ty, handles, InstanceMode::Identity)
286 .map_or_else(|_| opaque("oversized"), constant),
287 Err(_) => opaque("oversized"),
288 }
289}
290
291fn unconstant_kind(
294 mut store: impl AsContextMut,
295 any: &Rooted<AnyRef>,
296 ty: WasmType,
297 handles: &TypeHandles,
298) -> wasmtime::Result<Option<&'static str>> {
299 let (kind, elem) = match ty {
300 WasmType::AnyRef => (
301 classify_anyref(&mut store, *any, handles)?,
302 PairElement::AnyRef,
303 ),
304 WasmType::PairRef(elem) => (AnyRefKind::Pair, elem),
305 _ => return Ok(None),
306 };
307 match kind {
308 AnyRefKind::Commodity => {
309 Ok(is_compound_money(store.as_context_mut(), any)?.then_some("money"))
310 }
311 AnyRefKind::Entity(_) => Ok(Some("entity")),
312 AnyRefKind::Closure(_) | AnyRefKind::Other => Ok(Some("closure")),
313 AnyRefKind::Pair => {
314 let unconstant = holds_unconstant(store.as_context_mut(), *any, elem, handles, 0)?;
315 Ok(unconstant.then_some("list"))
316 }
317 _ => Ok(None),
318 }
319}
320
321pub(super) fn opaque(type_name: &str) -> Carried {
322 Carried::Opaque(type_name.to_string())
323}
324
325fn constant(value: EvalValue) -> Carried {
326 match top_constant(value) {
327 Some(expr) => Carried::Constant(expr),
328 None => opaque("unreadable"),
329 }
330}
331
332pub(super) fn top_constant(value: EvalValue) -> Option<Expr> {
334 match value {
335 EvalValue::Ratio { numer, denom } => {
336 Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
337 }
338 EvalValue::Symbol(name) => Some(match name.strip_prefix(':') {
339 Some(keyword) => Expr::Keyword(keyword.to_string()),
340 None => Expr::quoted(Expr::Symbol(name)),
341 }),
342 other => member_constant(other).map(|member| match member {
343 Expr::List(_) => Expr::quoted(member),
344 plain => plain,
345 }),
346 }
347}
348
349fn member_constant(value: EvalValue) -> Option<Expr> {
351 match value {
352 EvalValue::Nil => Some(Expr::Nil),
353 EvalValue::T => Some(Expr::T),
354 EvalValue::I32(n) => Some(Expr::Number(Number::Index(i64::from(n)))),
355 EvalValue::Ratio { numer, denom } => {
356 Some(Expr::Number(Number::Scalar(Fraction::new(numer, denom))))
357 }
358 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 EvalValue::List(items) => items
364 .into_iter()
365 .map(member_constant)
366 .collect::<Option<Vec<_>>>()
367 .map(Expr::List),
368 money @ EvalValue::Commodity { .. } => Some(Expr::RuntimeValue(money.into())),
369 EvalValue::Instance { serial, layout } => Some(Expr::Instance(serial, StructId(layout))),
370 EvalValue::Bytes(_)
371 | EvalValue::Closure { .. }
372 | EvalValue::Condition
373 | EvalValue::Opaque
374 | EvalValue::Struct(_) => None,
375 }
376}