Lines
97.67 %
Functions
80 %
Branches
100 %
//! The `$t` singleton (ADR-0033): a module global of an empty struct type,
//! `t`'s sole runtime representation. Recognised by reference identity
//! (`ref.eq`), never by type test — WasmGC struct types are structural, so an
//! empty struct type alone would not be unique.
use wasm_encoder::{ConstExpr, ExportKind, GlobalType, HeapType, Instruction, RefType, ValType};
use super::CompileContext;
use crate::ast::WasmType;
use crate::error::{Error, Result};
/// The export name of the mutable global `idx` a unit allocated for a runtime
/// global; the host reads it back after the unit runs.
#[must_use]
pub fn global_export_name(idx: u32) -> String {
format!("g{idx}")
}
impl CompileContext {
/// Registers the `$t_ty` empty struct type and the exported `t` global
/// initialised with `struct.new $t_ty`. Called once from `new_skeleton`,
/// alongside the other struct-type registrations, so `ids.ty_t` /
/// `ids.global_t` are set before any helper body needs to `global.get` it.
pub(super) fn register_t_global(&mut self) -> Result<()> {
let ty_t = self.register_struct_type(&[])?;
self.ids.ty_t = ty_t;
let global_ty = GlobalType {
val_type: ValType::Ref(RefType {
nullable: false,
heap_type: HeapType::Concrete(ty_t),
}),
mutable: false,
shared: false,
};
let init = ConstExpr::extended([Instruction::StructNew(ty_t)]);
let global_idx = self.push_global(global_ty, &init)?;
self.ids.global_t = global_idx;
self.exports.export("t", ExportKind::Global, global_idx);
Ok(())
/// Allocates a mutable global of `ty`, null (or zero) until the program
/// stores to it, exports it as [`global_export_name`] and returns its index.
pub(crate) fn alloc_mutable_global(&mut self, ty: WasmType) -> Result<u32> {
let val_type = self.wasm_val_type(ty)?;
let init = match val_type {
ValType::Ref(ref_ty) => ConstExpr::ref_null(ref_ty.heap_type),
_ => ConstExpr::i32_const(0),
val_type,
mutable: true,
let idx = self.push_global(global_ty, &init)?;
self.exports
.export(&global_export_name(idx), ExportKind::Global, idx);
Ok(idx)
pub(super) fn push_global(&mut self, global_ty: GlobalType, init: &ConstExpr) -> Result<u32> {
self.globals.global(global_ty, init);
let idx = self.global_count;
self.global_count = idx
.checked_add(1)
.ok_or_else(|| Error::Compile("wasm global index space exhausted".into()))?;