Skip to main content

nomiscript/compiler/context/
globals.rs

1//! The `$t` singleton (ADR-0033): a module global of an empty struct type,
2//! `t`'s sole runtime representation. Recognised by reference identity
3//! (`ref.eq`), never by type test — WasmGC struct types are structural, so an
4//! empty struct type alone would not be unique.
5
6use wasm_encoder::{ConstExpr, ExportKind, GlobalType, HeapType, Instruction, RefType, ValType};
7
8use super::CompileContext;
9use crate::ast::WasmType;
10use crate::error::{Error, Result};
11
12/// The export name of the mutable global `idx` a unit allocated for a runtime
13/// global; the host reads it back after the unit runs.
14#[must_use]
15pub fn global_export_name(idx: u32) -> String {
16    format!("g{idx}")
17}
18
19impl CompileContext {
20    /// Registers the `$t_ty` empty struct type and the exported `t` global
21    /// initialised with `struct.new $t_ty`. Called once from `new_skeleton`,
22    /// alongside the other struct-type registrations, so `ids.ty_t` /
23    /// `ids.global_t` are set before any helper body needs to `global.get` it.
24    pub(super) fn register_t_global(&mut self) -> Result<()> {
25        let ty_t = self.register_struct_type(&[])?;
26        self.ids.ty_t = ty_t;
27        let global_ty = GlobalType {
28            val_type: ValType::Ref(RefType {
29                nullable: false,
30                heap_type: HeapType::Concrete(ty_t),
31            }),
32            mutable: false,
33            shared: false,
34        };
35        let init = ConstExpr::extended([Instruction::StructNew(ty_t)]);
36        let global_idx = self.push_global(global_ty, &init)?;
37        self.ids.global_t = global_idx;
38        self.exports.export("t", ExportKind::Global, global_idx);
39        Ok(())
40    }
41
42    /// Allocates a mutable global of `ty`, null (or zero) until the program
43    /// stores to it, exports it as [`global_export_name`] and returns its index.
44    pub(crate) fn alloc_mutable_global(&mut self, ty: WasmType) -> Result<u32> {
45        let val_type = self.wasm_val_type(ty)?;
46        let init = match val_type {
47            ValType::Ref(ref_ty) => ConstExpr::ref_null(ref_ty.heap_type),
48            _ => ConstExpr::i32_const(0),
49        };
50        let global_ty = GlobalType {
51            val_type,
52            mutable: true,
53            shared: false,
54        };
55        let idx = self.push_global(global_ty, &init)?;
56        self.exports
57            .export(&global_export_name(idx), ExportKind::Global, idx);
58        Ok(idx)
59    }
60
61    pub(super) fn push_global(&mut self, global_ty: GlobalType, init: &ConstExpr) -> Result<u32> {
62        self.globals.global(global_ty, init);
63        let idx = self.global_count;
64        self.global_count = idx
65            .checked_add(1)
66            .ok_or_else(|| Error::Compile("wasm global index space exhausted".into()))?;
67        Ok(idx)
68    }
69}