1
//! Closure-signature registry.
2
//!
3
//! Tier 1.5 promotes lambdas from compile-time stringification to real
4
//! wasm functions. To pass a lambda around as a runtime value we need
5
//! a wasm GC type that bundles a typed funcref with its captured-env
6
//! ref — that's `$closure_<sig>`. Closures sharing the same
7
//! `(arg-types) -> ret-type` signature share the wasm closure-struct
8
//! type and the funcref signature; their env-struct types vary
9
//! independently per scope so two closures with disjoint captures
10
//! don't collide.
11
//!
12
//! This slice ships the per-signature interner that the
13
//! `WasmType::Closure(sig_id)` arm of `wasm_val_type` resolves through;
14
//! the env-struct allocator and monomorph cache (used to lower
15
//! `(funcall closure-arg ...)` and `(defun ...)` recursion through a
16
//! real fn) land alongside their first call-site so the no-dead-code
17
//! rule stays clean. See `doc/adr/0027-lambda-real-wasm-fn.org` for the
18
//! full design.
19

            
20
mod any_call;
21
#[cfg(test)]
22
mod tests;
23

            
24
use std::collections::HashMap;
25

            
26
use wasm_encoder::{
27
    AbstractHeapType, CompositeInnerType, CompositeType, FieldType, Function, HeapType, RefType,
28
    StorageType, StructType, SubType, ValType,
29
};
30

            
31
pub(crate) use any_call::AnyCallHelper;
32

            
33
use super::{CompileContext, LocalSlot};
34
use crate::ast::{ClosureSigId, WasmType};
35
use crate::error::{Error, Result};
36
use crate::runtime::ClosureSource;
37

            
38
/// Per-signature closure type metadata. Held in `CompileContext` so
39
/// the compiler can look up `$closure_<sig>` and `$fn_<sig>` indices
40
/// from a [`ClosureSigId`] without rehashing the signature on each
41
/// reference. `fn_type_idx` is the typed funcref's wasm type — needed
42
/// at every `call_ref` site so the engine can validate the funcref's
43
/// shape statically.
44
#[derive(Debug, Clone)]
45
pub(crate) struct ClosureSig {
46
    pub id: ClosureSigId,
47
    pub closure_type_idx: u32,
48
    pub fn_type_idx: u32,
49
    pub params: Vec<WasmType>,
50
    pub result: WasmType,
51
}
52

            
53
/// Layout of a per-scope `$env_<id>` struct holding values captured by
54
/// a lambda body. One entry per `CaptureSet` name, in insertion order
55
/// so the outer site (which fills the struct) and the helper-fn body
56
/// (which reads it) walk the same field indices. Field types are
57
/// captured at the point [`CompileContext::intern_env_struct`] is
58
/// called from the lookup of each name in the caller's symbol table.
59
#[derive(Debug, Clone)]
60
pub(crate) struct EnvStructLayout {
61
    pub type_idx: u32,
62
    pub fields: Vec<EnvField>,
63
}
64

            
65
#[derive(Debug, Clone)]
66
pub(crate) struct EnvField {
67
    pub name: String,
68
    pub ty: WasmType,
69
    /// The `$cell_<ty>` type index when the field carries the binding's
70
    /// shared cell rather than a copy of its value.
71
    pub cell: Option<u32>,
72
}
73

            
74
/// Field index of a closure's site: the index of its source among the unit's,
75
/// or [`NO_SITE`].
76
pub(crate) const CLOSURE_SITE_FIELD: u32 = 2;
77

            
78
/// Field index of a closure's signature id. Signatures that lower to the same
79
/// wasm shape (`bool`/`i32`, any `$pair`) share one canonical struct type, so
80
/// only this id tells them apart at runtime.
81
pub(crate) const CLOSURE_SIG_FIELD: u32 = 3;
82

            
83
5086640
fn i32_field() -> FieldType {
84
5086640
    FieldType {
85
5086640
        element_type: StorageType::Val(ValType::I32),
86
5086640
        mutable: false,
87
5086640
    }
88
5086640
}
89

            
90
/// The site of a closure whose source cannot be carried.
91
pub(crate) const NO_SITE: i32 = -1;
92

            
93
/// `(ref null $cell_<ty>)` for the cell struct type `cell_type_idx`.
94
14970
pub(crate) fn cell_ref(cell_type_idx: u32) -> ValType {
95
14970
    ValType::Ref(RefType {
96
14970
        nullable: true,
97
14970
        heap_type: HeapType::Concrete(cell_type_idx),
98
14970
    })
99
14970
}
100

            
101
#[derive(Debug, Default, Clone)]
102
pub(crate) struct ClosureRegistry {
103
    sigs: HashMap<(Vec<WasmType>, WasmType), ClosureSigId>,
104
    by_id: Vec<ClosureSig>,
105
    next_sig_id: u32,
106
    helper_count: u32,
107
    env_struct_count: u32,
108
    cells: HashMap<WasmType, u32>,
109
    sources: Vec<ClosureSource>,
110
    any_calls: Vec<AnyCallHelper>,
111
}
112

            
113
/// A reserved code-section slot; `fill_helper` consumes it, so it fills once.
114
#[derive(Debug, Clone)]
115
pub(crate) struct HelperSlot(usize);
116

            
117
/// Snapshot of `CompileContext`'s local-pool fields so a helper-fn
118
/// emit can carve out a fresh allocator without clobbering the caller's
119
/// in-flight state. Rebound by [`CompileContext::restore_local_pool`].
120
pub(crate) struct LocalPoolSnapshot {
121
    next_local: u32,
122
    local_types: Vec<LocalSlot>,
123
    serializer: super::super::layout::OutputSerializer,
124
    frames: super::frames::FrameJournal,
125
    outer_labels: Vec<String>,
126
}
127

            
128
impl CompileContext {
129
    /// Returns a `(ref null $closure_<sig>)` valtype. Helper for the
130
    /// `WasmType::Closure(sig)` arm of `wasm_val_type`.
131
305799
    pub(crate) fn closure_ref(&self, sig: ClosureSigId) -> Result<ValType> {
132
        Ok(ValType::Ref(RefType {
133
305799
            nullable: true,
134
305799
            heap_type: HeapType::Concrete(self.closure_sig(sig)?.closure_type_idx),
135
        }))
136
305799
    }
137

            
138
895262
    pub(crate) fn closure_sig(&self, sig: ClosureSigId) -> Result<&ClosureSig> {
139
895262
        self.closures
140
895262
            .by_id
141
895262
            .get(sig.0 as usize)
142
2721
            .ok_or_else(|| Error::Compile(format!("unknown closure signature {sig}")))
143
895262
    }
144

            
145
    /// Keeps the source of a closure made in this unit and returns its site.
146
193722
    pub(crate) fn note_closure_source(&mut self, source: ClosureSource) -> Result<i32> {
147
193722
        let site = i32::try_from(self.closures.sources.len())
148
            .map_err(|_| Error::Compile("closure site space exhausted".to_string()))?;
149
193722
        self.closures.sources.push(source);
150
193722
        Ok(site)
151
193722
    }
152

            
153
    /// The source of every closure this unit made, by site.
154
2141122
    pub(crate) fn take_closure_sources(&mut self) -> Vec<ClosureSource> {
155
2141122
        std::mem::take(&mut self.closures.sources)
156
2141122
    }
157

            
158
    /// Look up or register the wasm types behind a closure signature.
159
    /// Returns the same id for repeat calls with the same signature so
160
    /// distinct lambdas with the same shape share `$fn_<sig>` and
161
    /// `$closure_<sig>`.
162
216147
    pub(crate) fn intern_closure_signature(
163
216147
        &mut self,
164
216147
        params: &[WasmType],
165
216147
        result: WasmType,
166
216147
    ) -> Result<ClosureSigId> {
167
216147
        let key = (params.to_vec(), result);
168
216147
        if let Some(id) = self.closures.sigs.get(&key) {
169
25540
            return Ok(*id);
170
190607
        }
171
190607
        let env_anyref = self.anyref();
172
190607
        let mut fn_params = Vec::with_capacity(params.len() + 1);
173
190607
        fn_params.push(env_anyref);
174
190607
        for ty in params {
175
140345
            fn_params.push(self.wasm_val_type(*ty)?);
176
        }
177
190607
        let result_vt = self.wasm_val_type(result)?;
178
190607
        let fn_type_idx = self.get_or_create_func_type(&fn_params, &[result_vt])?;
179

            
180
190607
        let closure_type_idx = self.type_count;
181
190607
        let closure_fields = vec![
182
190607
            FieldType {
183
190607
                element_type: StorageType::Val(ValType::Ref(RefType {
184
190607
                    nullable: false,
185
190607
                    heap_type: HeapType::Concrete(fn_type_idx),
186
190607
                })),
187
190607
                mutable: false,
188
190607
            },
189
190607
            FieldType {
190
190607
                element_type: StorageType::Val(env_anyref),
191
190607
                mutable: false,
192
190607
            },
193
190607
            i32_field(),
194
190607
            i32_field(),
195
        ];
196
190607
        self.types.ty().subtype(&SubType {
197
190607
            is_final: true,
198
190607
            supertype_idxs: vec![self.ids.ty_closure_base],
199
190607
            composite_type: CompositeType {
200
190607
                inner: CompositeInnerType::Struct(StructType {
201
190607
                    fields: closure_fields.into_boxed_slice(),
202
190607
                }),
203
190607
                shared: false,
204
190607
                describes: None,
205
190607
                descriptor: None,
206
190607
            },
207
190607
        });
208
190607
        self.type_count = self
209
190607
            .type_count
210
190607
            .checked_add(1)
211
            .ok_or_else(|| Error::Compile("wasm type index space exhausted".to_string()))?;
212
190607
        let id = ClosureSigId(self.closures.next_sig_id);
213
190607
        self.closures.next_sig_id =
214
190607
            self.closures.next_sig_id.checked_add(1).ok_or_else(|| {
215
                Error::Compile("closure signature id space exhausted".to_string())
216
            })?;
217

            
218
190607
        self.closures.by_id.push(ClosureSig {
219
190607
            id,
220
190607
            closure_type_idx,
221
190607
            fn_type_idx,
222
190607
            params: params.to_vec(),
223
190607
            result,
224
190607
        });
225
190607
        self.closures.sigs.insert(key, id);
226
190607
        Ok(id)
227
216147
    }
228

            
229
    /// Registers the non-final `$closure_base` struct — `(ref func)` code,
230
    /// `anyref` environment — that every `$closure_<sig>` declares as its
231
    /// supertype (its typed `(ref $fn_<sig>)` code field is a covariant
232
    /// refinement), so `ref.test $closure_base` recognises a closure of any
233
    /// signature where a boxed value's kind must be told at runtime.
234
2352713
    pub(super) fn register_closure_base_type(&mut self) -> Result<()> {
235
2352713
        let fields = vec![
236
2352713
            FieldType {
237
2352713
                element_type: StorageType::Val(ValType::Ref(RefType {
238
2352713
                    nullable: false,
239
2352713
                    heap_type: HeapType::Abstract {
240
2352713
                        shared: false,
241
2352713
                        ty: AbstractHeapType::Func,
242
2352713
                    },
243
2352713
                })),
244
2352713
                mutable: false,
245
2352713
            },
246
2352713
            FieldType {
247
2352713
                element_type: StorageType::Val(self.anyref()),
248
2352713
                mutable: false,
249
2352713
            },
250
2352713
            i32_field(),
251
2352713
            i32_field(),
252
        ];
253
2352713
        self.types.ty().subtype(&SubType {
254
2352713
            is_final: false,
255
2352713
            supertype_idxs: Vec::new(),
256
2352713
            composite_type: CompositeType {
257
2352713
                inner: CompositeInnerType::Struct(StructType {
258
2352713
                    fields: fields.into_boxed_slice(),
259
2352713
                }),
260
2352713
                shared: false,
261
2352713
                describes: None,
262
2352713
                descriptor: None,
263
2352713
            },
264
2352713
        });
265
2352713
        self.ids.ty_closure_base = self.type_count;
266
2352713
        self.type_count = self
267
2352713
            .type_count
268
2352713
            .checked_add(1)
269
            .ok_or_else(|| Error::Compile("wasm type index space exhausted".to_string()))?;
270
2352713
        Ok(())
271
2352713
    }
272

            
273
    /// Registers a fresh `$env_<id>` struct type for one captured-name
274
    /// scope. Each call allocates a new wasm type (no dedup) — different
275
    /// lambdas captures different names even when shapes coincide, and
276
    /// the per-call cost is one type-section entry. Caller's
277
    /// responsibility to populate the layout in declared order.
278
22310
    pub(crate) fn intern_env_struct(&mut self, fields: &[EnvField]) -> Result<EnvStructLayout> {
279
22310
        let env_type_idx = self.type_count;
280
22310
        let struct_fields = fields
281
22310
            .iter()
282
22316
            .map(|f| {
283
                Ok(FieldType {
284
                    element_type: StorageType::Val(
285
22316
                        f.cell
286
17404
                            .map_or_else(|| self.wasm_val_type(f.ty), |cell| Ok(cell_ref(cell)))?,
287
                    ),
288
22316
                    mutable: false,
289
                })
290
22316
            })
291
            .collect::<Result<Vec<FieldType>>>()?;
292
22310
        self.types.ty().subtype(&SubType {
293
22310
            is_final: true,
294
22310
            supertype_idxs: Vec::new(),
295
22310
            composite_type: CompositeType {
296
22310
                inner: CompositeInnerType::Struct(StructType {
297
22310
                    fields: struct_fields.into_boxed_slice(),
298
22310
                }),
299
22310
                shared: false,
300
22310
                describes: None,
301
22310
                descriptor: None,
302
22310
            },
303
22310
        });
304
22310
        self.type_count = self
305
22310
            .type_count
306
22310
            .checked_add(1)
307
            .ok_or_else(|| Error::Compile("wasm type index space exhausted".to_string()))?;
308
22310
        self.closures.env_struct_count = self
309
22310
            .closures
310
22310
            .env_struct_count
311
22310
            .checked_add(1)
312
            .ok_or_else(|| Error::Compile("env-struct id space exhausted".to_string()))?;
313
22310
        Ok(EnvStructLayout {
314
22310
            type_idx: env_type_idx,
315
22310
            fields: fields.to_vec(),
316
22310
        })
317
22310
    }
318

            
319
    /// The struct type of a shared cell holding a `ty` value: one mutable
320
    /// field, interned once per value type.
321
10842
    pub(crate) fn intern_cell_type(&mut self, ty: WasmType) -> Result<u32> {
322
10842
        if let Some(&idx) = self.closures.cells.get(&ty) {
323
4990
            return Ok(idx);
324
5852
        }
325
5852
        let idx = self.type_count;
326
        let field = FieldType {
327
5852
            element_type: StorageType::Val(self.wasm_val_type(ty)?),
328
5852
            mutable: true,
329
        };
330
5852
        self.types.ty().subtype(&SubType {
331
5852
            is_final: true,
332
5852
            supertype_idxs: Vec::new(),
333
5852
            composite_type: CompositeType {
334
5852
                inner: CompositeInnerType::Struct(StructType {
335
5852
                    fields: Box::new([field]),
336
5852
                }),
337
5852
                shared: false,
338
5852
                describes: None,
339
5852
                descriptor: None,
340
5852
            },
341
5852
        });
342
5852
        self.type_count = self
343
5852
            .type_count
344
5852
            .checked_add(1)
345
            .ok_or_else(|| Error::Compile("wasm type index space exhausted".to_string()))?;
346
5852
        self.closures.cells.insert(ty, idx);
347
5852
        Ok(idx)
348
10842
    }
349

            
350
    /// Allocates a unique helper-fn name for a lambda body. Used by the
351
    /// emit path so distinct lambda bodies get stable wasm names even
352
    /// when sharing a `ClosureSigId`.
353
209940
    pub(crate) fn next_lambda_helper_name(&mut self) -> Result<String> {
354
209940
        let id = self.closures.helper_count;
355
209940
        self.closures.helper_count = self
356
209940
            .closures
357
209940
            .helper_count
358
209940
            .checked_add(1)
359
            .ok_or_else(|| Error::Compile("lambda helper id space exhausted".to_string()))?;
360
209940
        Ok(format!("__lambda_{id}"))
361
209940
    }
362

            
363
    /// Saves the in-flight local-pool state (local allocator + types +
364
    /// serializer cursor) so a helper-fn body can be emitted into a
365
    /// fresh pool. The new pool numbers locals from `next_local_base`,
366
    /// which the caller picks to match the helper fn's wasm-level
367
    /// layout — script-mode entry points use `LOCAL_POOL_BASE` (5
368
    /// preallocated slots), lambda helpers use `param_count` (no
369
    /// preallocated slots, locals begin immediately after params).
370
    /// Pair with [`Self::restore_local_pool`] once the helper's
371
    /// `Function` has been finished and queued.
372
5099464
    pub(crate) fn take_local_pool(&mut self, next_local_base: u32) -> LocalPoolSnapshot {
373
5099464
        let outer_labels = self.hide_labels_from_body();
374
5099464
        let saved = LocalPoolSnapshot {
375
5099464
            outer_labels,
376
5099464
            next_local: self.next_local,
377
5099464
            local_types: std::mem::take(&mut self.local_types),
378
5099464
            serializer: std::mem::replace(
379
5099464
                &mut self.serializer,
380
5099464
                super::super::layout::OutputSerializer::new(super::super::expr::LOCAL_OUTPUT_BASE),
381
5099464
            ),
382
5099464
            // Outer thresholds/depths are all relative to the enclosing
383
5099464
            // function's emitter — a helper body starts a FRESH emitter at
384
5099464
            // block depth 0, so `block_labels` / `tag_frames` (like
385
5099464
            // `unwind_frames`) cannot carry over. A `(return-from)` / `(go)`
386
5099464
            // inside the helper that names an outer BLOCK/TAGBODY can't
387
5099464
            // reach it anyway (that would cross a real wasm function
388
5099464
            // boundary, which `br` cannot do), so resetting them turns a
389
5099464
            // stale-depth miscompile into a clean "no such BLOCK/TAG" error.
390
5099464
            frames: self.take_frames(),
391
5099464
        };
392
5099464
        self.next_local = next_local_base;
393
5099464
        saved
394
5099464
    }
395

            
396
5099464
    pub(crate) fn restore_local_pool(&mut self, snapshot: LocalPoolSnapshot) {
397
5099464
        self.next_local = snapshot.next_local;
398
5099464
        self.local_types = snapshot.local_types;
399
5099464
        self.serializer = snapshot.serializer;
400
5099464
        self.restore_frames(snapshot.frames);
401
5099464
        self.outer_labels = snapshot.outer_labels;
402
5099464
    }
403

            
404
    /// Builds the locals declaration for a lambda helper fn whose
405
    /// `param_count` slots are reserved (env + user params, all func
406
    /// args). Mirrors [`Self::build_locals_declaration`] but starts
407
    /// numbering after the params and skips the script-mode preallocated
408
    /// pool — helper bodies use the local-pool allocator only.
409
5045350
    pub(crate) fn build_helper_locals(&self, param_count: u32) -> Result<Vec<(u32, ValType)>> {
410
5045350
        let mut locals: Vec<(u32, ValType)> = Vec::with_capacity(self.local_types.len());
411
5045350
        let _ = param_count;
412
5045350
        for slot in &self.local_types {
413
286121
            locals.push((1, self.slot_val_type(slot)?));
414
        }
415
5045350
        Ok(locals)
416
5045350
    }
417

            
418
209943
    pub(crate) fn queue_helper(&mut self, helper: Function) {
419
209943
        self.pending_helpers.push(helper);
420
209943
    }
421

            
422
    /// Holds the code-section slot of a function registered before its
423
    /// body exists, so helpers queued while that body compiles keep the
424
    /// slots their own registrations reserved.
425
4836686
    pub(crate) fn reserve_helper(&mut self) -> HelperSlot {
426
4836686
        self.pending_helpers.push(Function::new([]));
427
4836686
        HelperSlot(self.pending_helpers.len() - 1)
428
4836686
    }
429

            
430
4831619
    pub(crate) fn fill_helper(&mut self, slot: HelperSlot, helper: Function) -> Result<()> {
431
4831619
        let reserved = self
432
4831619
            .pending_helpers
433
4831619
            .get_mut(slot.0)
434
1
            .ok_or_else(|| Error::Compile(format!("no reserved helper slot {}", slot.0)))?;
435
4831618
        *reserved = helper;
436
4831618
        Ok(())
437
4831619
    }
438
}