1
//! `CompileContext` — the per-module wasm assembly state shared across
2
//! every codegen path.
3
//!
4
//! Split across topic-focused submodules so each file stays under the
5
//! ~500-line CLAUDE.md guideline:
6
//! - [`construct`] — the two public constructors (`new`, `new_eval_with_host_fns`),
7
//!   `new_skeleton`, and the per-mode import declarations.
8
//! - [`frames`] — `BlockLabel` / `TagFrame` / `UnwindFrame` + their
9
//!   push/pop/lookup methods (BLOCK / TAGBODY / UNWIND-PROTECT bookkeeping).
10
//! - [`globals`] — the `$t` singleton global (ADR-0033).
11
//! - [`host_fn`] — host-fn import registration + lookup.
12
//! - [`types`] — concrete + abstract heap-type accessors
13
//!   (`ratio_ref`, `commodity_ref`, `pair_ref`, `anyref`, ...).
14
//! - [`registry`] — section-level registration: types, imports,
15
//!   functions, exports, data segments, and the local-pool
16
//!   allocator.
17
//! - [`pair`] — `$pair`/`$i8_array` setup + entity allocators +
18
//!   string-eq helper.
19
//! - [`index`] — range-checked i31 boxing + throwing index division.
20
//! - [`commodity`] — commodity-arithmetic helpers
21
//!   (`commodity_new`, `commodity_add`/sub/neg/scale/cmp/...).
22
//! - [`ratio`] — ratio-arithmetic helpers (`ratio_new`, `gcd`,
23
//!   binops, comparisons).
24
//!
25
//! `mod.rs` stays the thin cross-submodule glue: the `CompileContext` struct
26
//! itself, the code-section drain (`add_nomi_eval`/`add_should_apply`/
27
//! `add_process`), the inlining-depth guard, and `finish` (module assembly).
28

            
29
mod block_joins;
30
pub(crate) mod closure;
31
mod commodity;
32
mod commodity_compound;
33
mod construct;
34
mod entity_registry;
35
mod exception;
36
mod frames;
37
mod globals;
38
mod host_fn;
39
mod ids;
40
mod index;
41
pub(in crate::compiler) mod monomorph;
42
mod pair;
43
mod pair_equal;
44
mod ratio;
45
mod ratio_ops;
46
mod registry;
47
mod snapshot;
48
mod stats;
49
mod structs;
50
mod types;
51
mod unbound;
52
mod unit_term;
53

            
54
pub use globals::global_export_name;
55
pub use structs::{PROLOGUE_DONE_EXPORT, instance_export_name};
56

            
57
#[cfg(test)]
58
mod tests;
59

            
60
#[cfg(test)]
61
mod snapshot_tests;
62

            
63
#[cfg(test)]
64
mod globals_tests;
65

            
66
#[cfg(test)]
67
mod structs_tests;
68

            
69
#[cfg(test)]
70
mod frames_tests;
71

            
72
#[cfg(test)]
73
mod digest;
74

            
75
use std::collections::{BTreeMap, HashMap, HashSet};
76

            
77
use anodized::spec;
78
use tracing::debug;
79
use wasm_encoder::{
80
    CodeSection, DataCountSection, DataSection, ElementSection, Elements, ExportSection, Function,
81
    FunctionSection, GlobalSection, ImportSection, Instruction, MemorySection, Module, TagSection,
82
    TypeSection, ValType,
83
};
84

            
85
use super::layout::OutputSerializer;
86
use super::stats::CompileStats;
87
use crate::ast::WasmType;
88
use crate::error::Result;
89

            
90
pub(crate) use closure::{AnyCallHelper, CLOSURE_SIG_FIELD, CLOSURE_SITE_FIELD, ClosureSig};
91
pub(in crate::compiler) use frames::{BlockLabel, TagEntry, TagFrame, UnwindFrame};
92
pub(crate) use pair_equal::ShapeCompare;
93
pub(crate) use snapshot::ContextSnapshot;
94
pub(crate) use unbound::LOST_FLAG;
95

            
96
#[derive(Debug, Clone)]
97
pub(crate) struct HostFnEntry {
98
    pub func_idx: u32,
99
    pub params: Vec<WasmType>,
100
    pub result: Option<WasmType>,
101
}
102

            
103
/// Base index for user-allocatable locals (after pre-allocated slots)
104
pub const LOCAL_POOL_BASE: u32 = 6;
105

            
106
/// One pool local. `ty` is the value type the body sees; a `cell` holds that
107
/// value in a shared `$cell_<ty>` struct of the given type index instead.
108
#[derive(Debug, Clone, Copy, PartialEq)]
109
pub(crate) struct LocalSlot {
110
    pub ty: WasmType,
111
    pub idx: u32,
112
    pub cell: Option<u32>,
113
}
114

            
115
pub struct CompileContext {
116
    pub(in crate::compiler::context) types: TypeSection,
117
    pub(in crate::compiler::context) imports: ImportSection,
118
    pub(in crate::compiler::context) functions: FunctionSection,
119
    pub(in crate::compiler::context) memories: MemorySection,
120
    pub(in crate::compiler::context) tags: TagSection,
121
    pub(in crate::compiler::context) globals: GlobalSection,
122
    pub(in crate::compiler::context) global_count: u32,
123
    pub(in crate::compiler::context) exports: ExportSection,
124
    pub(in crate::compiler::context) data: DataSection,
125
    pub(in crate::compiler::context) codes: CodeSection,
126
    pub(in crate::compiler::context) data_count: u32,
127
    pub(in crate::compiler::context) type_count: u32,
128
    pub(in crate::compiler::context) tag_count: u32,
129
    pub(in crate::compiler::context) import_func_count: u32,
130
    pub(in crate::compiler::context) local_func_count: u32,
131
    pub(in crate::compiler::context) type_cache: HashMap<Vec<ValType>, HashMap<Vec<ValType>, u32>>,
132
    /// Maps a declared helper-function / import NAME to its wasm function index.
133
    /// Written during the declare phase; read once by [`Self::resolve_ids`] to
134
    /// populate the typed `WasmIds`, and by `export_func` /
135
    /// `declared_func_index`. Emit code never touches it — it reads `self.ids`.
136
    pub(in crate::compiler::context) func_names: HashMap<String, u32>,
137
    pub(in crate::compiler::context) host_fns: HashMap<String, HostFnEntry>,
138
    pub(in crate::compiler::context) pending_helpers: Vec<Function>,
139
    pub(in crate::compiler::context) next_local: u32,
140
    pub(in crate::compiler::context) local_types: Vec<LocalSlot>,
141
    pub(in crate::compiler::context) serializer: OutputSerializer,
142
    pub(in crate::compiler::context) closures: closure::ClosureRegistry,
143
    pub(in crate::compiler::context) declared_funcs: Vec<u32>,
144
    pub(in crate::compiler::context) monomorphs: monomorph::MonomorphCache,
145
    pub(in crate::compiler::context) nomi_error_tag: Option<u32>,
146
    /// Resolved wasm fn/type indices for emit. Seeded poison
147
    /// ([`ids::WasmIds::UNRESOLVED`]) in `new_skeleton`, overwritten with the
148
    /// real indices by `resolve_ids` at the end of each public constructor —
149
    /// before any emit can read it. See `context/ids.rs`.
150
    pub(in crate::compiler) ids: ids::WasmIds,
151
    inlining_stack: Vec<String>,
152
    inlining_set: HashSet<String>,
153
    block_labels: Vec<BlockLabel>,
154
    /// Ranges of `block_labels` an inlined body cannot see: those opened
155
    /// between its function's definition and the call (ISS-179).
156
    hidden_labels: Vec<(usize, usize)>,
157
    /// The BLOCK names open in the code a function body is compiled out of,
158
    /// which a `RETURN-FROM` inside it cannot reach.
159
    outer_labels: Vec<String>,
160
    tag_frames: Vec<TagFrame>,
161
    unwind_frames: Vec<UnwindFrame>,
162
    block_joins: block_joins::BlockJoins,
163
    /// The compilation's counters. Outside `ContextSnapshot`, so a
164
    /// rolled-back trial still counts.
165
    stats: CompileStats,
166
    /// What a read of each cell of the unit checks, by global: made at the
167
    /// unit's start, before any trial, so outside `ContextSnapshot`.
168
    read_checks: HashMap<u32, unbound::UnboundCell>,
169
    /// The wasm global of each struct layout this compilation has used.
170
    struct_layouts: structs::LayoutGlobals,
171
    /// The wasm global of the instance serial counter, once allocated.
172
    struct_serial: Option<u32>,
173
    /// The serial the counter starts at: past every instance the session holds.
174
    struct_serial_base: u32,
175
    /// The wasm global of each session instance, by serial.
176
    instance_globals: BTreeMap<u32, u32>,
177
    /// The function that runs the instance prologue once, once it is built.
178
    instances_init: Option<u32>,
179
}
180

            
181
impl CompileContext {
182
683541
    pub fn add_nomi_eval(&mut self, f: Function) {
183
683541
        debug!("emitting nomi-eval function");
184
683541
        self.codes.function(&f);
185

            
186
683541
        for helper in self.pending_helpers.drain(..) {
187
49936437
            self.codes.function(&helper);
188
        }
189
683541
    }
190

            
191
    /// Emits `should_apply`, then drains the first `bootstrap_count`
192
    /// queued helpers so their code-section slots line up with the
193
    /// function-section slots reserved between `should_apply` and
194
    /// `process` during context bootstrap. Helpers the user's `process`
195
    /// body queued (e.g. a real wasm fn for a `(lambda ...)` value) stay
196
    /// in the queue until [`add_process`] drains them after the
197
    /// `process` body lands. Pass `usize::MAX` (or any value `>=` the
198
    /// pending count) to drain everything — the helper bootstrap path
199
    /// in tests goes that route.
200
1457593
    pub fn add_should_apply(&mut self, f: Function, bootstrap_count: usize) {
201
1457593
        debug!(
202
            bootstrap_count,
203
            "emitting should_apply with split-drain helpers"
204
        );
205
1457593
        self.codes.function(&f);
206

            
207
1457593
        let take = bootstrap_count.min(self.pending_helpers.len());
208
1457593
        for helper in self.pending_helpers.drain(..take) {
209
103489107
            self.codes.function(&helper);
210
        }
211
1457593
    }
212

            
213
1616935
    pub fn pending_helper_count(&self) -> usize {
214
1616935
        self.pending_helpers.len()
215
1616935
    }
216

            
217
1444063
    pub fn default_should_apply() -> Function {
218
1444063
        let mut f = Function::new([]);
219
1444063
        f.instruction(&Instruction::I32Const(1));
220
1444063
        f.instruction(&Instruction::End);
221
1444063
        f
222
1444063
    }
223

            
224
1457593
    pub fn add_process(&mut self, f: Function) {
225
1457593
        debug!("emitting process function");
226
1457593
        self.codes.function(&f);
227

            
228
        // User code in `process` may register lambda / defun helpers
229
        // whose function-section indices land *after* `process`. Their
230
        // bodies have to appear in the code section in the matching
231
        // order, so drain after the `process` body — `add_should_apply`
232
        // earlier already drained the bootstrap-time helpers
233
        // (ratio/commodity/pair) that were registered before `process`.
234
1457593
        for helper in self.pending_helpers.drain(..) {
235
3193658
            self.codes.function(&helper);
236
        }
237
1457593
    }
238

            
239
    /// Tracks active defun / lambda inlining frames so a body that
240
    /// re-enters itself can be flagged before the compiler stack
241
    /// overflows. The inline-call path is load-bearing const-fold (see
242
    /// ADR-0027 / Tier 1.5 reframe): recursion terminates only because
243
    /// each walk reduces args toward a base case via constant folding.
244
    /// With a runtime arg the walk re-enters the same body without
245
    /// progress; the runtime-call path that would terminate the
246
    /// recursion at one level is the next-tier follow-up.
247
829057
    pub(in crate::compiler) fn is_inlining(&self, name: &str) -> bool {
248
829057
        self.inlining_set.contains(name)
249
829057
    }
250

            
251
    /// Push an inlining frame. The codegen inline path
252
    /// (`compile_lambda_call`) walks a defun body recursively; const
253
    /// recursion with no foldable base case (or simply very deep
254
    /// const-folded recursion) would otherwise recurse the compiler's
255
    /// native stack until it overflows. Charged entirely against the
256
    /// SHARED compile-time recursion budget (macro expansion / eval-time
257
    /// inlining / AND-OR-COND runtime-guard nesting all share the same one
258
    /// ceiling — see `SymbolTable::enter_shared_recursion`) rather than a
259
    /// separate ceiling of its own — the codegen-path analogue of
260
    /// `SymbolTable::enter_inline`.
261
    #[spec(
262
        maintains: [
263
1011880
            self.inlining_stack.iter().all(|n| self.inlining_set.contains(n)),
264
884138
            self.inlining_set.iter().all(|n| self.inlining_stack.contains(n)),
265
        ],
266
442069
        captures: before = self.inlining_stack.len(),
267
        ensures: |ref output| [
268
442069
            self.inlining_stack.len() == before + usize::from(output.is_ok()),
269
442069
            output.is_err() || self.inlining_stack.last().is_some_and(|top| top == name),
270
        ],
271
    )]
272
442069
    pub(in crate::compiler) fn push_inlining_frame(
273
442069
        &mut self,
274
442069
        symbols: &mut crate::runtime::SymbolTable,
275
442069
        name: &str,
276
442069
    ) -> Result<()> {
277
442069
        symbols.enter_shared_recursion()?;
278
441650
        self.inlining_stack.push(name.to_string());
279
441650
        self.inlining_set.insert(name.to_string());
280
441650
        Ok(())
281
442069
    }
282

            
283
    #[spec(
284
441650
        requires: self.inlining_stack.last().is_some_and(|top| top == name),
285
        maintains: [
286
991768
            self.inlining_stack.iter().all(|n| self.inlining_set.contains(n)),
287
883300
            self.inlining_set.iter().all(|n| self.inlining_stack.contains(n)),
288
        ],
289
    )]
290
441650
    pub(in crate::compiler) fn pop_inlining_frame(
291
441650
        &mut self,
292
441650
        symbols: &mut crate::runtime::SymbolTable,
293
441650
        name: &str,
294
441650
    ) -> Result<()> {
295
441650
        if self.inlining_stack.pop().is_some() && !self.inlining_stack.iter().any(|n| n == name) {
296
424380
            self.inlining_set.remove(name);
297
17270
        }
298
441650
        symbols.exit_shared_recursion()
299
441650
    }
300

            
301
    /// Records `func_idx` as ref-able via `ref.func`. Wasm requires every
302
    /// `ref.func` operand to appear in either an import/export, a global
303
    /// initializer, or a declared element segment — lambda helpers are
304
    /// none of those, so we collect their indices and emit a single
305
    /// declared-funcref segment in [`Self::finish`].
306
209942
    pub(crate) fn declare_funcref(&mut self, func_idx: u32) {
307
209942
        if !self.declared_funcs.contains(&func_idx) {
308
209942
            self.declared_funcs.push(func_idx);
309
        }
310
209942
    }
311

            
312
2141134
    pub fn finish(self) -> Vec<u8> {
313
2141134
        debug!(data_segments = self.data_count, "assembling WASM module");
314
2141134
        let mut module = Module::new();
315
2141134
        module.section(&self.types);
316
2141134
        module.section(&self.imports);
317
2141134
        module.section(&self.functions);
318
2141134
        module.section(&self.memories);
319
        // Tag section (ID 13) sits after Memory and before Export in the
320
        // exception-handling proposal's section order.
321
2141134
        module.section(&self.tags);
322
        // The `$t` singleton global (ADR-0033) sits after Tags and before
323
        // Export — the Fable-reviewed section order the Phase 3 module test
324
        // pins (wasmtime rejects a module with sections out of order).
325
2141134
        module.section(&self.globals);
326
2141134
        module.section(&self.exports);
327
2141134
        let mut elements = ElementSection::new();
328
2141134
        if !self.declared_funcs.is_empty() {
329
146789
            elements.declared(Elements::Functions(std::borrow::Cow::Borrowed(
330
146789
                &self.declared_funcs,
331
146789
            )));
332
146789
            module.section(&elements);
333
1994345
        }
334
2141134
        module.section(&DataCountSection {
335
2141134
            count: self.data_count,
336
2141134
        });
337
2141134
        module.section(&self.codes);
338
2141134
        module.section(&self.data);
339
2141134
        module.finish()
340
2141134
    }
341
}