Lines
99 %
Functions
100 %
Branches
//! `CompileContext` construction: the two public entry points
//! (`new` for script mode, `new_eval_with_host_fns` for eval mode), the
//! shared `new_skeleton` (types + memory + exception/`$t`-global setup every
//! mode needs), and the import declarations each mode wires up.
use std::collections::{BTreeMap, HashMap, HashSet};
use tracing::debug;
use wasm_encoder::{
CodeSection, DataSection, ExportKind, ExportSection, FunctionSection, GlobalSection,
ImportSection, MemorySection, MemoryType, TagSection, TypeSection, ValType,
};
use super::{CompileContext, block_joins, closure, entity_registry, ids, monomorph};
use crate::compiler::stats::CompileStats;
use crate::error::Result;
use crate::host_fn::HostFnSpec;
impl CompileContext {
/// Builds an eval-mode compile context: same types and ratio helpers as
/// script mode, but exports `nomi-eval` (returning `(ref null any)`)
/// instead of `should_apply`/`process`. Each entry in `host_fns`
/// gets a wasm import declared up-front (so the function index is
/// stable for codegen) plus an entry in the lookup table the native
/// dispatcher consults when emitting calls. The host decodes the
/// nomi-eval return via `scripting::runtime::decode_eval_result`.
pub fn new_eval_with_host_fns(host_fns: &[HostFnSpec]) -> Result<Self> {
let mut ctx = Self::new_skeleton()?;
ctx.register_raise_import()?;
ctx.register_catch_each_import()?;
// `env.log` is the output channel for PRINT / DISPLAY / NEWLINE / DEBUG.
// It was script-mode-only; without it those natives' `ctx.func("log")`
// had no func index in eval mode. Declared before the local `nomi-eval`
// fn so the import index space stays contiguous. Host side: the rpc
// Session linker wires `env.log` (mirrors `scripting::host`).
ctx.register_log_import()?;
for spec in host_fns {
ctx.register_host_fn(spec)?;
}
let anyref = ctx.anyref();
ctx.register_function("nomi-eval", &[], &[anyref])?;
// Two-phase (declare → resolve → build): declare every helper signature
// so all indices exist, snapshot them into `ids`, then emit the bodies
// reading `ids`. Declare order fixes the function-index space; build
// order fixes `pending_helpers` + data-segment indices — both preserved
// exactly as the pre-split single-pass layout, so the wasm is identical.
ctx.declare_ratio_helpers()?;
ctx.declare_unit_term_helpers()?;
ctx.declare_commodity_helpers()?;
ctx.declare_pair_helpers()?;
ctx.declare_index_helpers()?;
ctx.declare_string_eq_helper()?;
ctx.declare_condition_helper()?;
ctx.declare_entity_allocators()?;
ctx.declare_struct_helpers()?;
ctx.export_func("nomi-eval")?;
ctx.install_ids()?;
ctx.build_ratio_helpers()?;
ctx.build_unit_term_helpers();
ctx.build_commodity_helpers()?;
ctx.build_pair_helpers();
ctx.build_index_helpers()?;
ctx.build_string_eq_helper()?;
ctx.build_condition_helper();
ctx.build_entity_allocators()?;
ctx.build_struct_helpers();
debug!(
host_fn_count = host_fns.len(),
"eval compile context initialized"
);
Ok(ctx)
/// Declares the `(error 'code "msg")` lowering target up-front so
/// the function index is stable before any user host fn is wired.
/// The native is declared as `(string-ref, string-ref, anyref) -> ()` —
/// it never returns normally; the host always produces
/// a `ScriptRaise` error which the classifier lifts before
/// the unreachable-trap branch (ADR-0014). See
/// `rpc::natives::raise` for the host side.
fn register_raise_import(&mut self) -> Result<()> {
let arr = self.array_ref();
let detail = self.anyref();
self.register_import("nomi", "__nomi_raise", &[arr, arr, detail], &[])?;
Ok(())
/// Declares the `(catch-each items var body)` lowering target up-front.
/// The body is compiled to a real wasm fn (Tier 1.5 closure machinery)
/// whose funcref + env are extracted at the call site and passed to
/// `__nomi_catch_each` along with the items list. The host walks the
/// chain in Rust, calls the funcref per item recovering per-call
/// `wasmtime::Error`, and returns a heterogeneous `pair<anyref>`
/// chain of `(ok . v)` / `(err . (code . msg))` cells. Engine-bound
/// `OutOfFuel` / `EpochInterrupt` traps re-throw straight through —
/// they never appear as `err` cells (ADR-0025).
fn register_catch_each_import(&mut self) -> Result<()> {
// Items + result go on the wire as abstract `(ref null struct)`.
// The host registers the fn with `Rooted<StructRef>` whose
// `WasmTy::valtype()` is the abstract heap type — declaring the
// concrete `$pair` here would fail the import-type check at
// instantiation. Compiler emits a `ref.cast` after the call to
// recover the concrete `$pair` for the downstream pipeline; the
// items-arg side accepts a `(ref null $pair)` because the struct
// subtype relationship is one-way (concrete <: abstract).
let funcref = ValType::Ref(wasm_encoder::RefType::FUNCREF);
let any = self.anyref();
let abstract_struct = self.struct_ref();
self.register_import(
"nomi",
"__nomi_catch_each",
&[funcref, any, abstract_struct],
&[abstract_struct],
)?;
fn new_skeleton() -> Result<Self> {
let mut ctx = Self {
types: TypeSection::new(),
imports: ImportSection::new(),
functions: FunctionSection::new(),
memories: MemorySection::new(),
tags: TagSection::new(),
globals: GlobalSection::new(),
global_count: 0,
exports: ExportSection::new(),
codes: CodeSection::new(),
data: DataSection::new(),
data_count: 0,
type_count: 0,
tag_count: 0,
import_func_count: 0,
local_func_count: 0,
type_cache: HashMap::new(),
func_names: HashMap::new(),
host_fns: HashMap::new(),
pending_helpers: Vec::new(),
next_local: super::LOCAL_POOL_BASE,
local_types: Vec::new(),
serializer: super::super::layout::OutputSerializer::new(
super::super::expr::LOCAL_OUTPUT_BASE,
),
closures: closure::ClosureRegistry::default(),
declared_funcs: Vec::new(),
monomorphs: monomorph::MonomorphCache::default(),
nomi_error_tag: None,
ids: ids::WasmIds::UNRESOLVED,
inlining_stack: Vec::new(),
inlining_set: HashSet::new(),
block_labels: Vec::new(),
outer_labels: Vec::new(),
hidden_labels: Vec::new(),
block_joins: block_joins::BlockJoins::default(),
tag_frames: Vec::new(),
unwind_frames: Vec::new(),
stats: CompileStats::default(),
read_checks: HashMap::new(),
struct_layouts: HashMap::new(),
struct_serial: None,
struct_serial_base: 0,
instance_globals: BTreeMap::new(),
instances_init: None,
// Type indices are captured into `ids.ty_*` AS each type registers, so
// the type-ref accessors (`ratio_ref`, `pair_ref`, …) read `ids` even
// mid-skeleton — before the helper-fn `resolve_ids` runs. The struct
// layouts + registration order are unchanged, so the wasm is identical.
ctx.ids.ty_i8_array = ctx.register_type()?;
ctx.ids.ty_ratio = ctx.register_struct_type(&[ValType::I64, ValType::I64])?;
ctx.ids.ty_pair = ctx.register_pair_type()?;
let name = ctx.symbol_name_ref();
ctx.ids.ty_symbol = ctx.register_struct_type(&[name])?;
// Commodity unit-term (ADR-0028): a flat `(array (mut i64))` of sorted
// canonical `(hi, lo, exp)` triples. Registered before `commodity` so
// the struct's 5th field can reference it. A NULL term means ATOMIC
// `[(atom, 1)]`, so atomic money leaves the field unset and round-trips
// exactly as before this widening.
ctx.ids.ty_unit_term = ctx.register_i64_array_type()?;
// Commodity = (i64 numer, i64 denom, i64 commodity_hi, i64 commodity_lo,
// (ref null $unit_term) term). commodity_hi/lo carry the two halves of
// the UUID, stored as i64 to match wasmtime host-fn primitive types
// (reassembled to Uuid at the host boundary via `Uuid::from_u128`).
// Fields 0-3 are byte-identical to the pre-ADR-0028 layout.
let unit_term_ref = ctx.unit_term_ref();
ctx.ids.ty_commodity = ctx.register_struct_type(&[
ValType::I64,
unit_term_ref,
])?;
// Server-entity wasm struct types. Field layouts read from
// the single-source-of-truth `ENTITY_SPECS` table in
// `entity_registry.rs` — both this site and
// `register_entity_allocators` walk the same const so the
// struct layout and the allocator signature can't drift.
// Adding a new entity kind: extend `EntityKind` in =ast.rs= +
// add one row to `ENTITY_SPECS`.
// One recursion group, so same-shaped entity structs stay distinct
// types (see `register_struct_rec_group`).
let entity_fields: Vec<Vec<ValType>> = entity_registry::ENTITY_SPECS
.iter()
.map(|spec| spec.fields.iter().map(|f| f.as_val_type(&ctx)).collect())
.collect();
let indices = ctx.register_struct_rec_group(&entity_fields)?;
for (spec, idx) in entity_registry::ENTITY_SPECS.iter().zip(indices) {
ctx.ids.set_entity_type(spec.kind, idx);
ctx.register_closure_base_type()?;
// `$nomi_condition` struct + `$nomi_error` exception tag (Tier 3,
// ADR-0026). Registered here so the type/tag indices are stable
// before any body emits a `throw` / `try_table`. The tag's payload
// is a single `(ref null $nomi_condition)` so a catch hands the
// handler the condition ref directly.
ctx.register_exception_support()?;
ctx.register_t_global()?;
ctx.register_struct_types()?;
ctx.memories.memory(MemoryType {
minimum: 1,
maximum: None,
memory64: false,
shared: false,
page_size_log2: None,
});
ctx.exports.export("memory", ExportKind::Memory, 0);
/// Builds a script-mode compile context. Each entry in `host_fns` gets a
/// wasm import declared up-front, exactly as in eval mode, so a host
/// that links extra `nomi.*` fns (the behaviour oracle's entity and
/// money sources) can run a script that calls them.
pub fn new_with_host_fns(host_fns: &[HostFnSpec]) -> Result<Self> {
debug!("initializing compile context");
ctx.register_script_imports()?;
// Tier 3: the boundary wrapper around `process` / `should_apply`
// bridges an uncaught `$nomi_error` to `__nomi_raise`, so script
// mode must declare the import too (it was eval-mode-only). Must
// precede the first `register_function` so the import index space
// stays contiguous. Host side: `scripting::host::define_host_functions`.
ctx.register_function("should_apply", &[], &[ValType::I32])?;
// Two-phase (declare → resolve → build); see `new_eval_with_host_fns`.
// `should_apply` / `process` keep their function-index slots (declared
// around the helper declarations exactly as before); helper BODIES land
// on `pending_helpers` in build order, which the `should_apply`
// split-drain (bootstrap count) consumes unchanged.
ctx.register_function("process", &[], &[])?;
ctx.export_func("should_apply")?;
ctx.export_func("process")?;
debug!("compile context initialized");
/// Declares the `env.log` import — the host output channel shared by
/// PRINT / DISPLAY / NEWLINE / DEBUG (`(i32 level, i32 ptr, i32 len) -> ()`)
/// — and `env.log_value`, which prints a runtime argument list
/// (`(ref null any) -> i32`, nonzero when a value cannot be printed).
/// Used by both module modes so the `log` func index always exists wherever
/// those natives can be emitted.
fn register_log_import(&mut self) -> Result<()> {
"env",
"log",
&[ValType::I32, ValType::I32, ValType::I32],
&[],
let anyref = self.anyref();
self.register_import("env", "log_value", &[anyref], &[ValType::I32])?;
fn register_script_imports(&mut self) -> Result<()> {
self.register_import("env", "get_output_offset", &[], &[ValType::I32])?;
self.register_import("env", "symbol_resolve", &[ValType::I32, ValType::I32], &[])?;
self.register_log_import()?;
self.register_import("env", "get_input_offset", &[], &[ValType::I32])?;
self.register_import("env", "get_strings_offset", &[], &[ValType::I32])?;
self.register_import("env", "get_input_entities_count", &[], &[ValType::I32])?;
self.register_import("env", "get_timestamp", &[], &[ValType::I64])?;
self.register_import("env", "generate_uuid", &[ValType::I32], &[])?;
"write_string",
&[ValType::I32, ValType::I32],
&[ValType::I32],
"write_bytes",