1
//! Tier 1.5 monomorph emit — closes Gap B.
2
//!
3
//! When a defun is called with a runtime arg the inline const-fold path
4
//! has no terminating walk (each step re-enters the body without
5
//! reducing toward a base case). The runtime-call path emits the body
6
//! once as a real wasm fn keyed on the call-site argument signature
7
//! and lowers each call site to `call $monomorph_idx`. The recursion
8
//! itself terminates at runtime via the same mechanism every wasm fn
9
//! uses — the wasm call stack — so the compile-time walk no longer has
10
//! to.
11
//!
12
//! Cache: [`super::super::context::monomorph::MonomorphCache`] is
13
//! keyed by `(defun_name, [arg_wasm_types])`. Distinct call-site
14
//! signatures emit distinct wasm fns; identical ones share.
15
//!
16
//! Type inference: we don't have a declared return type at the call
17
//! site. The body's return type is determined by emitting the body —
18
//! but the body may self-call, and that self-call needs a concrete
19
//! return type up front. Each guess is one [`recompile`] pass:
20
//! 1. Intern the guess — the first non-closure param's type (or `Ratio` for
21
//!    nullary recursion), then the previous pass's observation.
22
//! 2. Register the function with the guessed return type and emit the body
23
//!    with `compile_for_stack`. Self-calls inside the body resolve through
24
//!    the cache entry registered with it and emit `call $self_idx`.
25
//! 3. If the observed return type matches the guess, queue the helper
26
//!    and commit.
27
//! 4. Otherwise discard the pass, keeping only the observed type in its
28
//!    structural form: a closure signature interned by the discarded pass
29
//!    does not survive the rollback. Hard cap at 4 passes — anything that
30
//!    doesn't converge is a structured `Error::Compile`.
31

            
32
use super::captures::compute_captures;
33
use crate::ast::{Expr, LambdaParams, Place, WasmType};
34
use crate::compiler::binder_key::function_owner;
35
use crate::compiler::context::CompileContext;
36
use crate::compiler::context::closure::cell_ref;
37
use crate::compiler::context::monomorph::{MonomorphEntry, MonomorphKey, Slot};
38
use crate::compiler::emit::FunctionEmitter;
39
use crate::compiler::expr::{compile_for_stack, recursive_ret_guess};
40
use crate::compiler::observations::{Observations, StructuralType};
41
use crate::compiler::recompile::Trial;
42
use crate::compiler::recompile::recompile;
43
use crate::error::{Error, Result};
44
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
45
use wasm_encoder::ValType;
46

            
47
const FIXPOINT_ITER_CAP: usize = 4;
48

            
49
/// Lookup-or-emit pipeline. Returns the cache entry the caller emits
50
/// `call <entry.func_idx>` against. Body is the defun's `Expr::Lambda`
51
/// body; `params` is the defun's parameter list; `arg_types` is the
52
/// call-site argument signature (one wasm type per required param).
53
37100
pub(in crate::compiler) fn lookup_or_emit_monomorph(
54
37100
    ctx: &mut CompileContext,
55
37100
    symbols: &mut SymbolTable,
56
37100
    name: &str,
57
37100
    params: &LambdaParams,
58
37100
    body: &Expr,
59
37100
    arg_types: &[WasmType],
60
37100
    closures: Vec<Option<u32>>,
61
37100
) -> Result<MonomorphEntry> {
62
37100
    if !is_v1_signature(params) {
63
        return Err(Error::Compile(format!(
64
            "runtime-call lowering for '{name}' requires required-only \
65
             parameters; lambdas with &optional/&rest/&key/&aux still go \
66
             through the inline path"
67
        )));
68
37100
    }
69
37100
    if params.required.len() != arg_types.len() {
70
        return Err(Error::Arity {
71
            name: name.to_string(),
72
            expected: params.required.len(),
73
            actual: arg_types.len(),
74
        });
75
37100
    }
76

            
77
    let key = MonomorphKey {
78
37100
        slots: free_slots(ctx, symbols, name, params, body)?,
79
37097
        name: name.to_string(),
80
37097
        definition: symbols.lookup(name).map_or(0, Symbol::function_definition),
81
37097
        epoch: symbols.redefinition_epoch(),
82
37097
        params: arg_types.to_vec(),
83
37097
        closures,
84
    };
85
37097
    if let Some(entry) = ctx.monomorph_cache().get(&key) {
86
20023
        return Ok(entry.clone());
87
17074
    }
88

            
89
17074
    emit_monomorph(ctx, symbols, key, params, body, arg_types)
90
37100
}
91

            
92
/// The runtime names `body` reads or assigns that the caller owns. A function
93
/// is emitted apart from its caller, so each travels as a parameter: by value
94
/// when only read, as the shared cell itself when the unit assigns it. A
95
/// by-value slot is sound only because nothing in the helper's dynamic extent
96
/// can store to it; a store to one is refused.
97
37100
fn free_slots(
98
37100
    ctx: &CompileContext,
99
37100
    symbols: &SymbolTable,
100
37100
    name: &str,
101
37100
    params: &LambdaParams,
102
37100
    body: &Expr,
103
37100
) -> Result<Vec<Slot>> {
104
37100
    let mut view = symbols.clone();
105
37100
    view.hide_caller_lexicals(name)?;
106
37097
    let captures = compute_captures(&view, params, body)?;
107
37097
    let slots: Vec<Slot> = captures
108
37097
        .iter()
109
2148
        .filter_map(|free| match view.lookup(free).and_then(Symbol::value) {
110
8
            Some(Expr::WasmLocal(idx, ty)) => Some(Slot {
111
8
                name: free.to_string(),
112
8
                ty: *ty,
113
8
                cell: ctx.cell_of(*idx).is_some(),
114
8
            }),
115
2140
            _ => None,
116
2148
        })
117
        .collect();
118
37097
    let unshared_store = captures
119
37097
        .stored_captures()
120
        .find(|stored| slots.iter().any(|slot| slot.name == *stored && !slot.cell));
121
37097
    match unshared_store {
122
        Some(stored) => Err(Error::Compile(format!(
123
            "{stored}: a function called with runtime arguments assigns a variable that is not \
124
             a shared cell; not supported yet"
125
        ))),
126
37097
        None => Ok(slots),
127
    }
128
37100
}
129

            
130
37100
fn is_v1_signature(params: &LambdaParams) -> bool {
131
37100
    params.optional.is_empty()
132
37100
        && params.rest.is_none()
133
37100
        && params.key.is_empty()
134
37100
        && params.aux.is_empty()
135
37100
}
136

            
137
17074
fn initial_ret_guess(
138
17074
    ctx: &CompileContext,
139
17074
    name: &str,
140
17074
    params: &LambdaParams,
141
17074
    body: &Expr,
142
17074
    arg_types: &[WasmType],
143
17074
) -> Result<StructuralType> {
144
17074
    let guess = recursive_ret_guess(
145
17074
        name,
146
17074
        &params.required,
147
17074
        body,
148
17074
        arg_types.iter().copied().map(Some),
149
17074
    );
150
17074
    StructuralType::of(guess, ctx)
151
17074
}
152

            
153
17074
fn emit_monomorph(
154
17074
    ctx: &mut CompileContext,
155
17074
    symbols: &mut SymbolTable,
156
17074
    key: MonomorphKey,
157
17074
    params: &LambdaParams,
158
17074
    body: &Expr,
159
17074
    arg_types: &[WasmType],
160
17074
) -> Result<MonomorphEntry> {
161
17074
    let mut guess = initial_ret_guess(ctx, &key.name, params, body, arg_types)?;
162
17074
    let mut blocks = Vec::new();
163
17074
    for _ in 0..FIXPOINT_ITER_CAP {
164
20659
        let pass = ctx.closing_block_probe(|ctx| {
165
20659
            ctx.expecting_block_joins(blocks, |ctx| {
166
20659
                recompile(ctx, symbols, |ctx, symbols| {
167
20659
                    monomorph_pass(ctx, symbols, &key, params, body, arg_types, &guess)
168
20659
                })
169
20659
            })
170
20659
        })?;
171
19810
        match pass {
172
16225
            Trial::Commit(entry) => return Ok(entry),
173
            Trial::Discard(observed) => {
174
3585
                guess = observed.result;
175
3585
                blocks = observed.blocks;
176
            }
177
        }
178
    }
179
    Err(Error::Compile(format!(
180
        "type inference for '{}' did not converge within {} iterations; \
181
         the body's return type appears to depend on itself",
182
        key.name, FIXPOINT_ITER_CAP
183
    )))
184
17074
}
185

            
186
20659
fn monomorph_pass(
187
20659
    ctx: &mut CompileContext,
188
20659
    symbols: &SymbolTable,
189
20659
    key: &MonomorphKey,
190
20659
    params: &LambdaParams,
191
20659
    body: &Expr,
192
20659
    arg_types: &[WasmType],
193
20659
    guess: &StructuralType,
194
20659
) -> Result<Trial<MonomorphEntry, Observations>> {
195
20659
    let expected_ret = guess.intern(ctx)?;
196
20659
    let start = ctx.block_join_start();
197
20659
    match try_emit_body(ctx, symbols, key, params, body, arg_types, expected_ret)? {
198
        Trial::Commit(observed) => {
199
16225
            ctx.monomorph_cache_mut()
200
16225
                .insert(key.clone(), observed.clone());
201
16225
            Ok(Trial::Commit(observed))
202
        }
203
        Trial::Discard(observed_ret) => Ok(Trial::Discard(Observations {
204
3585
            result: StructuralType::of(observed_ret, ctx)?,
205
3585
            blocks: ctx.take_block_joins(start),
206
        })),
207
    }
208
20659
}
209

            
210
20659
fn try_emit_body(
211
20659
    ctx: &mut CompileContext,
212
20659
    symbols: &SymbolTable,
213
20659
    key: &MonomorphKey,
214
20659
    params: &LambdaParams,
215
20659
    body: &Expr,
216
20659
    arg_types: &[WasmType],
217
20659
    expected_ret: WasmType,
218
20659
) -> Result<Trial<MonomorphEntry, WasmType>> {
219
20659
    let mut param_vts = arg_types
220
20659
        .iter()
221
29623
        .map(|t| ctx.wasm_val_type(*t))
222
        .collect::<Result<Vec<_>>>()?;
223
20659
    for slot in &key.slots {
224
4
        param_vts.push(slot_val_type(ctx, slot)?);
225
    }
226
20659
    let result_vt = ctx.wasm_val_type(expected_ret)?;
227
20659
    let helper_name = next_monomorph_helper_name(key, arg_types);
228
20659
    let func_idx = ctx.register_function(&helper_name, &param_vts, &[result_vt])?;
229
20659
    let slot = ctx.reserve_helper();
230

            
231
20659
    let entry = MonomorphEntry {
232
20659
        func_idx,
233
20659
        ret_ty: expected_ret,
234
20659
        slots: key.slots.clone(),
235
20659
    };
236
20659
    ctx.monomorph_cache_mut().insert(key.clone(), entry);
237

            
238
20659
    let arg_count = u32::try_from(arg_types.len())
239
        .map_err(|_| Error::Compile("monomorph param count exceeds u32 range".to_string()))?;
240
20659
    let param_count = u32::try_from(param_vts.len())
241
        .map_err(|_| Error::Compile("monomorph param count exceeds u32 range".to_string()))?;
242

            
243
20659
    let mut local_symbols = symbols.clone();
244
20659
    local_symbols.enter_function_body(function_owner(symbols, Some(&key.name), body));
245
20659
    local_symbols.hide_caller_lexicals(&key.name)?;
246
20659
    local_symbols.drop_runtime_locals();
247
20659
    for (idx, (param_name, ty)) in params.required.iter().zip(arg_types.iter()).enumerate() {
248
29623
        let local_idx = u32::try_from(idx)
249
            .map_err(|_| Error::Compile("monomorph param index exceeds u32 range".to_string()))?;
250
29623
        local_symbols.define(
251
29623
            Symbol::new(param_name, SymbolKind::Variable)
252
29623
                .with_value(Expr::WasmLocal(local_idx, *ty)),
253
29623
        );
254
    }
255

            
256
20659
    let snapshot = ctx.take_local_pool(param_count);
257
20659
    ctx.forget_outer_labels();
258
20659
    record_closure_params(ctx, &mut local_symbols, key);
259

            
260
20659
    let mut helper_emit = FunctionEmitter::new();
261
20659
    let prologue = bind_slots(
262
20659
        ctx,
263
20659
        &mut helper_emit,
264
20659
        symbols,
265
20659
        &mut local_symbols,
266
20659
        arg_count,
267
20659
        &key.slots,
268
20659
    );
269
20659
    if let Err(e) = prologue.and_then(|()| ctx.push_inlining_frame(&mut local_symbols, &key.name)) {
270
        ctx.restore_local_pool(snapshot);
271
        return Err(e);
272
20659
    }
273
20659
    let body_result = compile_for_stack(ctx, &mut helper_emit, &mut local_symbols, body);
274
20659
    ctx.pop_inlining_frame(&mut local_symbols, &key.name)?;
275

            
276
20659
    let observed_ret = match body_result {
277
19810
        Ok(ty) => ty,
278
        Err(e) => {
279
849
            ctx.restore_local_pool(snapshot);
280
849
            return Err(e);
281
        }
282
    };
283

            
284
19810
    let helper_locals = match ctx.build_helper_locals(param_count) {
285
19810
        Ok(locals) => locals,
286
        Err(e) => {
287
            ctx.restore_local_pool(snapshot);
288
            return Err(e);
289
        }
290
    };
291
19810
    let helper_fn = match helper_emit.finish(&helper_locals) {
292
19810
        Ok(helper_fn) => helper_fn,
293
        Err(e) => {
294
            ctx.restore_local_pool(snapshot);
295
            return Err(e);
296
        }
297
    };
298
19810
    ctx.restore_local_pool(snapshot);
299

            
300
19810
    if observed_ret != expected_ret {
301
3585
        return Ok(Trial::Discard(observed_ret));
302
16225
    }
303

            
304
16225
    ctx.fill_helper(slot, helper_fn)?;
305
16225
    Ok(Trial::Commit(MonomorphEntry {
306
16225
        func_idx,
307
16225
        ret_ty: observed_ret,
308
16225
        slots: key.slots.clone(),
309
16225
    }))
310
20659
}
311

            
312
20659
fn record_closure_params(ctx: &CompileContext, symbols: &mut SymbolTable, key: &MonomorphKey) {
313
20659
    for (idx, id) in (0..).zip(&key.closures) {
314
29623
        let source = id.and_then(|id| ctx.monomorph_cache().source(id).cloned());
315
29623
        if let Some((params, body)) = source {
316
17
            symbols.record_closure_body(Place::Local(idx), params, body);
317
29606
        }
318
    }
319
20659
}
320

            
321
4
fn slot_val_type(ctx: &mut CompileContext, slot: &Slot) -> Result<ValType> {
322
4
    if slot.cell {
323
        return Ok(cell_ref(ctx.intern_cell_type(slot.ty)?));
324
4
    }
325
4
    ctx.wasm_val_type(slot.ty)
326
4
}
327

            
328
/// Binds each slot's name to the helper's parameter after the arguments; a
329
/// cell slot is copied into a fresh cell local, which the pool owns.
330
20659
fn bind_slots(
331
20659
    ctx: &mut CompileContext,
332
20659
    helper: &mut FunctionEmitter,
333
20659
    caller: &SymbolTable,
334
20659
    local_symbols: &mut SymbolTable,
335
20659
    arg_count: u32,
336
20659
    slots: &[Slot],
337
20659
) -> Result<()> {
338
20659
    for (param, slot) in (arg_count..).zip(slots) {
339
4
        let idx = if slot.cell {
340
            let cell = ctx.alloc_cell_local(slot.ty)?;
341
            helper.local_get(param);
342
            helper.local_set(cell);
343
            cell
344
        } else {
345
4
            param
346
        };
347
4
        let id = caller
348
4
            .lookup(&slot.name)
349
4
            .map_or(0, Symbol::value_definition);
350
4
        local_symbols.define(
351
4
            Symbol::new(&slot.name, SymbolKind::Variable)
352
4
                .with_value(Expr::WasmLocal(idx, slot.ty))
353
4
                .with_definition(id),
354
4
        );
355
    }
356
20659
    Ok(())
357
20659
}
358

            
359
20663
fn next_monomorph_helper_name(key: &MonomorphKey, arg_types: &[WasmType]) -> String {
360
20663
    let mut name = format!("__defun_{}_d{}_e{}", key.name, key.definition, key.epoch);
361
20663
    for ty in arg_types {
362
29627
        name.push('_');
363
29627
        name.push_str(&format_wasm_type(*ty));
364
    }
365
20663
    for id in key.closures.iter().flatten() {
366
17
        name.push_str(&format!("_src{id}"));
367
    }
368
20663
    for slot in &key.slots {
369
8
        let kind = if slot.cell { "cell" } else { "val" };
370
8
        name.push_str(&format!(
371
8
            "_{}_{kind}_{}",
372
8
            slot.name,
373
8
            format_wasm_type(slot.ty)
374
8
        ));
375
    }
376
20663
    name
377
20663
}
378

            
379
29635
fn format_wasm_type(ty: WasmType) -> String {
380
29635
    match ty {
381
2507
        WasmType::Ratio => "ratio".to_string(),
382
        WasmType::Commodity => "commodity".to_string(),
383
21493
        WasmType::I32 => "i32".to_string(),
384
208
        WasmType::Bool => "bool".to_string(),
385
416
        WasmType::StringRef => "string".to_string(),
386
        WasmType::SymbolRef => "symbol".to_string(),
387
210
        WasmType::PairRef(element) => format!("pair_{element:?}").to_lowercase(),
388
        WasmType::EntityRef(kind) => format!("entity_{}", kind.type_name()),
389
3328
        WasmType::StructRef(id) => format!("struct{}", id.0),
390
17
        WasmType::Closure(sig) => format!("closure{}", sig.0),
391
1456
        WasmType::AnyRef => "any".to_string(),
392
    }
393
29635
}
394

            
395
#[cfg(test)]
396
#[path = "monomorph_tests.rs"]
397
mod tests;