1
//! `$pair` setup + entity allocators + string-equality helper.
2
//!
3
//! Three loosely-related setup chunks share this file: they all
4
//! register type + function pairs that the rest of the compiler treats
5
//! as opaque imports. Pair is the canonical list cell, entity
6
//! allocators expose typed `alloc_<kind>` exports for host-side
7
//! struct construction, and `string_eq` is the byte-by-byte array
8
//! equality helper.
9

            
10
use super::CompileContext;
11
use crate::error::{Error, Result};
12
use wasm_encoder::{
13
    CompositeInnerType, CompositeType, FieldType, Function, HeapType, Instruction, RefType,
14
    StorageType, StructType, SubType, ValType,
15
};
16

            
17
impl CompileContext {
18
    /// Canonical list cell: `(struct (field anyref car) (field (ref null
19
    /// $pair) cdr))`. The only list-cell type in the compiler. CONS boxes
20
    /// the car (`ref.i31` for i32, implicit anyref subtype for Ratio /
21
    /// Commodity / String); CAR downcasts using the compile-time
22
    /// `PairElement` carried by `WasmType::PairRef`. Heterogeneous lists
23
    /// are refused at the language layer, so the wasm shape is uniform
24
    /// regardless of element type.
25
2352713
    pub(super) fn register_pair_type(&mut self) -> Result<u32> {
26
2352713
        let pair_idx = self.type_count;
27
2352713
        let pair_nullable_ref = ValType::Ref(RefType {
28
2352713
            nullable: true,
29
2352713
            heap_type: HeapType::Concrete(pair_idx),
30
2352713
        });
31
2352713
        let anyref_field = ValType::Ref(RefType {
32
2352713
            nullable: true,
33
2352713
            heap_type: HeapType::ANY,
34
2352713
        });
35
2352713
        let struct_fields = vec![
36
2352713
            FieldType {
37
2352713
                element_type: StorageType::Val(anyref_field),
38
2352713
                mutable: false,
39
2352713
            },
40
2352713
            FieldType {
41
2352713
                element_type: StorageType::Val(pair_nullable_ref),
42
2352713
                mutable: false,
43
2352713
            },
44
        ];
45
2352713
        self.types.ty().subtype(&SubType {
46
2352713
            is_final: true,
47
2352713
            supertype_idxs: Vec::new(),
48
2352713
            composite_type: CompositeType {
49
2352713
                inner: CompositeInnerType::Struct(StructType {
50
2352713
                    fields: struct_fields.into_boxed_slice(),
51
2352713
                }),
52
2352713
                shared: false,
53
2352713
                describes: None,
54
2352713
                descriptor: None,
55
2352713
            },
56
2352713
        });
57
2352713
        self.type_count = self
58
2352713
            .type_count
59
2352713
            .checked_add(1)
60
            .ok_or_else(|| Error::Compile("wasm type index space exhausted".to_string()))?;
61
2352713
        Ok(pair_idx)
62
2352713
    }
63

            
64
2352712
    pub(super) fn declare_pair_helpers(&mut self) -> Result<()> {
65
2352712
        let pair_ref = self.pair_ref();
66
2352712
        let anyref = self.anyref();
67
2352712
        self.register_function("pair_new", &[anyref, pair_ref], &[pair_ref])?;
68
        // Host helpers (`scripting::runtime::alloc_pair_chain`)
69
        // reach `pair_new` via `caller.get_export("pair_new")` to
70
        // fold chains element-by-element. Re-entry through the
71
        // guest's own allocator dodges engine type canonicalization
72
        // for the `$pair` struct's `(ref null $pair)` cdr field.
73
2352712
        self.export_func("pair_new")?;
74
2352712
        let name = self.symbol_name_ref();
75
2352712
        let symbol_ref = self.symbol_ref();
76
2352712
        self.register_function("symbol_new", &[name], &[symbol_ref])?;
77
2352712
        self.export_func("symbol_new")?;
78
2352712
        Ok(())
79
2352712
    }
80

            
81
2352712
    pub(super) fn build_pair_helpers(&mut self) {
82
2352712
        self.build_pair_new_body();
83
2352712
        self.build_symbol_new_body();
84
2352712
    }
85

            
86
2352712
    fn build_symbol_new_body(&mut self) {
87
2352712
        let mut f = Function::new([]);
88
2352712
        f.instruction(&Instruction::LocalGet(0));
89
2352712
        f.instruction(&Instruction::StructNew(self.ids.ty_symbol));
90
2352712
        f.instruction(&Instruction::End);
91
2352712
        self.pending_helpers.push(f);
92
2352712
    }
93

            
94
    /// One exported `alloc_<kind>` per entity wasm struct. Body is a
95
    /// straight `struct.new $<kind>` over the params. Host fns that
96
    /// produce typed entity returns (`list-accounts`, `get-account`,
97
    /// ...) re-enter the module via these exports — host-side
98
    /// `StructType::new` can't reproduce the entity's reference-typed
99
    /// field signature (`(ref null $i8_array)`) because engine
100
    /// canonicalization compares the field's concrete type index, not
101
    /// just the abstract heap class. Re-entry through the module's
102
    /// own allocator dodges the issue: each call produces a struct ref
103
    /// of the exact `$<kind>` type the guest's `ref.cast` then accepts.
104
    /// Declares + exports one `alloc_<kind>` per entity wasm struct (no bodies).
105
    /// Walks `ENTITY_SPECS` in order so [`Self::build_entity_allocators`] can
106
    /// emit the matching bodies positionally.
107
2352712
    pub(super) fn declare_entity_allocators(&mut self) -> Result<()> {
108
        // Walks the same `ENTITY_SPECS` table that `new_skeleton`
109
        // consults — single source of truth keeps the allocator
110
        // signature aligned with the struct layout.
111
2352712
        for spec in super::entity_registry::ENTITY_SPECS {
112
72934072
            let params: Vec<ValType> = spec.fields.iter().map(|f| f.as_val_type(self)).collect();
113
16468984
            let entity_ref = self.entity_ref(spec.kind);
114
16468984
            let export_name = format!("alloc_{}", spec.type_name);
115
16468984
            self.register_function(&export_name, &params, &[entity_ref])?;
116
            // Host helpers (`scripting::runtime::alloc_entity_via_export`)
117
            // reach each allocator via `caller.get_export(...)` — the
118
            // export must be present or the host fn traps at runtime.
119
16468984
            self.export_func(&export_name)?;
120
        }
121
2352712
        Ok(())
122
2352712
    }
123

            
124
    /// Emits each `alloc_<kind>` body — a flat `local.get $i` × n +
125
    /// `struct.new $kind` — in `ENTITY_SPECS` order, reading the struct index
126
    /// from `self.ids.entity_type`.
127
2352712
    pub(super) fn build_entity_allocators(&mut self) -> Result<()> {
128
2352712
        for spec in super::entity_registry::ENTITY_SPECS {
129
16468984
            let arity = spec.fields.len();
130
16468984
            let struct_idx = self.ids.entity_type(spec.kind);
131
16468984
            let mut f = Function::new([]);
132
16468984
            for i in 0..arity {
133
72934072
                let idx = u32::try_from(i)
134
                    .map_err(|_| Error::Compile("entity arity exceeds u32".to_string()))?;
135
72934072
                f.instruction(&Instruction::LocalGet(idx));
136
            }
137
16468984
            f.instruction(&Instruction::StructNew(struct_idx));
138
16468984
            f.instruction(&Instruction::End);
139
16468984
            self.pending_helpers.push(f);
140
        }
141
2352712
        Ok(())
142
2352712
    }
143

            
144
2352712
    fn build_pair_new_body(&mut self) {
145
2352712
        let pair_idx = self.ids.ty_pair;
146
        // params: $car=0 (anyref), $cdr=1 (ref null $pair).
147
        // body: push both, struct.new $pair.
148
2352712
        let mut f = Function::new([]);
149
2352712
        f.instruction(&Instruction::LocalGet(0));
150
2352712
        f.instruction(&Instruction::LocalGet(1));
151
2352712
        f.instruction(&Instruction::StructNew(pair_idx));
152
2352712
        f.instruction(&Instruction::End);
153
2352712
        self.pending_helpers.push(f);
154
2352712
    }
155

            
156
2352712
    pub(super) fn declare_string_eq_helper(&mut self) -> Result<()> {
157
2352712
        let string_ref = self.string_ref();
158
2352712
        self.register_function("string_eq", &[string_ref, string_ref], &[ValType::I32])?;
159
        // ADR-0033 Phase 6: the host resolves `$i8_array`'s `HeapType` from
160
        // this export's param type to classify a heterogeneous anyref cell —
161
        // no runtime value is ever taken through it host-side.
162
2352712
        self.export_func("string_eq")?;
163
2352712
        let symbol_ref = self.symbol_ref();
164
2352712
        self.register_function("symbol_eq", &[symbol_ref, symbol_ref], &[ValType::I32])?;
165
2352712
        let name = self.string_ref();
166
2352712
        self.register_function("symbol_designator", &[symbol_ref], &[name])?;
167
2352712
        self.register_function("symbol_keyword_p", &[symbol_ref], &[ValType::I32])?;
168
2352712
        self.declare_pair_equal()
169
2352712
    }
170

            
171
2352712
    pub(super) fn build_string_eq_helper(&mut self) -> Result<()> {
172
2352712
        self.build_string_eq_body();
173
2352712
        self.build_symbol_eq_body();
174
2352712
        self.build_symbol_designator_body();
175
2352712
        self.build_symbol_keyword_p_body();
176
2352712
        self.build_pair_equal()
177
2352712
    }
178

            
179
    /// A symbol's string designator is its name; a keyword's drops the colon.
180
2352712
    fn build_symbol_designator_body(&mut self) {
181
        const COLON: i32 = 58;
182
2352712
        let (symbol_idx, bytes) = (self.ids.ty_symbol, self.ids.ty_i8_array);
183
2352712
        let string = ValType::Ref(RefType {
184
2352712
            nullable: true,
185
2352712
            heap_type: HeapType::Concrete(bytes),
186
2352712
        });
187
2352712
        let mut f = Function::new([(2, string)]);
188
2352712
        let (name, tail) = (1, 2);
189
2352712
        f.instruction(&Instruction::LocalGet(0));
190
2352712
        f.instruction(&Instruction::StructGet {
191
2352712
            struct_type_index: symbol_idx,
192
2352712
            field_index: 0,
193
2352712
        });
194
2352712
        f.instruction(&Instruction::LocalSet(name));
195
2352712
        f.instruction(&Instruction::LocalGet(name));
196
2352712
        f.instruction(&Instruction::ArrayLen);
197
2352712
        f.instruction(&Instruction::I32Eqz);
198
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Result(string)));
199
2352712
        f.instruction(&Instruction::LocalGet(name));
200
2352712
        f.instruction(&Instruction::Else);
201
2352712
        f.instruction(&Instruction::LocalGet(name));
202
2352712
        f.instruction(&Instruction::I32Const(0));
203
2352712
        f.instruction(&Instruction::ArrayGetU(bytes));
204
2352712
        f.instruction(&Instruction::I32Const(COLON));
205
2352712
        f.instruction(&Instruction::I32Eq);
206
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Result(string)));
207
2352712
        f.instruction(&Instruction::LocalGet(name));
208
2352712
        f.instruction(&Instruction::ArrayLen);
209
2352712
        f.instruction(&Instruction::I32Const(1));
210
2352712
        f.instruction(&Instruction::I32Sub);
211
2352712
        f.instruction(&Instruction::ArrayNewDefault(bytes));
212
2352712
        f.instruction(&Instruction::LocalSet(tail));
213
2352712
        f.instruction(&Instruction::LocalGet(tail));
214
2352712
        f.instruction(&Instruction::I32Const(0));
215
2352712
        f.instruction(&Instruction::LocalGet(name));
216
2352712
        f.instruction(&Instruction::I32Const(1));
217
2352712
        f.instruction(&Instruction::LocalGet(tail));
218
2352712
        f.instruction(&Instruction::ArrayLen);
219
2352712
        f.instruction(&Instruction::ArrayCopy {
220
2352712
            array_type_index_dst: bytes,
221
2352712
            array_type_index_src: bytes,
222
2352712
        });
223
2352712
        f.instruction(&Instruction::LocalGet(tail));
224
2352712
        f.instruction(&Instruction::Else);
225
2352712
        f.instruction(&Instruction::LocalGet(name));
226
2352712
        f.instruction(&Instruction::End);
227
2352712
        f.instruction(&Instruction::End);
228
2352712
        f.instruction(&Instruction::End);
229
2352712
        self.pending_helpers.push(f);
230
2352712
    }
231

            
232
    /// A keyword is a non-nil symbol whose name starts with a colon.
233
2352712
    fn build_symbol_keyword_p_body(&mut self) {
234
        const COLON: i32 = 58;
235
2352712
        let (symbol_idx, bytes) = (self.ids.ty_symbol, self.ids.ty_i8_array);
236
2352712
        let string = ValType::Ref(RefType {
237
2352712
            nullable: true,
238
2352712
            heap_type: HeapType::Concrete(bytes),
239
2352712
        });
240
2352712
        let result = wasm_encoder::BlockType::Result(ValType::I32);
241
2352712
        let mut f = Function::new([(1, string)]);
242
2352712
        let name = 1;
243
2352712
        f.instruction(&Instruction::LocalGet(0));
244
2352712
        f.instruction(&Instruction::RefIsNull);
245
2352712
        f.instruction(&Instruction::If(result));
246
2352712
        f.instruction(&Instruction::I32Const(0));
247
2352712
        f.instruction(&Instruction::Else);
248
2352712
        f.instruction(&Instruction::LocalGet(0));
249
2352712
        f.instruction(&Instruction::StructGet {
250
2352712
            struct_type_index: symbol_idx,
251
2352712
            field_index: 0,
252
2352712
        });
253
2352712
        f.instruction(&Instruction::LocalSet(name));
254
2352712
        f.instruction(&Instruction::LocalGet(name));
255
2352712
        f.instruction(&Instruction::ArrayLen);
256
2352712
        f.instruction(&Instruction::If(result));
257
2352712
        f.instruction(&Instruction::LocalGet(name));
258
2352712
        f.instruction(&Instruction::I32Const(0));
259
2352712
        f.instruction(&Instruction::ArrayGetU(bytes));
260
2352712
        f.instruction(&Instruction::I32Const(COLON));
261
2352712
        f.instruction(&Instruction::I32Eq);
262
2352712
        f.instruction(&Instruction::Else);
263
2352712
        f.instruction(&Instruction::I32Const(0));
264
2352712
        f.instruction(&Instruction::End);
265
2352712
        f.instruction(&Instruction::End);
266
2352712
        f.instruction(&Instruction::End);
267
2352712
        self.pending_helpers.push(f);
268
2352712
    }
269

            
270
    /// Two symbols are equal when both are `nil` or their names are equal.
271
2352712
    fn build_symbol_eq_body(&mut self) {
272
2352712
        let symbol_idx = self.ids.ty_symbol;
273
2352712
        let mut f = Function::new([]);
274
2352712
        f.instruction(&Instruction::LocalGet(0));
275
2352712
        f.instruction(&Instruction::RefIsNull);
276
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Result(
277
2352712
            ValType::I32,
278
2352712
        )));
279
2352712
        f.instruction(&Instruction::LocalGet(1));
280
2352712
        f.instruction(&Instruction::RefIsNull);
281
2352712
        f.instruction(&Instruction::Else);
282
2352712
        f.instruction(&Instruction::LocalGet(1));
283
2352712
        f.instruction(&Instruction::RefIsNull);
284
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Result(
285
2352712
            ValType::I32,
286
2352712
        )));
287
2352712
        f.instruction(&Instruction::I32Const(0));
288
2352712
        f.instruction(&Instruction::Else);
289
2352712
        f.instruction(&Instruction::LocalGet(0));
290
2352712
        f.instruction(&Instruction::StructGet {
291
2352712
            struct_type_index: symbol_idx,
292
2352712
            field_index: 0,
293
2352712
        });
294
2352712
        f.instruction(&Instruction::LocalGet(1));
295
2352712
        f.instruction(&Instruction::StructGet {
296
2352712
            struct_type_index: symbol_idx,
297
2352712
            field_index: 0,
298
2352712
        });
299
2352712
        f.instruction(&Instruction::Call(self.ids.string_eq));
300
2352712
        f.instruction(&Instruction::End);
301
2352712
        f.instruction(&Instruction::End);
302
2352712
        f.instruction(&Instruction::End);
303
2352712
        self.pending_helpers.push(f);
304
2352712
    }
305

            
306
2352712
    fn build_string_eq_body(&mut self) {
307
2352712
        let i8_array_idx = self.ids.ty_i8_array;
308
        // params: $a=0 (ref null $i8_array), $b=1 (ref null $i8_array)
309
        // locals: $len=2 (i32), $i=3 (i32)
310
        //
311
        // No null guard: every call site (`STRING=`, `EQUAL`'s string
312
        // branch) null-checks both operands itself before calling in,
313
        // throwing a catchable `TYPE-ERROR` on a nil argument rather than
314
        // reaching here at all (ADR-0033 Phase 5) — a nil string is never a
315
        // legal `STRING=`/`EQUAL` operand, so there is no "both nil" or
316
        // "one nil" case left for this helper to define. The third caller,
317
        // `handler-case`'s condition-code dispatch, only ever compares two
318
        // freshly-interned literal byte arrays, never null.
319
2352712
        let mut f = Function::new([(1, ValType::I32), (1, ValType::I32)]);
320

            
321
        // len = array.len(a)
322
2352712
        f.instruction(&Instruction::LocalGet(0));
323
2352712
        f.instruction(&Instruction::ArrayLen);
324
2352712
        f.instruction(&Instruction::LocalSet(2));
325

            
326
        // if array.len(b) != len → return 0
327
2352712
        f.instruction(&Instruction::LocalGet(1));
328
2352712
        f.instruction(&Instruction::ArrayLen);
329
2352712
        f.instruction(&Instruction::LocalGet(2));
330
2352712
        f.instruction(&Instruction::I32Ne);
331
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
332
2352712
        f.instruction(&Instruction::I32Const(0));
333
2352712
        f.instruction(&Instruction::Return);
334
2352712
        f.instruction(&Instruction::End);
335

            
336
        // i = 0
337
2352712
        f.instruction(&Instruction::I32Const(0));
338
2352712
        f.instruction(&Instruction::LocalSet(3));
339

            
340
        // block $exit
341
2352712
        f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
342
        // loop $cmp
343
2352712
        f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));
344

            
345
        // if i >= len → break (equal)
346
2352712
        f.instruction(&Instruction::LocalGet(3));
347
2352712
        f.instruction(&Instruction::LocalGet(2));
348
2352712
        f.instruction(&Instruction::I32GeU);
349
2352712
        f.instruction(&Instruction::BrIf(1));
350

            
351
        // if a[i] != b[i] → return 0
352
2352712
        f.instruction(&Instruction::LocalGet(0));
353
2352712
        f.instruction(&Instruction::LocalGet(3));
354
2352712
        f.instruction(&Instruction::ArrayGetU(i8_array_idx));
355
2352712
        f.instruction(&Instruction::LocalGet(1));
356
2352712
        f.instruction(&Instruction::LocalGet(3));
357
2352712
        f.instruction(&Instruction::ArrayGetU(i8_array_idx));
358
2352712
        f.instruction(&Instruction::I32Ne);
359
2352712
        f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
360
2352712
        f.instruction(&Instruction::I32Const(0));
361
2352712
        f.instruction(&Instruction::Return);
362
2352712
        f.instruction(&Instruction::End);
363

            
364
        // i++
365
2352712
        f.instruction(&Instruction::LocalGet(3));
366
2352712
        f.instruction(&Instruction::I32Const(1));
367
2352712
        f.instruction(&Instruction::I32Add);
368
2352712
        f.instruction(&Instruction::LocalSet(3));
369
2352712
        f.instruction(&Instruction::Br(0));
370

            
371
2352712
        f.instruction(&Instruction::End); // end loop
372
2352712
        f.instruction(&Instruction::End); // end block
373

            
374
        // return 1 (equal)
375
2352712
        f.instruction(&Instruction::I32Const(1));
376
2352712
        f.instruction(&Instruction::End);
377
2352712
        self.pending_helpers.push(f);
378
2352712
    }
379
}