1
//! Lambda body emit — production-side path that lifts a value-position
2
//! `(lambda ...)` / `(function ...)` from compile-time stringification
3
//! to a real wasm function plus a `$closure_<sig>` GC-struct value
4
//! pushed onto the stack.
5
//!
6
//! Scope of this slice (Tier 1.5 v1, ADR-0027): required-only params
7
//! typed by inference, no keyword/optional/rest/aux. Free-variable captures
8
//! are now lowered: each captured name with a stable local storage
9
//! location rides through a per-scope `$env_<id>` GC struct that the
10
//! helper-fn body unpacks in its prologue. Globally-resolvable names
11
//! (host-fn placeholders, special forms) need no env transport — they
12
//! resolve identically inside the helper through the cloned symbol
13
//! table.
14
//!
15
//! The caller observes a `WasmType::Closure(sig)` on the stack — sig'd
16
//! through the per-context `ClosureRegistry` so distinct lambdas of the
17
//! same shape share `$fn_<sig>` and `$closure_<sig>`. Each capturing
18
//! lambda still gets its own `$env_<id>` so two closures with disjoint
19
//! captures don't collide.
20

            
21
use crate::ast::{ClosureSigId, Expr, LambdaParams, WasmType};
22
use crate::compiler::binder_key::function_owner;
23
use crate::compiler::context::CompileContext;
24
use crate::compiler::context::closure::{EnvField, EnvStructLayout, NO_SITE};
25
use crate::compiler::emit::FunctionEmitter;
26
use crate::compiler::expr::{bind_local, compile_for_stack};
27
use crate::compiler::special::binding::shared::mentions;
28
use crate::compiler::special::needs_cell;
29
use crate::error::{Error, Result};
30
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
31

            
32
use super::anyref::{emit_anyref_to_typed_downcast, promote_result_to_anyref};
33
use super::captures::{CaptureSet, compute_captures};
34
use super::guards::{reject_captured_stores, reject_foreign_locals};
35
use super::shape::{has_v1_param_shape, non_v1_lambda_error};
36
use super::source::closure_source;
37

            
38
/// Wire-level param types for the closure body fn. Catch-each (and other
39
/// future host-iteration callers) pass items as raw anyref values, so
40
/// the body fn must accept anyref params and downcast inside the
41
/// prologue to the declared user-visible param type. The lambda value
42
/// path (FUNCALL/APPLY/etc.) keeps the original typed signature so the
43
/// `call_ref` site doesn't need any boxing.
44
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45
pub(in crate::compiler) enum CallingConvention {
46
    /// Wasm-side typed call_ref: param wasm types match user-visible types.
47
    Typed,
48
    /// Host-side anyref call: every user param is wired as anyref + downcast
49
    /// in the prologue to the user-visible type.
50
    HostAnyref,
51
}
52

            
53
/// Emits a real wasm function for `params`/`body` and pushes a
54
/// `(ref $closure_<sig>)` value onto the caller's stack. Returns the
55
/// signature id so the caller can record `WasmType::Closure(sig)` for
56
/// the stack arm.
57
252588
pub(super) fn emit_lambda_value(
58
252588
    ctx: &mut CompileContext,
59
252588
    emit: &mut FunctionEmitter,
60
252588
    symbols: &mut SymbolTable,
61
252588
    params: &LambdaParams,
62
252588
    body: &Expr,
63
252588
) -> Result<ClosureSigId> {
64
252588
    let inferred = super::param_infer::infer_params(symbols, params, body);
65
252588
    let user_param_types: Vec<WasmType> = inferred
66
252588
        .types
67
252588
        .iter()
68
193496
        .map(|pin| pin.unwrap_or(super::param_infer::PLACEHOLDER))
69
        .collect();
70
252588
    emit_lambda_value_typed(
71
252588
        ctx,
72
252588
        emit,
73
252588
        symbols,
74
252588
        params,
75
252588
        body,
76
252588
        &user_param_types,
77
252588
        CallingConvention::Typed,
78
252588
    )
79
52633
    .map_err(|err| name_unpinned_param(err, (params, body), &inferred.ambiguous))
80
252588
}
81

            
82
/// A dimension error in a body whose used parameter nothing pinned, while
83
/// several dimensions fit it, keeps its message and gains the missing pin as
84
/// its likely cause.
85
52636
fn name_unpinned_param(
86
52636
    err: Error,
87
52636
    (params, body): (&LambdaParams, &Expr),
88
52636
    ambiguous: &[bool],
89
52636
) -> Error {
90
52636
    let unpinned = params
91
52636
        .required
92
52636
        .iter()
93
52636
        .zip(ambiguous)
94
51163
        .find(|(name, ambiguous)| **ambiguous && mentions(body, name));
95
52636
    match (err, unpinned) {
96
1
        (Error::Dimension(message), Some((name, _))) => Error::Dimension(format!(
97
1
            "{message}; cannot infer the type of parameter {name}; pin it with THE"
98
1
        )),
99
52635
        (err, _) => err,
100
    }
101
52636
}
102

            
103
/// Variant that lets the caller declare the user-visible param types
104
/// (the caller's choice). With `HostAnyref` calling convention every
105
/// param is wired as anyref on the wasm side and the prologue downcasts
106
/// to the declared user-visible type before the body runs.
107
264243
pub(in crate::compiler) fn emit_lambda_value_typed(
108
264243
    ctx: &mut CompileContext,
109
264243
    emit: &mut FunctionEmitter,
110
264243
    symbols: &mut SymbolTable,
111
264243
    params: &LambdaParams,
112
264243
    body: &Expr,
113
264243
    user_param_types: &[WasmType],
114
264243
    cc: CallingConvention,
115
264243
) -> Result<ClosureSigId> {
116
264243
    if !has_v1_param_shape(params) {
117
        return Err(non_v1_lambda_error());
118
264243
    }
119
264243
    if user_param_types.len() != params.required.len() {
120
        return Err(Error::Compile(format!(
121
            "lambda emit: param-type count {} does not match required-param count {}",
122
            user_param_types.len(),
123
            params.required.len()
124
        )));
125
264243
    }
126

            
127
264243
    let captures = compute_captures(symbols, params, body)?;
128
263411
    symbols.note_closure_deps(captures.followed_functions());
129
263411
    reject_captured_stores(ctx, symbols, &captures)?;
130
263203
    let env_fields = collect_env_fields(ctx, symbols, &captures)?;
131
263203
    for field in env_fields.iter().filter(|field| field.cell.is_none()) {
132
17332
        if let Some(symbol) = symbols.lookup_mut(&field.name) {
133
17332
            symbol.mark_captured();
134
        }
135
    }
136

            
137
263203
    let (result_ty, helper_func_idx, env_layout) = compile_body_into_helper(
138
263203
        ctx,
139
263203
        symbols,
140
263203
        &params.required,
141
263203
        user_param_types,
142
263203
        body,
143
263203
        &env_fields,
144
263203
        cc,
145
263203
    )?;
146
209940
    let wire_param_types: Vec<WasmType> = match cc {
147
199955
        CallingConvention::Typed => user_param_types.to_vec(),
148
        CallingConvention::HostAnyref => {
149
9985
            user_param_types.iter().map(|_| WasmType::AnyRef).collect()
150
        }
151
    };
152
209940
    let wire_result_ty = match cc {
153
199955
        CallingConvention::Typed => result_ty,
154
9985
        CallingConvention::HostAnyref => WasmType::AnyRef,
155
    };
156
209940
    let sig = ctx.intern_closure_signature(&wire_param_types, wire_result_ty)?;
157

            
158
209940
    let source = closure_source(symbols, (params, body), &env_fields, cc)?;
159
209940
    let site = match source {
160
193722
        Some(source) => ctx.note_closure_source(source)?,
161
16218
        None => NO_SITE,
162
    };
163
209940
    push_closure_value(
164
209940
        ctx,
165
209940
        emit,
166
209940
        symbols,
167
209940
        (sig, site),
168
209940
        helper_func_idx,
169
209940
        env_layout.as_ref(),
170
209940
    )?;
171
209940
    Ok(sig)
172
264243
}
173

            
174
/// Walks `captures` against `symbols`, keeping only names that resolve
175
/// to a `WasmLocal(idx, ty)` — those have a stable outer-scope storage
176
/// location to copy from. `WasmRuntime` placeholders (e.g. registered
177
/// host-fn symbols) are globally resolvable and need no env transport;
178
/// the helper's cloned symbol table sees them unchanged.
179
263203
fn collect_env_fields(
180
263203
    ctx: &CompileContext,
181
263203
    symbols: &SymbolTable,
182
263203
    captures: &CaptureSet,
183
263203
) -> Result<Vec<EnvField>> {
184
263203
    let mut fields = Vec::new();
185
263203
    for name in captures.iter() {
186
24190
        let sym = symbols.lookup(name).ok_or_else(|| {
187
            Error::Compile(format!(
188
                "lambda body references undefined name {name:?} during capture analysis"
189
            ))
190
        })?;
191
24190
        if let Some(Expr::WasmLocal(idx, ty)) = sym.value() {
192
22316
            fields.push(EnvField {
193
22316
                name: name.to_string(),
194
22316
                ty: *ty,
195
22316
                cell: ctx.cell_of(*idx),
196
22316
            });
197
1874
        }
198
    }
199
263203
    Ok(fields)
200
263203
}
201

            
202
/// Body emit pipeline:
203
/// 1. Snapshot caller's local-pool state.
204
/// 2. Build a fresh `FunctionEmitter`, bind params as `WasmLocal`s
205
///    (slot 0 = env anyref, 1..=N = user params).
206
/// 3. If the body captures anything: register an `$env_<id>` struct,
207
///    allocate one helper-side local per field, emit the prologue
208
///    that downcasts param-0 and unpacks the env into those locals,
209
///    rebind captured names in the helper's local symbol table.
210
/// 4. Walk body via `compile_for_stack` to produce the value the helper
211
///    returns.
212
/// 5. End the body, drop the locals declaration, register the helper
213
///    fn (reserves a stable wasm fn idx), queue the body into
214
///    `pending_helpers`.
215
/// 6. Restore caller's local-pool snapshot.
216
263204
fn compile_body_into_helper(
217
263204
    ctx: &mut CompileContext,
218
263204
    symbols: &SymbolTable,
219
263204
    param_names: &[String],
220
263204
    user_param_types: &[WasmType],
221
263204
    body: &Expr,
222
263204
    env_fields: &[EnvField],
223
263204
    cc: CallingConvention,
224
263204
) -> Result<(WasmType, u32, Option<EnvStructLayout>)> {
225
263204
    let env_anyref = ctx.anyref();
226
263204
    let mut helper_param_vts = Vec::with_capacity(user_param_types.len() + 1);
227
263204
    helper_param_vts.push(env_anyref);
228
263204
    for &ty in user_param_types {
229
204112
        let wire_ty = match cc {
230
192664
            CallingConvention::Typed => ty,
231
11448
            CallingConvention::HostAnyref => WasmType::AnyRef,
232
        };
233
204112
        helper_param_vts.push(ctx.wasm_val_type(wire_ty)?);
234
    }
235
263204
    let param_count = u32::try_from(helper_param_vts.len())
236
        .map_err(|_| Error::Compile("lambda parameter count exceeds u32 range".to_string()))?;
237

            
238
263204
    let env_layout = if env_fields.is_empty() {
239
240894
        None
240
    } else {
241
22310
        Some(ctx.intern_env_struct(env_fields)?)
242
    };
243

            
244
263204
    let snapshot = ctx.take_local_pool(param_count);
245

            
246
263204
    let mut local_symbols = symbols.clone();
247
263204
    local_symbols.enter_function_body(function_owner(symbols, None, body));
248
263204
    local_symbols.drop_runtime_locals();
249
263204
    let mut helper_emit = FunctionEmitter::new();
250

            
251
263204
    if let Err(e) = bind_user_params(
252
263204
        ctx,
253
263204
        &mut helper_emit,
254
263204
        &mut local_symbols,
255
263204
        param_names,
256
263204
        user_param_types,
257
263204
        body,
258
263204
        cc,
259
263204
    ) {
260
1
        ctx.restore_local_pool(snapshot);
261
1
        return Err(e);
262
263203
    }
263

            
264
263203
    if let Some(layout) = env_layout.as_ref()
265
22310
        && let Err(e) =
266
22310
            emit_env_unpack_prologue(ctx, &mut helper_emit, symbols, &mut local_symbols, layout)
267
    {
268
        ctx.restore_local_pool(snapshot);
269
        return Err(e);
270
263203
    }
271

            
272
    // A `HostAnyref` callback is host-invoked (catch-each), so an
273
    // uncaught `(error)` throw inside it must be bridged to `__nomi_raise`
274
    // at this boundary — wrap the body in the Tier 3 boundary `try_table`
275
    // (ADR-0026). The wire result is always anyref here, known up-front.
276
    // `Typed` lambdas are in-module calls: NO wrapper, so an enclosing
277
    // `(handler-case)` can still catch their throws.
278
263203
    let result_ty = match cc {
279
        CallingConvention::Typed => {
280
251756
            match compile_for_stack(ctx, &mut helper_emit, &mut local_symbols, body) {
281
199955
                Ok(ty) => ty,
282
                Err(e) => {
283
51801
                    ctx.restore_local_pool(snapshot);
284
51801
                    return Err(e);
285
                }
286
            }
287
        }
288
        CallingConvention::HostAnyref => {
289
            let wrap =
290
11447
                ctx.emit_boundary_wrapper(&mut helper_emit, Some(WasmType::AnyRef), |ctx, emit| {
291
11447
                    let ty = compile_for_stack(ctx, emit, &mut local_symbols, body)?;
292
10193
                    promote_result_to_anyref(ctx, emit, ty)?;
293
9985
                    Ok(())
294
11447
                });
295
11447
            if let Err(e) = wrap {
296
1462
                ctx.restore_local_pool(snapshot);
297
1462
                return Err(e);
298
9985
            }
299
9985
            WasmType::AnyRef
300
        }
301
    };
302
209940
    let helper_locals = match ctx.build_helper_locals(param_count) {
303
209940
        Ok(locals) => locals,
304
        Err(e) => {
305
            ctx.restore_local_pool(snapshot);
306
            return Err(e);
307
        }
308
    };
309
209940
    if let Err(e) = reject_foreign_locals(&helper_emit, param_count, &helper_locals) {
310
        ctx.restore_local_pool(snapshot);
311
        return Err(e);
312
209940
    }
313
209940
    let helper_fn = match helper_emit.finish(&helper_locals) {
314
209940
        Ok(helper_fn) => helper_fn,
315
        Err(e) => {
316
            ctx.restore_local_pool(snapshot);
317
            return Err(e);
318
        }
319
    };
320

            
321
209940
    ctx.restore_local_pool(snapshot);
322

            
323
209940
    let result_vt = ctx.wasm_val_type(result_ty)?;
324
209940
    let helper_name = ctx.next_lambda_helper_name()?;
325
209940
    let func_idx = ctx.register_function(&helper_name, &helper_param_vts, &[result_vt])?;
326
209940
    ctx.declare_funcref(func_idx);
327
209940
    ctx.queue_helper(helper_fn);
328
209940
    Ok((result_ty, func_idx, env_layout))
329
263204
}
330

            
331
/// Binds each user-facing param symbol so the body sees a `WasmLocal`
332
/// of the declared user type. With `Typed` the wasm param already holds
333
/// a typed value — bind directly. With `HostAnyref` the wasm param is
334
/// anyref; allocate a fresh helper-side typed local, downcast the
335
/// anyref into it, and bind the user name to that local.
336
263204
fn bind_user_params(
337
263204
    ctx: &mut CompileContext,
338
263204
    helper: &mut FunctionEmitter,
339
263204
    local_symbols: &mut SymbolTable,
340
263204
    param_names: &[String],
341
263204
    user_param_types: &[WasmType],
342
263204
    body: &Expr,
343
263204
    cc: CallingConvention,
344
263204
) -> Result<()> {
345
263204
    for (idx, (name, ty)) in param_names.iter().zip(user_param_types.iter()).enumerate() {
346
204112
        let wire_local_idx = u32::try_from(idx + 1)
347
            .map_err(|_| Error::Compile("lambda parameter count exceeds u32 range".to_string()))?;
348
204112
        let bound_idx = match cc {
349
192664
            CallingConvention::Typed => wire_local_idx,
350
            CallingConvention::HostAnyref => {
351
11448
                let typed_local = ctx.alloc_local(*ty)?;
352
11448
                helper.local_get(wire_local_idx);
353
11448
                emit_anyref_to_typed_downcast(ctx, helper, *ty)?;
354
11447
                helper.local_set(typed_local);
355
11447
                typed_local
356
            }
357
        };
358
204111
        let bound_idx = if needs_cell(local_symbols, name, std::slice::from_ref(body))? {
359
6
            helper.local_get(bound_idx);
360
6
            bind_local(ctx, helper, *ty, true)?
361
        } else {
362
204105
            bound_idx
363
        };
364
204111
        local_symbols.define(
365
204111
            Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmLocal(bound_idx, *ty)),
366
204111
        );
367
    }
368
263203
    Ok(())
369
263204
}
370

            
371
/// Emits the helper-fn prologue that unpacks an env-struct into fresh
372
/// helper-side locals. For each captured field: downcast param-0
373
/// (`(ref null any)`) to the concrete env-struct type, read the field,
374
/// stash it in a freshly allocated helper-side local (a cell local when the
375
/// field carries a shared cell), then rebind the captured name in
376
/// `local_symbols` to that local so the body's `compile_for_stack` walks
377
/// resolve captures via `local.get`.
378
22310
fn emit_env_unpack_prologue(
379
22310
    ctx: &mut CompileContext,
380
22310
    helper: &mut FunctionEmitter,
381
22310
    caller: &SymbolTable,
382
22310
    local_symbols: &mut SymbolTable,
383
22310
    layout: &EnvStructLayout,
384
22310
) -> Result<()> {
385
22310
    for (field_idx, field) in layout.fields.iter().enumerate() {
386
22316
        let local_idx = match field.cell {
387
4984
            Some(_) => ctx.alloc_cell_local(field.ty)?,
388
17332
            None => ctx.alloc_local(field.ty)?,
389
        };
390
22316
        let field_idx_u32 = u32::try_from(field_idx)
391
            .map_err(|_| Error::Compile("env-struct field count exceeds u32 range".to_string()))?;
392
22316
        helper.local_get(0);
393
22316
        helper.ref_cast(layout.type_idx);
394
22316
        helper.struct_get(layout.type_idx, field_idx_u32);
395
22316
        helper.local_set(local_idx);
396
22316
        let outer = caller.lookup(&field.name);
397
22316
        local_symbols.define(
398
22316
            Symbol::new(&field.name, SymbolKind::Variable)
399
22316
                .with_value(Expr::WasmLocal(local_idx, field.ty))
400
22316
                .with_definition(outer.map_or(0, Symbol::value_definition))
401
22316
                .with_home(outer.and_then(Symbol::home).cloned()),
402
22316
        );
403
    }
404
22310
    Ok(())
405
22310
}
406

            
407
/// Emits the closure construction sequence at the caller's stack:
408
/// `ref.func $helper` + (env-struct construction or `ref.null any`) +
409
/// `struct.new $closure_<sig>`. Captures are loaded from the caller's
410
/// scope via `local.get` on each captured name's outer-scope local
411
/// index, then bundled into a `$env_<id>` struct whose ref slots into
412
/// the closure's nullable env field.
413
209940
fn push_closure_value(
414
209940
    ctx: &CompileContext,
415
209940
    emit: &mut FunctionEmitter,
416
209940
    symbols: &SymbolTable,
417
209940
    (sig, site): (ClosureSigId, i32),
418
209940
    func_idx: u32,
419
209940
    env_layout: Option<&EnvStructLayout>,
420
209940
) -> Result<()> {
421
209940
    let closure_type_idx = ctx.closure_sig(sig)?.closure_type_idx;
422
209940
    let sig_id = i32::try_from(sig.0)
423
        .map_err(|_| Error::Compile("closure signature id exceeds i32".to_string()))?;
424
209940
    emit.ref_func(func_idx);
425
209940
    match env_layout {
426
21894
        Some(layout) => emit_env_struct_construction(emit, symbols, layout)?,
427
188046
        None => emit.ref_null_any(),
428
    }
429
209940
    emit.i32_const(site);
430
209940
    emit.i32_const(sig_id);
431
209940
    emit.struct_new(closure_type_idx);
432
209940
    Ok(())
433
209940
}
434

            
435
21894
fn emit_env_struct_construction(
436
21894
    emit: &mut FunctionEmitter,
437
21894
    symbols: &SymbolTable,
438
21894
    layout: &EnvStructLayout,
439
21894
) -> Result<()> {
440
21894
    for field in &layout.fields {
441
21900
        let sym = symbols.lookup(&field.name).ok_or_else(|| {
442
            Error::Compile(format!(
443
                "captured name {:?} disappeared from symbol table before env-struct \
444
                 construction",
445
                field.name
446
            ))
447
        })?;
448
21900
        let Some(Expr::WasmLocal(idx, _)) = sym.value() else {
449
            return Err(Error::Compile(format!(
450
                "captured name {:?} no longer resolves to a local at env-struct \
451
                 construction time",
452
                field.name
453
            )));
454
        };
455
21900
        emit.local_get(*idx);
456
    }
457
21894
    emit.struct_new(layout.type_idx);
458
21894
    Ok(())
459
21894
}
460

            
461
#[cfg(test)]
462
#[path = "emit_tests.rs"]
463
mod tests;