1
//! `CompileContext` construction: the two public entry points
2
//! (`new` for script mode, `new_eval_with_host_fns` for eval mode), the
3
//! shared `new_skeleton` (types + memory + exception/`$t`-global setup every
4
//! mode needs), and the import declarations each mode wires up.
5

            
6
use std::collections::{BTreeMap, HashMap, HashSet};
7

            
8
use tracing::debug;
9
use wasm_encoder::{
10
    CodeSection, DataSection, ExportKind, ExportSection, FunctionSection, GlobalSection,
11
    ImportSection, MemorySection, MemoryType, TagSection, TypeSection, ValType,
12
};
13

            
14
use super::{CompileContext, block_joins, closure, entity_registry, ids, monomorph};
15
use crate::compiler::stats::CompileStats;
16
use crate::error::Result;
17
use crate::host_fn::HostFnSpec;
18

            
19
impl CompileContext {
20
    /// Builds an eval-mode compile context: same types and ratio helpers as
21
    /// script mode, but exports `nomi-eval` (returning `(ref null any)`)
22
    /// instead of `should_apply`/`process`. Each entry in `host_fns`
23
    /// gets a wasm import declared up-front (so the function index is
24
    /// stable for codegen) plus an entry in the lookup table the native
25
    /// dispatcher consults when emitting calls. The host decodes the
26
    /// nomi-eval return via `scripting::runtime::decode_eval_result`.
27
735345
    pub fn new_eval_with_host_fns(host_fns: &[HostFnSpec]) -> Result<Self> {
28
735345
        let mut ctx = Self::new_skeleton()?;
29
735345
        ctx.register_raise_import()?;
30
735345
        ctx.register_catch_each_import()?;
31
        // `env.log` is the output channel for PRINT / DISPLAY / NEWLINE / DEBUG.
32
        // It was script-mode-only; without it those natives' `ctx.func("log")`
33
        // had no func index in eval mode. Declared before the local `nomi-eval`
34
        // fn so the import index space stays contiguous. Host side: the rpc
35
        // Session linker wires `env.log` (mirrors `scripting::host`).
36
735345
        ctx.register_log_import()?;
37
735345
        for spec in host_fns {
38
44692493
            ctx.register_host_fn(spec)?;
39
        }
40
735344
        let anyref = ctx.anyref();
41
735344
        ctx.register_function("nomi-eval", &[], &[anyref])?;
42
        // Two-phase (declare → resolve → build): declare every helper signature
43
        // so all indices exist, snapshot them into `ids`, then emit the bodies
44
        // reading `ids`. Declare order fixes the function-index space; build
45
        // order fixes `pending_helpers` + data-segment indices — both preserved
46
        // exactly as the pre-split single-pass layout, so the wasm is identical.
47
735344
        ctx.declare_ratio_helpers()?;
48
735344
        ctx.declare_unit_term_helpers()?;
49
735344
        ctx.declare_commodity_helpers()?;
50
735344
        ctx.declare_pair_helpers()?;
51
735344
        ctx.declare_index_helpers()?;
52
735344
        ctx.declare_string_eq_helper()?;
53
735344
        ctx.declare_condition_helper()?;
54
735344
        ctx.declare_entity_allocators()?;
55
735344
        ctx.declare_struct_helpers()?;
56
735344
        ctx.export_func("nomi-eval")?;
57
735344
        ctx.install_ids()?;
58
735344
        ctx.build_ratio_helpers()?;
59
735344
        ctx.build_unit_term_helpers();
60
735344
        ctx.build_commodity_helpers()?;
61
735344
        ctx.build_pair_helpers();
62
735344
        ctx.build_index_helpers()?;
63
735344
        ctx.build_string_eq_helper()?;
64
735344
        ctx.build_condition_helper();
65
735344
        ctx.build_entity_allocators()?;
66
735344
        ctx.build_struct_helpers();
67
735344
        debug!(
68
            host_fn_count = host_fns.len(),
69
            "eval compile context initialized"
70
        );
71
735344
        Ok(ctx)
72
735345
    }
73

            
74
    /// Declares the `(error 'code "msg")` lowering target up-front so
75
    /// the function index is stable before any user host fn is wired.
76
    /// The native is declared as `(string-ref, string-ref, anyref) -> ()` —
77
    /// it never returns normally; the host always produces
78
    /// a `ScriptRaise` error which the classifier lifts before
79
    /// the unreachable-trap branch (ADR-0014). See
80
    /// `rpc::natives::raise` for the host side.
81
2352713
    fn register_raise_import(&mut self) -> Result<()> {
82
2352713
        let arr = self.array_ref();
83
2352713
        let detail = self.anyref();
84
2352713
        self.register_import("nomi", "__nomi_raise", &[arr, arr, detail], &[])?;
85
2352713
        Ok(())
86
2352713
    }
87

            
88
    /// Declares the `(catch-each items var body)` lowering target up-front.
89
    /// The body is compiled to a real wasm fn (Tier 1.5 closure machinery)
90
    /// whose funcref + env are extracted at the call site and passed to
91
    /// `__nomi_catch_each` along with the items list. The host walks the
92
    /// chain in Rust, calls the funcref per item recovering per-call
93
    /// `wasmtime::Error`, and returns a heterogeneous `pair<anyref>`
94
    /// chain of `(ok . v)` / `(err . (code . msg))` cells. Engine-bound
95
    /// `OutOfFuel` / `EpochInterrupt` traps re-throw straight through —
96
    /// they never appear as `err` cells (ADR-0025).
97
735345
    fn register_catch_each_import(&mut self) -> Result<()> {
98
        // Items + result go on the wire as abstract `(ref null struct)`.
99
        // The host registers the fn with `Rooted<StructRef>` whose
100
        // `WasmTy::valtype()` is the abstract heap type — declaring the
101
        // concrete `$pair` here would fail the import-type check at
102
        // instantiation. Compiler emits a `ref.cast` after the call to
103
        // recover the concrete `$pair` for the downstream pipeline; the
104
        // items-arg side accepts a `(ref null $pair)` because the struct
105
        // subtype relationship is one-way (concrete <: abstract).
106
735345
        let funcref = ValType::Ref(wasm_encoder::RefType::FUNCREF);
107
735345
        let any = self.anyref();
108
735345
        let abstract_struct = self.struct_ref();
109
735345
        self.register_import(
110
735345
            "nomi",
111
735345
            "__nomi_catch_each",
112
735345
            &[funcref, any, abstract_struct],
113
735345
            &[abstract_struct],
114
735345
        )?;
115
735345
        Ok(())
116
735345
    }
117

            
118
2352713
    fn new_skeleton() -> Result<Self> {
119
2352713
        let mut ctx = Self {
120
2352713
            types: TypeSection::new(),
121
2352713
            imports: ImportSection::new(),
122
2352713
            functions: FunctionSection::new(),
123
2352713
            memories: MemorySection::new(),
124
2352713
            tags: TagSection::new(),
125
2352713
            globals: GlobalSection::new(),
126
2352713
            global_count: 0,
127
2352713
            exports: ExportSection::new(),
128
2352713
            codes: CodeSection::new(),
129
2352713
            data: DataSection::new(),
130
2352713
            data_count: 0,
131
2352713
            type_count: 0,
132
2352713
            tag_count: 0,
133
2352713
            import_func_count: 0,
134
2352713
            local_func_count: 0,
135
2352713
            type_cache: HashMap::new(),
136
2352713
            func_names: HashMap::new(),
137
2352713
            host_fns: HashMap::new(),
138
2352713
            pending_helpers: Vec::new(),
139
2352713
            next_local: super::LOCAL_POOL_BASE,
140
2352713
            local_types: Vec::new(),
141
2352713
            serializer: super::super::layout::OutputSerializer::new(
142
2352713
                super::super::expr::LOCAL_OUTPUT_BASE,
143
2352713
            ),
144
2352713
            closures: closure::ClosureRegistry::default(),
145
2352713
            declared_funcs: Vec::new(),
146
2352713
            monomorphs: monomorph::MonomorphCache::default(),
147
2352713
            nomi_error_tag: None,
148
2352713
            ids: ids::WasmIds::UNRESOLVED,
149
2352713
            inlining_stack: Vec::new(),
150
2352713
            inlining_set: HashSet::new(),
151
2352713
            block_labels: Vec::new(),
152
2352713
            outer_labels: Vec::new(),
153
2352713
            hidden_labels: Vec::new(),
154
2352713
            block_joins: block_joins::BlockJoins::default(),
155
2352713
            tag_frames: Vec::new(),
156
2352713
            unwind_frames: Vec::new(),
157
2352713
            stats: CompileStats::default(),
158
2352713
            read_checks: HashMap::new(),
159
2352713
            struct_layouts: HashMap::new(),
160
2352713
            struct_serial: None,
161
2352713
            struct_serial_base: 0,
162
2352713
            instance_globals: BTreeMap::new(),
163
2352713
            instances_init: None,
164
2352713
        };
165
        // Type indices are captured into `ids.ty_*` AS each type registers, so
166
        // the type-ref accessors (`ratio_ref`, `pair_ref`, …) read `ids` even
167
        // mid-skeleton — before the helper-fn `resolve_ids` runs. The struct
168
        // layouts + registration order are unchanged, so the wasm is identical.
169
2352713
        ctx.ids.ty_i8_array = ctx.register_type()?;
170
2352713
        ctx.ids.ty_ratio = ctx.register_struct_type(&[ValType::I64, ValType::I64])?;
171
2352713
        ctx.ids.ty_pair = ctx.register_pair_type()?;
172
2352713
        let name = ctx.symbol_name_ref();
173
2352713
        ctx.ids.ty_symbol = ctx.register_struct_type(&[name])?;
174
        // Commodity unit-term (ADR-0028): a flat `(array (mut i64))` of sorted
175
        // canonical `(hi, lo, exp)` triples. Registered before `commodity` so
176
        // the struct's 5th field can reference it. A NULL term means ATOMIC
177
        // `[(atom, 1)]`, so atomic money leaves the field unset and round-trips
178
        // exactly as before this widening.
179
2352713
        ctx.ids.ty_unit_term = ctx.register_i64_array_type()?;
180
        // Commodity = (i64 numer, i64 denom, i64 commodity_hi, i64 commodity_lo,
181
        // (ref null $unit_term) term). commodity_hi/lo carry the two halves of
182
        // the UUID, stored as i64 to match wasmtime host-fn primitive types
183
        // (reassembled to Uuid at the host boundary via `Uuid::from_u128`).
184
        // Fields 0-3 are byte-identical to the pre-ADR-0028 layout.
185
2352713
        let unit_term_ref = ctx.unit_term_ref();
186
2352713
        ctx.ids.ty_commodity = ctx.register_struct_type(&[
187
2352713
            ValType::I64,
188
2352713
            ValType::I64,
189
2352713
            ValType::I64,
190
2352713
            ValType::I64,
191
2352713
            unit_term_ref,
192
2352713
        ])?;
193
        // Server-entity wasm struct types. Field layouts read from
194
        // the single-source-of-truth `ENTITY_SPECS` table in
195
        // `entity_registry.rs` — both this site and
196
        // `register_entity_allocators` walk the same const so the
197
        // struct layout and the allocator signature can't drift.
198
        // Adding a new entity kind: extend `EntityKind` in =ast.rs= +
199
        // add one row to `ENTITY_SPECS`.
200
        // One recursion group, so same-shaped entity structs stay distinct
201
        // types (see `register_struct_rec_group`).
202
2352713
        let entity_fields: Vec<Vec<ValType>> = entity_registry::ENTITY_SPECS
203
2352713
            .iter()
204
72934103
            .map(|spec| spec.fields.iter().map(|f| f.as_val_type(&ctx)).collect())
205
            .collect();
206
2352713
        let indices = ctx.register_struct_rec_group(&entity_fields)?;
207
2352713
        for (spec, idx) in entity_registry::ENTITY_SPECS.iter().zip(indices) {
208
16468991
            ctx.ids.set_entity_type(spec.kind, idx);
209
        }
210
2352713
        ctx.register_closure_base_type()?;
211
        // `$nomi_condition` struct + `$nomi_error` exception tag (Tier 3,
212
        // ADR-0026). Registered here so the type/tag indices are stable
213
        // before any body emits a `throw` / `try_table`. The tag's payload
214
        // is a single `(ref null $nomi_condition)` so a catch hands the
215
        // handler the condition ref directly.
216
2352713
        ctx.register_exception_support()?;
217
2352713
        ctx.register_t_global()?;
218
2352713
        ctx.register_struct_types()?;
219
2352713
        ctx.memories.memory(MemoryType {
220
2352713
            minimum: 1,
221
2352713
            maximum: None,
222
2352713
            memory64: false,
223
2352713
            shared: false,
224
2352713
            page_size_log2: None,
225
2352713
        });
226
2352713
        ctx.exports.export("memory", ExportKind::Memory, 0);
227
2352713
        Ok(ctx)
228
2352713
    }
229

            
230
    /// Builds a script-mode compile context. Each entry in `host_fns` gets a
231
    /// wasm import declared up-front, exactly as in eval mode, so a host
232
    /// that links extra `nomi.*` fns (the behaviour oracle's entity and
233
    /// money sources) can run a script that calls them.
234
1617368
    pub fn new_with_host_fns(host_fns: &[HostFnSpec]) -> Result<Self> {
235
1617368
        debug!("initializing compile context");
236
1617368
        let mut ctx = Self::new_skeleton()?;
237
1617368
        ctx.register_script_imports()?;
238
        // Tier 3: the boundary wrapper around `process` / `should_apply`
239
        // bridges an uncaught `$nomi_error` to `__nomi_raise`, so script
240
        // mode must declare the import too (it was eval-mode-only). Must
241
        // precede the first `register_function` so the import index space
242
        // stays contiguous. Host side: `scripting::host::define_host_functions`.
243
1617368
        ctx.register_raise_import()?;
244
1617368
        for spec in host_fns {
245
10758
            ctx.register_host_fn(spec)?;
246
        }
247
1617368
        ctx.register_function("should_apply", &[], &[ValType::I32])?;
248
        // Two-phase (declare → resolve → build); see `new_eval_with_host_fns`.
249
        // `should_apply` / `process` keep their function-index slots (declared
250
        // around the helper declarations exactly as before); helper BODIES land
251
        // on `pending_helpers` in build order, which the `should_apply`
252
        // split-drain (bootstrap count) consumes unchanged.
253
1617368
        ctx.declare_ratio_helpers()?;
254
1617368
        ctx.declare_unit_term_helpers()?;
255
1617368
        ctx.declare_commodity_helpers()?;
256
1617368
        ctx.declare_pair_helpers()?;
257
1617368
        ctx.declare_index_helpers()?;
258
1617368
        ctx.declare_string_eq_helper()?;
259
1617368
        ctx.declare_condition_helper()?;
260
1617368
        ctx.declare_entity_allocators()?;
261
1617368
        ctx.declare_struct_helpers()?;
262
1617368
        ctx.register_function("process", &[], &[])?;
263
1617368
        ctx.install_ids()?;
264
1617368
        ctx.build_ratio_helpers()?;
265
1617368
        ctx.build_unit_term_helpers();
266
1617368
        ctx.build_commodity_helpers()?;
267
1617368
        ctx.build_pair_helpers();
268
1617368
        ctx.build_index_helpers()?;
269
1617368
        ctx.build_string_eq_helper()?;
270
1617368
        ctx.build_condition_helper();
271
1617368
        ctx.build_entity_allocators()?;
272
1617368
        ctx.build_struct_helpers();
273
1617368
        ctx.export_func("should_apply")?;
274
1617368
        ctx.export_func("process")?;
275
1617368
        ctx.install_ids()?;
276
1617368
        debug!("compile context initialized");
277
1617368
        Ok(ctx)
278
1617368
    }
279

            
280
    /// Declares the `env.log` import — the host output channel shared by
281
    /// PRINT / DISPLAY / NEWLINE / DEBUG (`(i32 level, i32 ptr, i32 len) -> ()`)
282
    /// — and `env.log_value`, which prints a runtime argument list
283
    /// (`(ref null any) -> i32`, nonzero when a value cannot be printed).
284
    /// Used by both module modes so the `log` func index always exists wherever
285
    /// those natives can be emitted.
286
2352713
    fn register_log_import(&mut self) -> Result<()> {
287
2352713
        self.register_import(
288
2352713
            "env",
289
2352713
            "log",
290
2352713
            &[ValType::I32, ValType::I32, ValType::I32],
291
2352713
            &[],
292
2352713
        )?;
293
2352713
        let anyref = self.anyref();
294
2352713
        self.register_import("env", "log_value", &[anyref], &[ValType::I32])?;
295
2352713
        Ok(())
296
2352713
    }
297

            
298
1617368
    fn register_script_imports(&mut self) -> Result<()> {
299
1617368
        self.register_import("env", "get_output_offset", &[], &[ValType::I32])?;
300
1617368
        self.register_import("env", "symbol_resolve", &[ValType::I32, ValType::I32], &[])?;
301
1617368
        self.register_log_import()?;
302
1617368
        self.register_import("env", "get_input_offset", &[], &[ValType::I32])?;
303
1617368
        self.register_import("env", "get_strings_offset", &[], &[ValType::I32])?;
304
1617368
        self.register_import("env", "get_input_entities_count", &[], &[ValType::I32])?;
305
1617368
        self.register_import("env", "get_timestamp", &[], &[ValType::I64])?;
306
1617368
        self.register_import("env", "generate_uuid", &[ValType::I32], &[])?;
307
1617368
        self.register_import(
308
1617368
            "env",
309
1617368
            "write_string",
310
1617368
            &[ValType::I32, ValType::I32],
311
1617368
            &[ValType::I32],
312
1617368
        )?;
313
1617368
        self.register_import(
314
1617368
            "env",
315
1617368
            "write_bytes",
316
1617368
            &[ValType::I32, ValType::I32, ValType::I32],
317
1617368
            &[ValType::I32],
318
1617368
        )?;
319
1617368
        Ok(())
320
1617368
    }
321
}