Lines
97.75 %
Functions
100 %
Branches
//! `CompileContext` — the per-module wasm assembly state shared across
//! every codegen path.
//!
//! Split across topic-focused submodules so each file stays under the
//! ~500-line CLAUDE.md guideline:
//! - [`construct`] — the two public constructors (`new`, `new_eval_with_host_fns`),
//! `new_skeleton`, and the per-mode import declarations.
//! - [`frames`] — `BlockLabel` / `TagFrame` / `UnwindFrame` + their
//! push/pop/lookup methods (BLOCK / TAGBODY / UNWIND-PROTECT bookkeeping).
//! - [`globals`] — the `$t` singleton global (ADR-0033).
//! - [`host_fn`] — host-fn import registration + lookup.
//! - [`types`] — concrete + abstract heap-type accessors
//! (`ratio_ref`, `commodity_ref`, `pair_ref`, `anyref`, ...).
//! - [`registry`] — section-level registration: types, imports,
//! functions, exports, data segments, and the local-pool
//! allocator.
//! - [`pair`] — `$pair`/`$i8_array` setup + entity allocators +
//! string-eq helper.
//! - [`index`] — range-checked i31 boxing + throwing index division.
//! - [`commodity`] — commodity-arithmetic helpers
//! (`commodity_new`, `commodity_add`/sub/neg/scale/cmp/...).
//! - [`ratio`] — ratio-arithmetic helpers (`ratio_new`, `gcd`,
//! binops, comparisons).
//! `mod.rs` stays the thin cross-submodule glue: the `CompileContext` struct
//! itself, the code-section drain (`add_nomi_eval`/`add_should_apply`/
//! `add_process`), the inlining-depth guard, and `finish` (module assembly).
mod block_joins;
pub(crate) mod closure;
mod commodity;
mod commodity_compound;
mod construct;
mod entity_registry;
mod exception;
mod frames;
mod globals;
mod host_fn;
mod ids;
mod index;
pub(in crate::compiler) mod monomorph;
mod pair;
mod pair_equal;
mod ratio;
mod ratio_ops;
mod registry;
mod snapshot;
mod stats;
mod structs;
mod types;
mod unbound;
mod unit_term;
pub use globals::global_export_name;
pub use structs::{PROLOGUE_DONE_EXPORT, instance_export_name};
#[cfg(test)]
mod tests;
mod snapshot_tests;
mod globals_tests;
mod structs_tests;
mod frames_tests;
mod digest;
use std::collections::{BTreeMap, HashMap, HashSet};
use anodized::spec;
use tracing::debug;
use wasm_encoder::{
CodeSection, DataCountSection, DataSection, ElementSection, Elements, ExportSection, Function,
FunctionSection, GlobalSection, ImportSection, Instruction, MemorySection, Module, TagSection,
TypeSection, ValType,
};
use super::layout::OutputSerializer;
use super::stats::CompileStats;
use crate::ast::WasmType;
use crate::error::Result;
pub(crate) use closure::{AnyCallHelper, CLOSURE_SIG_FIELD, CLOSURE_SITE_FIELD, ClosureSig};
pub(in crate::compiler) use frames::{BlockLabel, TagEntry, TagFrame, UnwindFrame};
pub(crate) use pair_equal::ShapeCompare;
pub(crate) use snapshot::ContextSnapshot;
pub(crate) use unbound::LOST_FLAG;
#[derive(Debug, Clone)]
pub(crate) struct HostFnEntry {
pub func_idx: u32,
pub params: Vec<WasmType>,
pub result: Option<WasmType>,
}
/// Base index for user-allocatable locals (after pre-allocated slots)
pub const LOCAL_POOL_BASE: u32 = 6;
/// One pool local. `ty` is the value type the body sees; a `cell` holds that
/// value in a shared `$cell_<ty>` struct of the given type index instead.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct LocalSlot {
pub ty: WasmType,
pub idx: u32,
pub cell: Option<u32>,
pub struct CompileContext {
pub(in crate::compiler::context) types: TypeSection,
pub(in crate::compiler::context) imports: ImportSection,
pub(in crate::compiler::context) functions: FunctionSection,
pub(in crate::compiler::context) memories: MemorySection,
pub(in crate::compiler::context) tags: TagSection,
pub(in crate::compiler::context) globals: GlobalSection,
pub(in crate::compiler::context) global_count: u32,
pub(in crate::compiler::context) exports: ExportSection,
pub(in crate::compiler::context) data: DataSection,
pub(in crate::compiler::context) codes: CodeSection,
pub(in crate::compiler::context) data_count: u32,
pub(in crate::compiler::context) type_count: u32,
pub(in crate::compiler::context) tag_count: u32,
pub(in crate::compiler::context) import_func_count: u32,
pub(in crate::compiler::context) local_func_count: u32,
pub(in crate::compiler::context) type_cache: HashMap<Vec<ValType>, HashMap<Vec<ValType>, u32>>,
/// Maps a declared helper-function / import NAME to its wasm function index.
/// Written during the declare phase; read once by [`Self::resolve_ids`] to
/// populate the typed `WasmIds`, and by `export_func` /
/// `declared_func_index`. Emit code never touches it — it reads `self.ids`.
pub(in crate::compiler::context) func_names: HashMap<String, u32>,
pub(in crate::compiler::context) host_fns: HashMap<String, HostFnEntry>,
pub(in crate::compiler::context) pending_helpers: Vec<Function>,
pub(in crate::compiler::context) next_local: u32,
pub(in crate::compiler::context) local_types: Vec<LocalSlot>,
pub(in crate::compiler::context) serializer: OutputSerializer,
pub(in crate::compiler::context) closures: closure::ClosureRegistry,
pub(in crate::compiler::context) declared_funcs: Vec<u32>,
pub(in crate::compiler::context) monomorphs: monomorph::MonomorphCache,
pub(in crate::compiler::context) nomi_error_tag: Option<u32>,
/// Resolved wasm fn/type indices for emit. Seeded poison
/// ([`ids::WasmIds::UNRESOLVED`]) in `new_skeleton`, overwritten with the
/// real indices by `resolve_ids` at the end of each public constructor —
/// before any emit can read it. See `context/ids.rs`.
pub(in crate::compiler) ids: ids::WasmIds,
inlining_stack: Vec<String>,
inlining_set: HashSet<String>,
block_labels: Vec<BlockLabel>,
/// Ranges of `block_labels` an inlined body cannot see: those opened
/// between its function's definition and the call (ISS-179).
hidden_labels: Vec<(usize, usize)>,
/// The BLOCK names open in the code a function body is compiled out of,
/// which a `RETURN-FROM` inside it cannot reach.
outer_labels: Vec<String>,
tag_frames: Vec<TagFrame>,
unwind_frames: Vec<UnwindFrame>,
block_joins: block_joins::BlockJoins,
/// The compilation's counters. Outside `ContextSnapshot`, so a
/// rolled-back trial still counts.
stats: CompileStats,
/// What a read of each cell of the unit checks, by global: made at the
/// unit's start, before any trial, so outside `ContextSnapshot`.
read_checks: HashMap<u32, unbound::UnboundCell>,
/// The wasm global of each struct layout this compilation has used.
struct_layouts: structs::LayoutGlobals,
/// The wasm global of the instance serial counter, once allocated.
struct_serial: Option<u32>,
/// The serial the counter starts at: past every instance the session holds.
struct_serial_base: u32,
/// The wasm global of each session instance, by serial.
instance_globals: BTreeMap<u32, u32>,
/// The function that runs the instance prologue once, once it is built.
instances_init: Option<u32>,
impl CompileContext {
pub fn add_nomi_eval(&mut self, f: Function) {
debug!("emitting nomi-eval function");
self.codes.function(&f);
for helper in self.pending_helpers.drain(..) {
self.codes.function(&helper);
/// Emits `should_apply`, then drains the first `bootstrap_count`
/// queued helpers so their code-section slots line up with the
/// function-section slots reserved between `should_apply` and
/// `process` during context bootstrap. Helpers the user's `process`
/// body queued (e.g. a real wasm fn for a `(lambda ...)` value) stay
/// in the queue until [`add_process`] drains them after the
/// `process` body lands. Pass `usize::MAX` (or any value `>=` the
/// pending count) to drain everything — the helper bootstrap path
/// in tests goes that route.
pub fn add_should_apply(&mut self, f: Function, bootstrap_count: usize) {
debug!(
bootstrap_count,
"emitting should_apply with split-drain helpers"
);
let take = bootstrap_count.min(self.pending_helpers.len());
for helper in self.pending_helpers.drain(..take) {
pub fn pending_helper_count(&self) -> usize {
self.pending_helpers.len()
pub fn default_should_apply() -> Function {
let mut f = Function::new([]);
f.instruction(&Instruction::I32Const(1));
f.instruction(&Instruction::End);
f
pub fn add_process(&mut self, f: Function) {
debug!("emitting process function");
// User code in `process` may register lambda / defun helpers
// whose function-section indices land *after* `process`. Their
// bodies have to appear in the code section in the matching
// order, so drain after the `process` body — `add_should_apply`
// earlier already drained the bootstrap-time helpers
// (ratio/commodity/pair) that were registered before `process`.
/// Tracks active defun / lambda inlining frames so a body that
/// re-enters itself can be flagged before the compiler stack
/// overflows. The inline-call path is load-bearing const-fold (see
/// ADR-0027 / Tier 1.5 reframe): recursion terminates only because
/// each walk reduces args toward a base case via constant folding.
/// With a runtime arg the walk re-enters the same body without
/// progress; the runtime-call path that would terminate the
/// recursion at one level is the next-tier follow-up.
pub(in crate::compiler) fn is_inlining(&self, name: &str) -> bool {
self.inlining_set.contains(name)
/// Push an inlining frame. The codegen inline path
/// (`compile_lambda_call`) walks a defun body recursively; const
/// recursion with no foldable base case (or simply very deep
/// const-folded recursion) would otherwise recurse the compiler's
/// native stack until it overflows. Charged entirely against the
/// SHARED compile-time recursion budget (macro expansion / eval-time
/// inlining / AND-OR-COND runtime-guard nesting all share the same one
/// ceiling — see `SymbolTable::enter_shared_recursion`) rather than a
/// separate ceiling of its own — the codegen-path analogue of
/// `SymbolTable::enter_inline`.
#[spec(
maintains: [
self.inlining_stack.iter().all(|n| self.inlining_set.contains(n)),
self.inlining_set.iter().all(|n| self.inlining_stack.contains(n)),
],
captures: before = self.inlining_stack.len(),
ensures: |ref output| [
self.inlining_stack.len() == before + usize::from(output.is_ok()),
output.is_err() || self.inlining_stack.last().is_some_and(|top| top == name),
)]
pub(in crate::compiler) fn push_inlining_frame(
&mut self,
symbols: &mut crate::runtime::SymbolTable,
name: &str,
) -> Result<()> {
symbols.enter_shared_recursion()?;
self.inlining_stack.push(name.to_string());
self.inlining_set.insert(name.to_string());
Ok(())
requires: self.inlining_stack.last().is_some_and(|top| top == name),
pub(in crate::compiler) fn pop_inlining_frame(
if self.inlining_stack.pop().is_some() && !self.inlining_stack.iter().any(|n| n == name) {
self.inlining_set.remove(name);
symbols.exit_shared_recursion()
/// Records `func_idx` as ref-able via `ref.func`. Wasm requires every
/// `ref.func` operand to appear in either an import/export, a global
/// initializer, or a declared element segment — lambda helpers are
/// none of those, so we collect their indices and emit a single
/// declared-funcref segment in [`Self::finish`].
pub(crate) fn declare_funcref(&mut self, func_idx: u32) {
if !self.declared_funcs.contains(&func_idx) {
self.declared_funcs.push(func_idx);
pub fn finish(self) -> Vec<u8> {
debug!(data_segments = self.data_count, "assembling WASM module");
let mut module = Module::new();
module.section(&self.types);
module.section(&self.imports);
module.section(&self.functions);
module.section(&self.memories);
// Tag section (ID 13) sits after Memory and before Export in the
// exception-handling proposal's section order.
module.section(&self.tags);
// The `$t` singleton global (ADR-0033) sits after Tags and before
// Export — the Fable-reviewed section order the Phase 3 module test
// pins (wasmtime rejects a module with sections out of order).
module.section(&self.globals);
module.section(&self.exports);
let mut elements = ElementSection::new();
if !self.declared_funcs.is_empty() {
elements.declared(Elements::Functions(std::borrow::Cow::Borrowed(
&self.declared_funcs,
)));
module.section(&elements);
module.section(&DataCountSection {
count: self.data_count,
});
module.section(&self.codes);
module.section(&self.data);
module.finish()