1
//! Wasm module section-level registration: types, imports, functions,
2
//! exports, data segments, plus the local-pool allocator.
3
//!
4
//! Every helper that mutates the wasm encoder sections lives here so
5
//! the other context submodules (types, pair, ratio, commodity, ...)
6
//! are pure consumers of stable indices.
7

            
8
use super::{CompileContext, LOCAL_POOL_BASE, LocalSlot};
9
use crate::ast::WasmType;
10
use crate::error::{Error, Result};
11
use anodized::spec;
12
use tracing::debug;
13
use wasm_encoder::{
14
    ArrayType, CompositeInnerType, CompositeType, EntityType as WasmEntityType, ExportKind,
15
    FieldType, StorageType, StructType, SubType, ValType,
16
};
17

            
18
#[spec(
19
517625622
    captures: before = *counter,
20
    ensures: |ref output| [
21
517625622
        output.as_ref().ok().is_none_or(|idx| *idx == before && *counter == before + 1),
22
517625622
        output.is_ok() || *counter == before,
23
    ],
24
)]
25
517625622
pub(super) fn bump(counter: &mut u32, kind: &'static str) -> Result<u32> {
26
517625622
    let idx = *counter;
27
517625622
    *counter = counter
28
517625622
        .checked_add(1)
29
        .ok_or_else(|| Error::Compile(format!("wasm {kind} index space exhausted")))?;
30
517625622
    Ok(idx)
31
517625622
}
32

            
33
impl CompileContext {
34
    #[spec(
35
8509895
        captures: [next = self.next_local, count = self.local_types.len()],
36
        ensures: |ref output| [
37
8509895
            output.as_ref().ok().is_none_or(|idx| *idx == next && self.next_local == next + 1),
38
8509895
            output.as_ref().ok().is_none_or(|idx| {
39
8509895
                self.local_types.last() == Some(&LocalSlot { ty, idx: *idx, cell: None })
40
8509895
            }),
41
8509895
            output.is_err() || self.local_types.len() == count + 1,
42
        ],
43
    )]
44
8509895
    pub fn alloc_local(&mut self, ty: WasmType) -> Result<u32> {
45
8509895
        let idx = bump(&mut self.next_local, "local")?;
46
8509895
        self.local_types.push(LocalSlot {
47
8509895
            ty,
48
8509895
            idx,
49
8509895
            cell: None,
50
8509895
        });
51
8509895
        Ok(idx)
52
8509895
    }
53

            
54
    /// Allocates a local holding a shared `$cell_<ty>` ref; the body still
55
    /// sees it as a `ty` value (see [`Self::cell_of`]).
56
10841
    pub(crate) fn alloc_cell_local(&mut self, ty: WasmType) -> Result<u32> {
57
10841
        let cell = self.intern_cell_type(ty)?;
58
10841
        let idx = bump(&mut self.next_local, "local")?;
59
10841
        self.local_types.push(LocalSlot {
60
10841
            ty,
61
10841
            idx,
62
10841
            cell: Some(cell),
63
10841
        });
64
10841
        Ok(idx)
65
10841
    }
66

            
67
    /// The `$cell_<ty>` type index when local `idx` of the current pool holds
68
    /// a shared cell.
69
4033025
    pub(crate) fn cell_of(&self, idx: u32) -> Option<u32> {
70
4033025
        self.local_types
71
4033025
            .iter()
72
281889485
            .find(|slot| slot.idx == idx)
73
3849020
            .and_then(|slot| slot.cell)
74
4033025
    }
75

            
76
8074005
    pub(crate) fn slot_val_type(&self, slot: &LocalSlot) -> Result<ValType> {
77
8074005
        slot.cell.map_or_else(
78
8064019
            || self.wasm_val_type(slot.ty),
79
9986
            |cell| Ok(super::closure::cell_ref(cell)),
80
        )
81
8074005
    }
82

            
83
    /// Restarts the local pool; the closure sources recorded under its indices
84
    /// go with it, or the next body reusing an index would read a stale one.
85
2155276
    pub fn reset_locals(&mut self, symbols: &mut crate::runtime::SymbolTable) {
86
2155276
        symbols.forget_local_closure_bodies();
87
2155276
        self.next_local = LOCAL_POOL_BASE;
88
2155276
        self.local_types.clear();
89
2155276
        self.serializer =
90
2155276
            super::super::layout::OutputSerializer::new(super::super::expr::LOCAL_OUTPUT_BASE);
91
2155276
    }
92

            
93
    /// The preallocated slots must number exactly [`LOCAL_POOL_BASE`], or every
94
    /// pool local index would name the wrong declaration.
95
2155276
    #[spec(ensures: |ref output| output.is_err() || usize::try_from(LOCAL_POOL_BASE)
96
2155276
        .is_ok_and(|base| output.as_ref().is_ok_and(|locals| locals.len() == base + self.local_types.len())))]
97
2155276
    pub fn build_locals_declaration(&self) -> Result<Vec<(u32, ValType)>> {
98
2155276
        let preallocated: [(u32, ValType); 6] = [
99
2155276
            (1, self.string_ref()),
100
2155276
            (1, ValType::I32),
101
2155276
            (1, ValType::I32),
102
2155276
            (1, self.ratio_ref()),
103
2155276
            (1, ValType::I32),
104
2155276
            (1, ValType::I32),
105
2155276
        ];
106
2155276
        let mut locals: Vec<(u32, ValType)> = preallocated.to_vec();
107
2155276
        for slot in &self.local_types {
108
7787884
            locals.push((1, self.slot_val_type(slot)?));
109
        }
110
2155276
        Ok(locals)
111
2155276
    }
112

            
113
    #[spec(
114
2352713
        captures: before = self.type_count,
115
2352713
        ensures: |ref output| output
116
2352713
            .as_ref()
117
2352713
            .ok()
118
2352713
            .is_none_or(|idx| *idx == before && self.type_count == before + 1),
119
    )]
120
2352713
    pub fn register_type(&mut self) -> Result<u32> {
121
2352713
        let idx = bump(&mut self.type_count, "type")?;
122
2352713
        self.types.ty().subtype(&SubType {
123
2352713
            is_final: true,
124
2352713
            supertype_idxs: Vec::new(),
125
2352713
            composite_type: CompositeType {
126
2352713
                inner: CompositeInnerType::Array(ArrayType(FieldType {
127
2352713
                    element_type: StorageType::I8,
128
2352713
                    mutable: true,
129
2352713
                })),
130
2352713
                shared: false,
131
2352713
                describes: None,
132
2352713
                descriptor: None,
133
2352713
            },
134
2352713
        });
135
2352713
        Ok(idx)
136
2352713
    }
137

            
138
    /// Registers a mutable `(array (mut i64))` type. Used for the commodity
139
    /// unit-term (ADR-0028): a flat array of sorted `(hi, lo, exp)` i64 triples.
140
    #[spec(
141
2352713
        captures: before = self.type_count,
142
2352713
        ensures: |ref output| output
143
2352713
            .as_ref()
144
2352713
            .ok()
145
2352713
            .is_none_or(|idx| *idx == before && self.type_count == before + 1),
146
    )]
147
2352713
    pub fn register_i64_array_type(&mut self) -> Result<u32> {
148
2352713
        let idx = bump(&mut self.type_count, "type")?;
149
2352713
        self.types.ty().subtype(&SubType {
150
2352713
            is_final: true,
151
2352713
            supertype_idxs: Vec::new(),
152
2352713
            composite_type: CompositeType {
153
2352713
                inner: CompositeInnerType::Array(ArrayType(FieldType {
154
2352713
                    element_type: StorageType::Val(ValType::I64),
155
2352713
                    mutable: true,
156
2352713
                })),
157
2352713
                shared: false,
158
2352713
                describes: None,
159
2352713
                descriptor: None,
160
2352713
            },
161
2352713
        });
162
2352713
        Ok(idx)
163
2352713
    }
164

            
165
    #[spec(
166
14116280
        captures: before = self.type_count,
167
14116280
        ensures: |ref output| output
168
14116280
            .as_ref()
169
14116280
            .ok()
170
14116280
            .is_none_or(|idx| *idx == before && self.type_count == before + 1),
171
    )]
172
14116280
    pub fn register_struct_type(&mut self, fields: &[ValType]) -> Result<u32> {
173
14116280
        let idx = bump(&mut self.type_count, "type")?;
174
14116280
        self.types.ty().subtype(&struct_subtype(fields));
175
14116280
        Ok(idx)
176
14116280
    }
177

            
178
    /// Registers one struct type per member of `structs` as ONE recursion
179
    /// group, in order. WasmGC type identity is iso-recursive — (group,
180
    /// position), not shape — so two members with identical fields (the
181
    /// Account and Transaction entities, say) are distinct types a
182
    /// `ref.test` tells apart, where each in its own group would be the same
183
    /// canonical type.
184
    #[spec(
185
2352713
        captures: before = self.type_count,
186
2352713
        ensures: |ref output| output
187
2352713
            .as_ref()
188
2352713
            .ok()
189
2352713
            .is_none_or(|indices| indices.len() == structs.len()
190
2352713
                && self.type_count == before + structs.len() as u32),
191
    )]
192
2352713
    pub fn register_struct_rec_group(&mut self, structs: &[Vec<ValType>]) -> Result<Vec<u32>> {
193
2352713
        let indices = structs
194
2352713
            .iter()
195
16468991
            .map(|_| bump(&mut self.type_count, "type"))
196
            .collect::<Result<Vec<_>>>()?;
197
2352713
        self.types
198
2352713
            .ty()
199
16468991
            .rec(structs.iter().map(|fields| struct_subtype(fields)));
200
2352713
        Ok(indices)
201
2352713
    }
202

            
203
    /// Errors if `name` is already bound in `func_names`. The name space is a
204
    /// closed universe (built-in helpers + reserved imports `__nomi_raise` /
205
    /// `log` / `__nomi_catch_each` + user host fns + unique monomorph/lambda
206
    /// helper names), and a silent overwrite would re-point an already-resolved
207
    /// caller at the wrong index. Notably this rejects a user `HostFnSpec` whose
208
    /// `import_name` collides with a reserved built-in (e.g. `"log"`), which
209
    /// would otherwise misroute PRINT/DISPLAY to the user fn or emit invalid
210
    /// wasm on a signature mismatch — surfaced as a structured `Error::Compile`.
211
243112306
    fn reject_duplicate_func_name(&self, name: &str) -> Result<()> {
212
243112306
        if self.func_names.contains_key(name) {
213
1
            return Err(Error::Compile(format!(
214
1
                "wasm function name '{name}' is already registered (reserved built-in or duplicate host fn)"
215
1
            )));
216
243112305
        }
217
243112305
        Ok(())
218
243112306
    }
219

            
220
    /// Imports occupy the low function indices, so every import must be
221
    /// registered before the first local function takes its index.
222
    #[spec(
223
67053047
        requires: self.local_func_count == 0,
224
67053047
        captures: before = self.import_func_count,
225
        ensures: |ref output| [
226
67053047
            output.as_ref().ok().is_none_or(|idx| *idx == before && self.import_func_count == before + 1),
227
67053047
            output.as_ref().ok().is_none_or(|idx| self.func_names.get(name) == Some(idx)),
228
        ],
229
    )]
230
67053047
    pub fn register_import(
231
67053047
        &mut self,
232
67053047
        module: &str,
233
67053047
        name: &str,
234
67053047
        params: &[ValType],
235
67053047
        results: &[ValType],
236
67053047
    ) -> Result<u32> {
237
67053047
        self.reject_duplicate_func_name(name)?;
238
67053046
        let type_idx = self.get_or_create_func_type(params, results)?;
239
67053046
        self.imports
240
67053046
            .import(module, name, WasmEntityType::Function(type_idx));
241
67053046
        let func_idx = bump(&mut self.import_func_count, "imported function")?;
242
67053046
        self.func_names.insert(name.to_string(), func_idx);
243
67053046
        Ok(func_idx)
244
67053047
    }
245

            
246
    /// Reserves a stable wasm function index for `name` *before* its
247
    /// body is emitted, and returns the new index. The function
248
    /// section already accounts for the slot at this point, so any
249
    /// body emitted afterward can `call $name` (including itself for
250
    /// recursion) by looking the index up via [`Self::declared_func_index`].
251
    /// The body must land on `pending_helpers` in the order matching the
252
    /// reservation sequence; later phases drain that queue into the code
253
    /// section.
254
    #[spec(
255
176059259
        captures: [imports = self.import_func_count, locals = self.local_func_count],
256
176059259
        ensures: self.import_func_count == imports,
257
        ensures: |ref output| [
258
176059259
            output.as_ref().ok().is_none_or(|idx| *idx == imports + locals),
259
176059259
            output.is_err() || self.local_func_count == locals + 1,
260
176059259
            output.as_ref().ok().is_none_or(|idx| self.func_names.get(name) == Some(idx)),
261
        ],
262
    )]
263
176059259
    pub fn register_function(
264
176059259
        &mut self,
265
176059259
        name: &str,
266
176059259
        params: &[ValType],
267
176059259
        results: &[ValType],
268
176059259
    ) -> Result<u32> {
269
176059259
        self.reject_duplicate_func_name(name)?;
270
176059259
        let type_idx = self.get_or_create_func_type(params, results)?;
271
176059259
        self.functions.function(type_idx);
272
176059259
        let local_idx = bump(&mut self.local_func_count, "local function")?;
273
176059259
        let func_idx = self
274
176059259
            .import_func_count
275
176059259
            .checked_add(local_idx)
276
            .ok_or_else(|| Error::Compile("wasm function index space exhausted".to_string()))?;
277
176059259
        self.func_names.insert(name.to_string(), func_idx);
278
176059259
        Ok(func_idx)
279
176059259
    }
280

            
281
    /// Exports a previously-declared function by name. The name set is the
282
    /// closed, static universe registered by the constructor, so a miss is a
283
    /// compiler bug — surfaced as a structured `Error::Compile` rather than a
284
    /// `HashMap[key]` panic (CLAUDE.md).
285
48671608
    #[spec(ensures: |ref output| output.is_ok() == self.func_names.contains_key(name))]
286
48671608
    pub fn export_func(&mut self, name: &str) -> Result<()> {
287
48671608
        let idx = self.func_names.get(name).copied().ok_or_else(|| {
288
            Error::Compile(format!(
289
                "internal: cannot export unregistered wasm function '{name}'"
290
            ))
291
        })?;
292
48671608
        self.exports.export(name, ExportKind::Func, idx);
293
48671608
        Ok(())
294
48671608
    }
295

            
296
    /// Looks up a declared function index by name, erroring (never panicking)
297
    /// on a miss. For the rare construction-time helper not covered by a typed
298
    /// `WasmIds` field (e.g. `unit_div`); emit-time code uses `ctx.ids.*`.
299
2352712
    pub(super) fn declared_func_index(&self, name: &str) -> Result<u32> {
300
2352712
        self.func_names.get(name).copied().ok_or_else(|| {
301
            Error::Compile(format!(
302
                "internal: wasm function '{name}' was not registered during context construction"
303
            ))
304
        })
305
2352712
    }
306

            
307
7261752
    pub fn serializer(&mut self) -> &mut super::super::layout::OutputSerializer {
308
7261752
        &mut self.serializer
309
7261752
    }
310

            
311
    #[spec(
312
245655625
        captures: before = self.type_count,
313
245655625
        ensures: self.type_count - before <= 1,
314
        ensures: |ref output| [
315
245655625
            output.as_ref().ok().is_none_or(|idx| *idx < self.type_count),
316
245655625
            output.as_ref().ok().is_none_or(|idx| {
317
245655625
                self.type_cache.get(params).and_then(|inner| inner.get(results)) == Some(idx)
318
245655625
            }),
319
        ],
320
    )]
321
245655625
    pub(super) fn get_or_create_func_type(
322
245655625
        &mut self,
323
245655625
        params: &[ValType],
324
245655625
        results: &[ValType],
325
245655625
    ) -> Result<u32> {
326
245655625
        if let Some(inner) = self.type_cache.get(params)
327
162525654
            && let Some(&idx) = inner.get(results)
328
        {
329
123582855
            return Ok(idx);
330
122072770
        }
331
122072770
        let idx = bump(&mut self.type_count, "type")?;
332
122072770
        self.types
333
122072770
            .ty()
334
122072770
            .function(params.iter().copied(), results.iter().copied());
335
122072770
        self.type_cache
336
122072770
            .entry(params.to_vec())
337
122072770
            .or_default()
338
122072770
            .insert(results.to_vec(), idx);
339
122072770
        Ok(idx)
340
245655625
    }
341

            
342
    #[spec(
343
106276401
        captures: before = self.data_count,
344
106276401
        ensures: |ref output| output
345
106276401
            .as_ref()
346
106276401
            .ok()
347
106276401
            .is_none_or(|idx| *idx == before && self.data_count == before + 1),
348
    )]
349
106276401
    pub fn add_data(&mut self, bytes: &[u8]) -> Result<u32> {
350
106276401
        let idx = bump(&mut self.data_count, "data segment")?;
351
106276401
        debug!(idx, len = bytes.len(), "adding data segment");
352
106276401
        self.data.passive(bytes.iter().copied());
353
106276401
        Ok(idx)
354
106276401
    }
355
}
356

            
357
/// A final struct type of immutable `fields` with no supertype.
358
30585271
fn struct_subtype(fields: &[ValType]) -> SubType {
359
30585271
    let struct_fields: Vec<FieldType> = fields
360
30585271
        .iter()
361
        .map(|vt| FieldType {
362
105872087
            element_type: StorageType::Val(*vt),
363
105872087
            mutable: false,
364
105872087
        })
365
        .collect();
366
30585271
    SubType {
367
30585271
        is_final: true,
368
30585271
        supertype_idxs: Vec::new(),
369
30585271
        composite_type: CompositeType {
370
30585271
            inner: CompositeInnerType::Struct(StructType {
371
30585271
                fields: struct_fields.into_boxed_slice(),
372
30585271
            }),
373
30585271
            shared: false,
374
30585271
            describes: None,
375
30585271
            descriptor: None,
376
30585271
        },
377
30585271
    }
378
30585271
}