1
pub(crate) mod binder_key;
2
pub(crate) mod budget;
3
mod context;
4
pub(crate) mod datum;
5
mod emit;
6
pub(crate) mod expr;
7
pub(crate) mod join;
8
mod layout;
9
mod native;
10
mod observations;
11
mod recompile;
12
mod settle;
13
pub mod special;
14
pub(crate) mod stats;
15

            
16
use tracing::debug;
17

            
18
use crate::ast::{Expr, Program, WasmType};
19
use crate::error::{Error, Result};
20
use crate::host_fn::HostFnSpec;
21
use crate::runtime::SymbolTable;
22

            
23
pub(crate) use native::registered_names as native_names;
24

            
25
use context::CompileContext;
26
pub use context::{PROLOGUE_DONE_EXPORT, global_export_name, instance_export_name};
27
use emit::FunctionEmitter;
28
use stats::CompileStats;
29

            
30
/// Selects which export shape the compiler emits.
31
///
32
/// `Script` keeps the entity-script surface (`should_apply` + `process`
33
/// exports, env.* imports) the script executor consumes. `Eval` emits a
34
/// `nomi-eval` export that runs the program and returns the final value
35
/// via the function's `(ref null any)` return slot; the host decodes it
36
/// with `scripting::runtime::decode_eval_result`.
37
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38
pub enum CompileMode {
39
    Script,
40
    Eval,
41
}
42

            
43
pub struct Compiler {
44
    host_fns: Vec<HostFnSpec>,
45
    stats: CompileStats,
46
}
47

            
48
impl Compiler {
49
    #[must_use]
50
587771
    pub fn new() -> Self {
51
587771
        Self::with_host_fns(Vec::new())
52
587771
    }
53

            
54
    /// Builds a compiler that recognises the given host fn names in either
55
    /// mode. Each spec gets a wasm import declared in the module and an entry
56
    /// the native dispatcher consults when emitting calls.
57
    #[must_use]
58
989484
    pub fn with_host_fns(host_fns: Vec<HostFnSpec>) -> Self {
59
989484
        Self {
60
989484
            host_fns,
61
989484
            stats: CompileStats::default(),
62
989484
        }
63
989484
    }
64

            
65
1538217
    pub fn compile(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
66
1538217
        self.compile_with_mode(program, symbols, CompileMode::Script)
67
1538217
    }
68

            
69
1551321
    pub fn compile_with_mode(
70
1551321
        &mut self,
71
1551321
        program: &Program,
72
1551321
        symbols: &mut SymbolTable,
73
1551321
        mode: CompileMode,
74
1551321
    ) -> Result<Vec<u8>> {
75
1551321
        debug!(expr_count = program.exprs.len(), ?mode, "compilation start");
76
1551321
        match mode {
77
1541468
            CompileMode::Script => self.compile_script(program, symbols),
78
9853
            CompileMode::Eval => self.compile_eval(program, symbols),
79
        }
80
1551321
    }
81

            
82
1541468
    fn compile_script(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
83
1541468
        self.settle(
84
1541468
            program,
85
1541468
            symbols,
86
1541468
            CompileContext::new_with_host_fns,
87
1616929
            |this, ctx, program, symbols| this.lower_script(ctx, program, symbols),
88
        )
89
        .map(|(wasm, ())| wasm)
90
1541468
    }
91

            
92
    /// Compiles the unit until its homes settle; `lower` fills the context.
93
2262238
    fn settle<T>(
94
2262238
        &mut self,
95
2262238
        program: &Program,
96
2262238
        symbols: &mut SymbolTable,
97
2262238
        new_ctx: fn(&[HostFnSpec]) -> Result<CompileContext>,
98
2262238
        lower: impl Fn(&Self, &mut CompileContext, &Program, &mut SymbolTable) -> Result<T>,
99
2262238
    ) -> Result<(Vec<u8>, T)> {
100
2262238
        self.stats = CompileStats::default();
101
2262238
        symbols.reset_budget();
102
2352271
        settle::settle_homes(symbols, |symbols| {
103
2352271
            symbols.reset_measurements();
104
2352271
            symbols.forget_unit_closures();
105
2352271
            let mut ctx = new_ctx(&self.host_fns)?;
106
2352271
            let lowered = lower(self, &mut ctx, program, symbols);
107
2352271
            self.record_stats(ctx.compile_stats(), symbols);
108
2352271
            let value = lowered?;
109
2141122
            let closures = ctx.take_closure_sources();
110
2141122
            let wasm = ctx.finish();
111
2141122
            validate_module(&wasm)?;
112
2141122
            symbols.finish_unit(closures);
113
2141122
            debug!(wasm_size = wasm.len(), "compilation complete");
114
2141122
            Ok((wasm, value))
115
2352271
        })
116
2262238
    }
117

            
118
1616929
    fn lower_script(
119
1616929
        &self,
120
1616929
        ctx: &mut CompileContext,
121
1616929
        program: &Program,
122
1616929
        symbols: &mut SymbolTable,
123
1616929
    ) -> Result<()> {
124
        // Snapshot how many helpers (gcd / ratio_* / commodity_* / pair_*)
125
        // were queued during context bootstrap; these correspond to the
126
        // function-section slots between `should_apply` and `process`,
127
        // so their bodies must drain *with* `should_apply`'s emit. User
128
        // code inside `process` may queue more helpers (e.g. a real
129
        // wasm fn for a `(lambda ...)` value); those slots land *after*
130
        // `process` and have to drain *with* `process`'s emit so the
131
        // code-section ordering matches the function-section.
132
1616929
        let bootstrap_helper_count = ctx.pending_helper_count();
133

            
134
1616929
        let mut process = FunctionEmitter::new();
135

            
136
        // Wrap the body in the Tier 3 boundary `try_table` so an uncaught
137
        // `(error)` throw bridges to `__nomi_raise` (ADR-0026). `process`
138
        // returns void.
139
1616929
        ctx.emit_boundary_wrapper(&mut process, None, |ctx, emit| {
140
            // output_base = get_output_offset()
141
1616929
            emit.call(ctx.ids.get_output_offset()?);
142
1616929
            emit.local_set(expr::LOCAL_OUTPUT_BASE);
143
1616929
            expr::compile_program(ctx, emit, symbols, program)
144
1616929
        })?;
145

            
146
1458206
        let process_locals = ctx.build_locals_declaration()?;
147
1458206
        ctx.reset_locals(symbols);
148

            
149
1458206
        let should_apply = self.build_should_apply(ctx, symbols)?;
150
1457582
        expr::fill_any_call_helpers(ctx)?;
151
1457582
        ctx.add_should_apply(should_apply, bootstrap_helper_count);
152
1457582
        ctx.add_process(process.finish(&process_locals)?);
153
1457582
        Ok(())
154
1616929
    }
155

            
156
9853
    fn compile_eval(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
157
9853
        let (wasm, _ty) = self.compile_eval_with_type(program, symbols)?;
158
9018
        Ok(wasm)
159
9853
    }
160

            
161
    /// Compiles `program` in eval mode and returns the wasm bytes paired
162
    /// with the form's final result type. `None` for empty programs /
163
    /// definition-only forms (nomi-eval returns `ref.null any`); `Some(ty)`
164
    /// for any other terminator. Hosts decode the returned anyref via the
165
    /// type hint — see `scripting::runtime::decode_eval_result`.
166
720770
    pub fn compile_eval_with_type(
167
720770
        &mut self,
168
720770
        program: &Program,
169
720770
        symbols: &mut SymbolTable,
170
720770
    ) -> Result<(Vec<u8>, Option<WasmType>)> {
171
720770
        self.settle(
172
720770
            program,
173
720770
            symbols,
174
720770
            CompileContext::new_eval_with_host_fns,
175
735342
            |_, ctx, program, symbols| Self::lower_eval(ctx, program, symbols),
176
        )
177
720770
    }
178

            
179
735342
    fn lower_eval(
180
735342
        ctx: &mut CompileContext,
181
735342
        program: &Program,
182
735342
        symbols: &mut SymbolTable,
183
735342
    ) -> Result<Option<WasmType>> {
184
735342
        let mut emit = FunctionEmitter::new();
185

            
186
        // `nomi-eval` returns anyref. The boundary wrapper bridges an
187
        // uncaught `(error)` to `__nomi_raise` (ADR-0026). The body's
188
        // final result type is computed inside the closure and surfaced
189
        // out for the host's `decode_eval_result` hint.
190
735342
        let mut result_ty: Option<WasmType> = None;
191
735342
        ctx.emit_boundary_wrapper(&mut emit, Some(WasmType::AnyRef), |ctx, emit| {
192
735342
            if program.exprs.is_empty() {
193
209
                expr::prepare_unit(symbols, &program.exprs, CompileMode::Eval)?;
194
209
                emit.ref_null_any();
195
209
                return Ok(());
196
735133
            }
197
735133
            expr::begin_unit(ctx, emit, symbols, &program.exprs, CompileMode::Eval)?;
198
734694
            result_ty = Self::compile_eval_forms(ctx, emit, symbols, program)?;
199
683331
            Ok(())
200
735342
        })?;
201

            
202
683540
        let locals = ctx.build_locals_declaration()?;
203
683540
        ctx.reset_locals(symbols);
204
683540
        expr::fill_any_call_helpers(ctx)?;
205
683540
        ctx.add_nomi_eval(emit.finish(&locals)?);
206
683540
        Ok(result_ty)
207
735342
    }
208

            
209
    /// Compiles the forms of an eval unit; the final type is `None` for a
210
    /// definition.
211
734694
    fn compile_eval_forms(
212
734694
        ctx: &mut CompileContext,
213
734694
        emit: &mut FunctionEmitter,
214
734694
        symbols: &mut SymbolTable,
215
734694
        program: &Program,
216
734694
    ) -> Result<Option<WasmType>> {
217
734694
        let Some((last, init)) = program.exprs.split_last() else {
218
            return Err(Error::Compile("empty eval unit".into()));
219
        };
220
734694
        for expr in init {
221
29150
            expr::compile_for_effect(ctx, emit, symbols, expr)?;
222
        }
223
734558
        if is_definition_form(last) {
224
30014
            expr::compile_for_effect(ctx, emit, symbols, last)?;
225
30005
            emit.ref_null_any();
226
30005
            return Ok(None);
227
704544
        }
228
704544
        let ty = expr::compile_for_stack(ctx, emit, symbols, last)?;
229
653326
        emit_to_anyref(ctx, emit, ty);
230
653326
        Ok(Some(ty))
231
734694
    }
232

            
233
    /// Adds the counters of the attempt that just ended to the unit's, with
234
    /// the measurements the symbol table's shared budget collected.
235
2352271
    fn record_stats(&mut self, stats: CompileStats, symbols: &SymbolTable) {
236
2352271
        let measured = symbols.measurements();
237
2352271
        let (stored_globals, possibly_storing, opaque_macro_uses) = measured.store_scan();
238
2352271
        self.stats = self.stats.after_attempt(CompileStats {
239
2352271
            folds: measured.folds(),
240
2352271
            probe_walks: measured.walks(),
241
2352271
            macro_bodies_reading_globals: measured.macro_global_reads(),
242
2352271
            stored_globals,
243
2352271
            possibly_storing,
244
2352271
            opaque_macro_uses,
245
2352271
            ..stats
246
2352271
        });
247
2352271
        debug!(
248
            folds = self.stats.folds,
249
            macro_bodies_reading_globals = self.stats.macro_bodies_reading_globals,
250
            "compile stats"
251
        );
252
2352271
    }
253

            
254
1458206
    fn build_should_apply(
255
1458206
        &self,
256
1458206
        ctx: &mut CompileContext,
257
1458206
        symbols: &mut SymbolTable,
258
1458206
    ) -> Result<wasm_encoder::Function> {
259
1458206
        let body = symbols
260
1458206
            .lookup("SHOULD-APPLY")
261
14154
            .and_then(|s| s.function().cloned());
262

            
263
1458206
        let Some(Expr::Lambda(params, body)) = body else {
264
1444052
            return Ok(CompileContext::default_should_apply());
265
        };
266

            
267
14154
        if !params.required.is_empty() {
268
            return Err(Error::Compile(
269
                "SHOULD-APPLY must take no parameters".to_string(),
270
            ));
271
14154
        }
272

            
273
14154
        debug!("compiling custom should-apply");
274
14154
        let mut emit = FunctionEmitter::new();
275
14154
        let mut symbols = symbols.clone();
276
14154
        symbols.enter_function_body(binder_key::function_owner(&symbols, None, &body));
277
14154
        symbols.drop_runtime_locals();
278
14154
        let symbols = &mut symbols;
279

            
280
        // Boundary wrapper bridges an uncaught `(error)` in the body to
281
        // `__nomi_raise` (ADR-0026). `should_apply` returns i32.
282
14154
        ctx.emit_boundary_wrapper(&mut emit, Some(WasmType::I32), |ctx, emit| {
283
14154
            ctx.call_instances_init(emit)?;
284
14154
            let ty = expr::compile_for_stack(ctx, emit, symbols, &body)?;
285
13530
            match ty {
286
                // Bool is the natural should-apply result (a predicate); I32
287
                // (a raw count used as truthy) is also accepted. Both are
288
                // i32-repr, so the i32 return passes through unchanged.
289
13530
                WasmType::I32 | WasmType::Bool => Ok(()),
290
                WasmType::Ratio => {
291
                    emit.struct_get(ctx.ids.ty_ratio, 0);
292
                    emit.i64_const(0);
293
                    emit.i64_ne();
294
                    Ok(())
295
                }
296
                _ => Err(Error::Compile(
297
                    "SHOULD-APPLY must return a boolean or numeric value".to_string(),
298
                )),
299
            }
300
14154
        })?;
301

            
302
13530
        let locals = ctx.build_locals_declaration()?;
303
13530
        ctx.reset_locals(symbols);
304
13530
        emit.finish(&locals)
305
1458206
    }
306
}
307

            
308
/// Promotes the form's final value (already on the wasm stack as its
309
/// declared `WasmType`) to an anyref-subtype so it satisfies nomi-eval's
310
/// `(ref null any)` return slot. Reference-typed values (ratio_ref,
311
/// commodity_ref, i8_array, pair_ref, entity_ref) are anyref subtypes
312
/// already. An index crosses exactly as a `(n, 1)` ratio struct the host
313
/// decodes by the result type — every i32 survives, and no script handler
314
/// could catch a boxing failure this late. A bool is nil-null / i31 1.
315
653326
fn emit_to_anyref(ctx: &CompileContext, emit: &mut FunctionEmitter, ty: WasmType) {
316
653326
    match ty {
317
        WasmType::I32 => {
318
251018
            emit.i64_extend_i32_s();
319
251018
            emit.call(ctx.ids.ratio_from_i64);
320
        }
321
102208
        WasmType::Bool => expr::emit_box_anyref(ctx, emit, ty),
322
        WasmType::Ratio
323
        | WasmType::Commodity
324
        | WasmType::StringRef
325
        | WasmType::SymbolRef
326
        | WasmType::PairRef(_)
327
        | WasmType::EntityRef(_)
328
        | WasmType::StructRef(_)
329
        | WasmType::Closure(_)
330
300100
        | WasmType::AnyRef => {}
331
    }
332
653326
}
333

            
334
/// The `wasmparser` feature set every module the compiler emits is checked
335
/// against: GC + function-references + exceptions, on top of the defaults.
336
/// The single source of truth for that set — `validate_module` (every
337
/// `Compiler::compile*` call) and the `codegen` integration tests'
338
/// `validate_wasm` (`tests/codegen/common.rs`, which cannot see this
339
/// module's private items and so calls this `pub` fn instead) both route
340
/// through it, rather than each keeping their own copy of the same feature
341
/// list to drift apart (ADR-0034 / plan 0011 Phase 0).
342
#[must_use]
343
2245746
pub fn wasm_validation_features() -> wasmparser::WasmFeatures {
344
    use wasmparser::WasmFeatures;
345

            
346
2245746
    WasmFeatures::default()
347
2245746
        | WasmFeatures::GC
348
2245746
        | WasmFeatures::REFERENCE_TYPES
349
2245746
        | WasmFeatures::FUNCTION_REFERENCES
350
2245746
        | WasmFeatures::EXCEPTIONS
351
2245746
}
352

            
353
/// Validates a finished module with `wasmparser`. Every module
354
/// `Compiler::compile*` produces is checked this way — a validation failure
355
/// surfaces as a structured `Error::Compile` instead of shipping wasm the
356
/// host's engine would reject (or, worse, silently misinterpret) at load
357
/// time (ADR-0034 / plan 0011 Phase 0).
358
2141122
fn validate_module(wasm: &[u8]) -> Result<()> {
359
2141122
    wasmparser::Validator::new_with_features(wasm_validation_features())
360
2141122
        .validate_all(wasm)
361
        .map_err(|e| Error::Compile(format!("emitted module failed wasm validation: {e}")))?;
362
2141122
    Ok(())
363
2141122
}
364

            
365
734558
fn is_definition_form(expr: &Expr) -> bool {
366
734558
    let Expr::List(elems) = expr else {
367
109537
        return false;
368
    };
369
625021
    let Some(Expr::Symbol(name)) = elems.first() else {
370
7
        return false;
371
    };
372
625014
    matches!(
373
625014
        name.as_str(),
374
        "DEFUN" | "DEFVAR" | "DEFMACRO" | "DEFPARAMETER" | "DEFSTRUCT"
375
    )
376
734558
}
377

            
378
impl Default for Compiler {
379
    fn default() -> Self {
380
        Self::new()
381
    }
382
}
383

            
384
#[cfg(test)]
385
#[path = "mod_tests.rs"]
386
mod tests;
387

            
388
#[cfg(test)]
389
mod behaviour_oracle;
390

            
391
#[cfg(test)]
392
mod behaviour_snapshot;
393

            
394
#[cfg(test)]
395
impl Compiler {
396
    /// The counters of the most recent compilation.
397
5915
    pub(crate) fn stats(&self) -> CompileStats {
398
5915
        self.stats
399
5915
    }
400
}
401

            
402
#[cfg(test)]
403
mod unit_budget_tests;