Skip to main content

nomiscript/compiler/
mod.rs

1pub(crate) mod binder_key;
2pub(crate) mod budget;
3mod context;
4pub(crate) mod datum;
5mod emit;
6pub(crate) mod expr;
7pub(crate) mod join;
8mod layout;
9mod native;
10mod observations;
11mod recompile;
12mod settle;
13pub mod special;
14pub(crate) mod stats;
15
16use tracing::debug;
17
18use crate::ast::{Expr, Program, WasmType};
19use crate::error::{Error, Result};
20use crate::host_fn::HostFnSpec;
21use crate::runtime::SymbolTable;
22
23pub(crate) use native::registered_names as native_names;
24
25use context::CompileContext;
26pub use context::{PROLOGUE_DONE_EXPORT, global_export_name, instance_export_name};
27use emit::FunctionEmitter;
28use 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)]
38pub enum CompileMode {
39    Script,
40    Eval,
41}
42
43pub struct Compiler {
44    host_fns: Vec<HostFnSpec>,
45    stats: CompileStats,
46}
47
48impl Compiler {
49    #[must_use]
50    pub fn new() -> Self {
51        Self::with_host_fns(Vec::new())
52    }
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    pub fn with_host_fns(host_fns: Vec<HostFnSpec>) -> Self {
59        Self {
60            host_fns,
61            stats: CompileStats::default(),
62        }
63    }
64
65    pub fn compile(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
66        self.compile_with_mode(program, symbols, CompileMode::Script)
67    }
68
69    pub fn compile_with_mode(
70        &mut self,
71        program: &Program,
72        symbols: &mut SymbolTable,
73        mode: CompileMode,
74    ) -> Result<Vec<u8>> {
75        debug!(expr_count = program.exprs.len(), ?mode, "compilation start");
76        match mode {
77            CompileMode::Script => self.compile_script(program, symbols),
78            CompileMode::Eval => self.compile_eval(program, symbols),
79        }
80    }
81
82    fn compile_script(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
83        self.settle(
84            program,
85            symbols,
86            CompileContext::new_with_host_fns,
87            |this, ctx, program, symbols| this.lower_script(ctx, program, symbols),
88        )
89        .map(|(wasm, ())| wasm)
90    }
91
92    /// Compiles the unit until its homes settle; `lower` fills the context.
93    fn settle<T>(
94        &mut self,
95        program: &Program,
96        symbols: &mut SymbolTable,
97        new_ctx: fn(&[HostFnSpec]) -> Result<CompileContext>,
98        lower: impl Fn(&Self, &mut CompileContext, &Program, &mut SymbolTable) -> Result<T>,
99    ) -> Result<(Vec<u8>, T)> {
100        self.stats = CompileStats::default();
101        symbols.reset_budget();
102        settle::settle_homes(symbols, |symbols| {
103            symbols.reset_measurements();
104            symbols.forget_unit_closures();
105            let mut ctx = new_ctx(&self.host_fns)?;
106            let lowered = lower(self, &mut ctx, program, symbols);
107            self.record_stats(ctx.compile_stats(), symbols);
108            let value = lowered?;
109            let closures = ctx.take_closure_sources();
110            let wasm = ctx.finish();
111            validate_module(&wasm)?;
112            symbols.finish_unit(closures);
113            debug!(wasm_size = wasm.len(), "compilation complete");
114            Ok((wasm, value))
115        })
116    }
117
118    fn lower_script(
119        &self,
120        ctx: &mut CompileContext,
121        program: &Program,
122        symbols: &mut SymbolTable,
123    ) -> 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        let bootstrap_helper_count = ctx.pending_helper_count();
133
134        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        ctx.emit_boundary_wrapper(&mut process, None, |ctx, emit| {
140            // output_base = get_output_offset()
141            emit.call(ctx.ids.get_output_offset()?);
142            emit.local_set(expr::LOCAL_OUTPUT_BASE);
143            expr::compile_program(ctx, emit, symbols, program)
144        })?;
145
146        let process_locals = ctx.build_locals_declaration()?;
147        ctx.reset_locals(symbols);
148
149        let should_apply = self.build_should_apply(ctx, symbols)?;
150        expr::fill_any_call_helpers(ctx)?;
151        ctx.add_should_apply(should_apply, bootstrap_helper_count);
152        ctx.add_process(process.finish(&process_locals)?);
153        Ok(())
154    }
155
156    fn compile_eval(&mut self, program: &Program, symbols: &mut SymbolTable) -> Result<Vec<u8>> {
157        let (wasm, _ty) = self.compile_eval_with_type(program, symbols)?;
158        Ok(wasm)
159    }
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    pub fn compile_eval_with_type(
167        &mut self,
168        program: &Program,
169        symbols: &mut SymbolTable,
170    ) -> Result<(Vec<u8>, Option<WasmType>)> {
171        self.settle(
172            program,
173            symbols,
174            CompileContext::new_eval_with_host_fns,
175            |_, ctx, program, symbols| Self::lower_eval(ctx, program, symbols),
176        )
177    }
178
179    fn lower_eval(
180        ctx: &mut CompileContext,
181        program: &Program,
182        symbols: &mut SymbolTable,
183    ) -> Result<Option<WasmType>> {
184        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        let mut result_ty: Option<WasmType> = None;
191        ctx.emit_boundary_wrapper(&mut emit, Some(WasmType::AnyRef), |ctx, emit| {
192            if program.exprs.is_empty() {
193                expr::prepare_unit(symbols, &program.exprs, CompileMode::Eval)?;
194                emit.ref_null_any();
195                return Ok(());
196            }
197            expr::begin_unit(ctx, emit, symbols, &program.exprs, CompileMode::Eval)?;
198            result_ty = Self::compile_eval_forms(ctx, emit, symbols, program)?;
199            Ok(())
200        })?;
201
202        let locals = ctx.build_locals_declaration()?;
203        ctx.reset_locals(symbols);
204        expr::fill_any_call_helpers(ctx)?;
205        ctx.add_nomi_eval(emit.finish(&locals)?);
206        Ok(result_ty)
207    }
208
209    /// Compiles the forms of an eval unit; the final type is `None` for a
210    /// definition.
211    fn compile_eval_forms(
212        ctx: &mut CompileContext,
213        emit: &mut FunctionEmitter,
214        symbols: &mut SymbolTable,
215        program: &Program,
216    ) -> Result<Option<WasmType>> {
217        let Some((last, init)) = program.exprs.split_last() else {
218            return Err(Error::Compile("empty eval unit".into()));
219        };
220        for expr in init {
221            expr::compile_for_effect(ctx, emit, symbols, expr)?;
222        }
223        if is_definition_form(last) {
224            expr::compile_for_effect(ctx, emit, symbols, last)?;
225            emit.ref_null_any();
226            return Ok(None);
227        }
228        let ty = expr::compile_for_stack(ctx, emit, symbols, last)?;
229        emit_to_anyref(ctx, emit, ty);
230        Ok(Some(ty))
231    }
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    fn record_stats(&mut self, stats: CompileStats, symbols: &SymbolTable) {
236        let measured = symbols.measurements();
237        let (stored_globals, possibly_storing, opaque_macro_uses) = measured.store_scan();
238        self.stats = self.stats.after_attempt(CompileStats {
239            folds: measured.folds(),
240            probe_walks: measured.walks(),
241            macro_bodies_reading_globals: measured.macro_global_reads(),
242            stored_globals,
243            possibly_storing,
244            opaque_macro_uses,
245            ..stats
246        });
247        debug!(
248            folds = self.stats.folds,
249            macro_bodies_reading_globals = self.stats.macro_bodies_reading_globals,
250            "compile stats"
251        );
252    }
253
254    fn build_should_apply(
255        &self,
256        ctx: &mut CompileContext,
257        symbols: &mut SymbolTable,
258    ) -> Result<wasm_encoder::Function> {
259        let body = symbols
260            .lookup("SHOULD-APPLY")
261            .and_then(|s| s.function().cloned());
262
263        let Some(Expr::Lambda(params, body)) = body else {
264            return Ok(CompileContext::default_should_apply());
265        };
266
267        if !params.required.is_empty() {
268            return Err(Error::Compile(
269                "SHOULD-APPLY must take no parameters".to_string(),
270            ));
271        }
272
273        debug!("compiling custom should-apply");
274        let mut emit = FunctionEmitter::new();
275        let mut symbols = symbols.clone();
276        symbols.enter_function_body(binder_key::function_owner(&symbols, None, &body));
277        symbols.drop_runtime_locals();
278        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        ctx.emit_boundary_wrapper(&mut emit, Some(WasmType::I32), |ctx, emit| {
283            ctx.call_instances_init(emit)?;
284            let ty = expr::compile_for_stack(ctx, emit, symbols, &body)?;
285            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                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        })?;
301
302        let locals = ctx.build_locals_declaration()?;
303        ctx.reset_locals(symbols);
304        emit.finish(&locals)
305    }
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.
315fn emit_to_anyref(ctx: &CompileContext, emit: &mut FunctionEmitter, ty: WasmType) {
316    match ty {
317        WasmType::I32 => {
318            emit.i64_extend_i32_s();
319            emit.call(ctx.ids.ratio_from_i64);
320        }
321        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        | WasmType::AnyRef => {}
331    }
332}
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]
343pub fn wasm_validation_features() -> wasmparser::WasmFeatures {
344    use wasmparser::WasmFeatures;
345
346    WasmFeatures::default()
347        | WasmFeatures::GC
348        | WasmFeatures::REFERENCE_TYPES
349        | WasmFeatures::FUNCTION_REFERENCES
350        | WasmFeatures::EXCEPTIONS
351}
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).
358fn validate_module(wasm: &[u8]) -> Result<()> {
359    wasmparser::Validator::new_with_features(wasm_validation_features())
360        .validate_all(wasm)
361        .map_err(|e| Error::Compile(format!("emitted module failed wasm validation: {e}")))?;
362    Ok(())
363}
364
365fn is_definition_form(expr: &Expr) -> bool {
366    let Expr::List(elems) = expr else {
367        return false;
368    };
369    let Some(Expr::Symbol(name)) = elems.first() else {
370        return false;
371    };
372    matches!(
373        name.as_str(),
374        "DEFUN" | "DEFVAR" | "DEFMACRO" | "DEFPARAMETER" | "DEFSTRUCT"
375    )
376}
377
378impl Default for Compiler {
379    fn default() -> Self {
380        Self::new()
381    }
382}
383
384#[cfg(test)]
385#[path = "mod_tests.rs"]
386mod tests;
387
388#[cfg(test)]
389mod behaviour_oracle;
390
391#[cfg(test)]
392mod behaviour_snapshot;
393
394#[cfg(test)]
395impl Compiler {
396    /// The counters of the most recent compilation.
397    pub(crate) fn stats(&self) -> CompileStats {
398        self.stats
399    }
400}
401
402#[cfg(test)]
403mod unit_budget_tests;