nomiscript/compiler/context/
globals.rs1use wasm_encoder::{ConstExpr, ExportKind, GlobalType, HeapType, Instruction, RefType, ValType};
7
8use super::CompileContext;
9use crate::ast::WasmType;
10use crate::error::{Error, Result};
11
12#[must_use]
15pub fn global_export_name(idx: u32) -> String {
16 format!("g{idx}")
17}
18
19impl CompileContext {
20 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 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}