1
//! `CONS` constructor. Eval path constant-folds chains; compile path
2
//! pushes typed car/cdr onto the stack and calls `pair_new`.
3
//! `push_pair_car` boxes i32 values (indices range-checked by
4
//! `box_index`); `push_pair_cdr` emits `ref.null pair` for terminal `nil`,
5
//! materializes a constant list, or validates a typed `PairRef(elem)`
6
//! matches the declared element.
7

            
8
use crate::ast::{Expr, PairElement, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::datum::bounded;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::compiler::expr::{
13
    compile_expr, compile_for_effect, compile_for_stack, compile_for_stack_as, emit_box_anyref,
14
    emit_box_cell, eval_value, fold_value, is_untyped, no_list_cell_representation, probe_value,
15
    quoted_datum, serialize_stack_to_output,
16
};
17
use crate::compiler::join::Arm;
18
use crate::error::{Error, Result};
19
use crate::runtime::{SymbolTable, Value};
20

            
21
use super::append::emit_nil_pair_operand;
22
use super::datum::{compile_folded_to_stack, is_datum_result};
23
use super::infer::{chain_pair_element, infer_pair_element, is_scalar_literal};
24
use super::spill::{compile_spilled_chain, lambda_runs_at_runtime};
25

            
26
410633
pub(super) fn cons(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
27
410633
    check_arity(args)?;
28
410631
    let car = eval_value(symbols, &args[0])?;
29
409570
    let cdr = eval_value(symbols, &args[1])?;
30
408940
    let closure_car = lambda_runs_at_runtime(symbols, std::slice::from_ref(&car));
31
408940
    if car.is_wasm_runtime()
32
178426
        || closure_car
33
174417
        || cdr.is_wasm_runtime()
34
162077
        || matches!(cdr.wasm_type(), Some(WasmType::PairRef(_)))
35
    {
36
246863
        let elem = infer_pair_element(&car, &cdr)?;
37
246863
        return Ok(Expr::WasmRuntime(WasmType::PairRef(elem)));
38
162077
    }
39
162077
    bounded(
40
162077
        symbols,
41
162077
        match cdr {
42
118078
            Expr::Datum(inner) => match *inner {
43
                Expr::List(mut elems) => {
44
118078
                    elems.insert(0, car);
45
118078
                    Expr::quoted_list(elems)
46
                }
47
                Expr::Nil => Expr::quoted_list(vec![car]),
48
                other => Expr::quoted(Expr::cons(car, other)),
49
            },
50
39995
            Expr::Nil => Expr::quoted_list(vec![car]),
51
4004
            other => Expr::quoted(Expr::cons(car, other)),
52
        },
53
    )
54
410633
}
55

            
56
814631
fn check_arity(args: &[Expr]) -> Result<()> {
57
814631
    if args.len() != 2 {
58
418
        return Err(Error::Arity {
59
418
            name: "CONS".to_string(),
60
418
            expected: 2,
61
418
            actual: args.len(),
62
418
        });
63
814213
    }
64
814213
    Ok(())
65
814631
}
66

            
67
4994
pub(super) fn compile_cons(
68
4994
    ctx: &mut CompileContext,
69
4994
    emit: &mut FunctionEmitter,
70
4994
    symbols: &mut SymbolTable,
71
4994
    args: &[Expr],
72
4994
) -> Result<()> {
73
4994
    check_arity(args)?;
74
4578
    if let Some(folded) = fold_cons(symbols, args)? {
75
2082
        return compile_expr(ctx, emit, symbols, &folded);
76
2496
    }
77
2496
    let ty = compile_cons_to_stack(ctx, emit, symbols, args)?;
78
2496
    serialize_stack_to_output(ctx, emit, ty)
79
4994
}
80

            
81
/// The datum a fold-safe `(cons …)` folds to, or `None` when the pair is
82
/// built at runtime.
83
403582
fn fold_cons(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Option<Expr>> {
84
403582
    let form = Expr::List(
85
403582
        std::iter::once(Expr::symbol("CONS"))
86
403582
            .chain(args.iter().cloned())
87
403582
            .collect(),
88
403582
    );
89
403582
    Ok(fold_value(symbols, &form)?.filter(is_datum_result))
90
403582
}
91

            
92
399004
pub(super) fn compile_cons_to_stack(
93
399004
    ctx: &mut CompileContext,
94
399004
    emit: &mut FunctionEmitter,
95
399004
    symbols: &mut SymbolTable,
96
399004
    args: &[Expr],
97
399004
) -> Result<WasmType> {
98
    // A fully-constant cons folds to a quoted list datum (e.g. (cons 0 '(1 2 3))
99
    // → '(0 1 2 3)); render it as a datum so value position agrees with the
100
    // effect path instead of trapping when push_pair_cdr meets the quoted cdr.
101
    // Only a runtime car/cdr (PairRef result) takes the pair_new path below.
102
399004
    check_arity(args)?;
103
399004
    if let Some(folded) = fold_cons(symbols, args)? {
104
1684
        return compile_folded_to_stack(ctx, emit, symbols, folded);
105
397320
    }
106
    // If an argument transfers control before the pair is built (a
107
    // `(return-from …)` / `(error …)` — args evaluate left-to-right before the
108
    // call), the rest is dead: the pair is never constructed, so a non-list cdr
109
    // must NOT be rejected. Emit the live prefix (which performs the exit) and
110
    // return a placeholder element. Classify divergence on a CLONE (the exit is
111
    // still recorded by the single emit below).
112
397320
    if crate::compiler::special::form_diverges_scratch(symbols, &args[0])? {
113
845
        let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
114
845
        return Ok(WasmType::PairRef(
115
845
            PairElement::from_wasm_type(ty).unwrap_or(PairElement::AnyRef),
116
845
        ));
117
396475
    }
118
396475
    if crate::compiler::special::form_diverges_scratch(symbols, &args[1])? {
119
        // Car is evaluated (for its effects) then the cdr exits before
120
        // `pair_new`; the car value is dead, so compile it for effect.
121
651
        compile_for_effect(ctx, emit, symbols, &args[0])?;
122
651
        let ty = compile_for_stack(ctx, emit, symbols, &args[1])?;
123
651
        return Ok(WasmType::PairRef(
124
651
            PairElement::from_wasm_type(ty).unwrap_or(PairElement::AnyRef),
125
651
        ));
126
395824
    }
127
    // The element type is decided up front, on a clone, so the live table sees
128
    // each operand's effects once, from its own compilation.
129
395824
    let mut probe = symbols.clone();
130
395824
    let car_resolved = probe_value(&mut probe, &args[0])?;
131
395821
    let cdr_resolved = probe_value(&mut probe, &args[1])?;
132
395821
    let elem = if is_untyped(&cdr_resolved) {
133
630
        PairElement::AnyRef
134
    } else {
135
395191
        infer_pair_element(&car_resolved, &cdr_resolved)?
136
    };
137
395821
    push_pair_car(ctx, emit, symbols, &args[0], elem)?;
138
395399
    push_pair_cdr(ctx, emit, symbols, &args[1], elem, &cdr_resolved)?;
139
391616
    emit.call(ctx.ids.pair_new);
140
391616
    Ok(WasmType::PairRef(elem))
141
399004
}
142

            
143
/// Emit `elem_args` as a nul-terminated `$pair` chain. LIST uses this so it
144
/// never synthesizes a `(CONS …)` form. `elem_args` are the
145
/// ORIGINAL element expressions (emitted once via `push_pair_car`); the
146
/// chain's element type is decided up front from their resolved values by
147
/// [`chain_pair_element`] — the same rule the eval `list` reports — so every
148
/// cell is emitted homogeneously.
149
303718
pub(in crate::compiler) fn compile_pair_chain(
150
303718
    ctx: &mut CompileContext,
151
303718
    emit: &mut FunctionEmitter,
152
303718
    symbols: &mut SymbolTable,
153
303718
    elem_args: &[Expr],
154
303718
) -> Result<WasmType> {
155
303718
    let mut probe = symbols.clone();
156
303718
    let resolved: Vec<Expr> = elem_args
157
303718
        .iter()
158
1586201
        .map(|a| probe_value(&mut probe, a))
159
848
        .collect::<Result<_>>()?;
160
302870
    if lambda_runs_at_runtime(symbols, &resolved) {
161
27765
        return compile_spilled_chain(ctx, emit, symbols, elem_args, &resolved);
162
275105
    }
163
275105
    let elem = chain_pair_element(&resolved)?;
164
275105
    emit_pair_chain(ctx, emit, symbols, elem_args, elem)?;
165
270245
    Ok(WasmType::PairRef(elem))
166
303718
}
167

            
168
/// Materialize a constant list's `elements` (DATA, not expressions) as a
169
/// `$pair` chain whose cells ride `elem`, the element its consumer declared.
170
/// A member the cell push would otherwise RESOLVE (a bare symbol → variable
171
/// lookup, a nested list → a call) is quoted so it stays literal; one with no
172
/// runtime representation then surfaces "cannot compile to WASM stack value".
173
127085
pub(super) fn emit_constant_chain(
174
127085
    ctx: &mut CompileContext,
175
127085
    emit: &mut FunctionEmitter,
176
127085
    symbols: &mut SymbolTable,
177
127085
    elements: Vec<Expr>,
178
127085
    elem: PairElement,
179
127085
) -> Result<()> {
180
127085
    let members: Vec<Expr> = elements
181
127085
        .into_iter()
182
210013
        .map(|e| match e {
183
            Expr::Number(_)
184
            | Expr::String(_)
185
            | Expr::T
186
            | Expr::Nil
187
            | Expr::Instance(_, _)
188
116450
            | Expr::RuntimeValue(Value::Commodity { .. }) => e,
189
93563
            other => Expr::quoted(other),
190
210013
        })
191
        .collect();
192
127085
    for member in &members {
193
210013
        push_constant_car(ctx, emit, symbols, member, elem)?;
194
    }
195
126877
    close_pair_chain(ctx, emit, members.len());
196
126877
    Ok(())
197
127085
}
198

            
199
/// Emit the `pair_new` cells for `elem_args` (original expressions), every car
200
/// at the unified `elem` slot. All cars are pushed in source order, then the
201
/// terminating `nil`, and each `pair_new` folds the top `[car, cdr_ref]` into
202
/// one cell — innermost first — without recursing per element.
203
275105
fn emit_pair_chain(
204
275105
    ctx: &mut CompileContext,
205
275105
    emit: &mut FunctionEmitter,
206
275105
    symbols: &mut SymbolTable,
207
275105
    elem_args: &[Expr],
208
275105
    elem: PairElement,
209
275105
) -> Result<()> {
210
275105
    for car in elem_args {
211
1542535
        push_pair_car(ctx, emit, symbols, car, elem)?;
212
    }
213
270245
    close_pair_chain(ctx, emit, elem_args.len());
214
270245
    Ok(())
215
275105
}
216

            
217
/// Terminates the `count` pushed cars with `nil` and folds each `[car,
218
/// cdr_ref]` pair into a cell, innermost first.
219
424676
pub(super) fn close_pair_chain(ctx: &CompileContext, emit: &mut FunctionEmitter, count: usize) {
220
424676
    emit.ref_null(ctx.ids.ty_pair);
221
424676
    for _ in 0..count {
222
1787312
        emit.call(ctx.ids.pair_new);
223
    }
224
424676
}
225

            
226
1946692
pub(super) fn push_pair_car(
227
1946692
    ctx: &mut CompileContext,
228
1946692
    emit: &mut FunctionEmitter,
229
1946692
    symbols: &mut SymbolTable,
230
1946692
    arg: &Expr,
231
1946692
    elem: PairElement,
232
1946692
) -> Result<()> {
233
1946692
    let resolved = probe_value(&mut symbols.clone(), arg)?;
234
1946692
    check_cell_representable(&resolved, elem)?;
235
1946688
    match elem {
236
228222
        PairElement::AnyRef => push_anyref_car(ctx, emit, symbols, arg),
237
1718466
        _ => push_typed_car(ctx, emit, symbols, arg, elem),
238
    }
239
1946692
}
240

            
241
/// [`push_pair_car`] for a constant list member, which is its own probe.
242
210013
fn push_constant_car(
243
210013
    ctx: &mut CompileContext,
244
210013
    emit: &mut FunctionEmitter,
245
210013
    symbols: &mut SymbolTable,
246
210013
    member: &Expr,
247
210013
    elem: PairElement,
248
210013
) -> Result<()> {
249
210013
    check_cell_representable(member, elem)?;
250
210013
    match elem {
251
124894
        PairElement::AnyRef => push_constant_arm(ctx, emit, symbols, member).map(drop),
252
85119
        _ => push_typed_car(ctx, emit, symbols, member, elem),
253
    }
254
210013
}
255

            
256
/// A nested constant list has a real materialization for an AnyRef cell
257
/// (ADR-0033 Phase 6: `push_anyref_car` builds it as a `$pair` chain), so it
258
/// alone is let through; every OTHER quoted datum (a symbol, a dotted cons, a
259
/// quasiquote) stays a compile error for every cell kind, AnyRef included —
260
/// it has no list-cell representation at all.
261
2156705
fn check_cell_representable(resolved: &Expr, elem: PairElement) -> Result<()> {
262
2156705
    let is_nested_list_literal = matches!(
263
2156705
        quoted_datum(resolved),
264
72555
        Some(Expr::List(elems)) if !elems.is_empty()
265
    );
266
2156705
    if crate::compiler::expr::is_quoted_datum(resolved)
267
72559
        && !(elem == PairElement::AnyRef && is_nested_list_literal)
268
    {
269
4
        return Err(no_list_cell_representation(resolved));
270
2156701
    }
271
2156701
    Ok(())
272
2156705
}
273

            
274
1803585
fn push_typed_car(
275
1803585
    ctx: &mut CompileContext,
276
1803585
    emit: &mut FunctionEmitter,
277
1803585
    symbols: &mut SymbolTable,
278
1803585
    arg: &Expr,
279
1803585
    elem: PairElement,
280
1803585
) -> Result<()> {
281
1803585
    match elem {
282
        // Value cells: a dimension-flexible integer literal coerces to the
283
        // cell's stratum (Index or Scalar) rather than mismatching the slot.
284
        PairElement::I32 | PairElement::Bool | PairElement::Ratio => {
285
1700958
            compile_for_stack_as(ctx, emit, symbols, arg, elem.as_wasm_type())?;
286
1698836
            emit_box_cell(ctx, emit, elem, elem);
287
1698836
            Ok(())
288
        }
289
        // Reference cells (string / entity / commodity): keep the strict match
290
        // so a `nil` or wrong-typed car stays a COMPILE error rather than a
291
        // typed null that `CAR`'s non-null cast would trap on at runtime.
292
        _ => {
293
102627
            let actual = compile_for_stack(ctx, emit, symbols, arg)?;
294
102627
            if PairElement::from_wasm_type(actual) != Some(elem) {
295
                return Err(Error::Compile(format!(
296
                    "CONS car: expected {elem} to match the inferred pair element, got {actual}"
297
                )));
298
102627
            }
299
102627
            Ok(())
300
        }
301
    }
302
1803585
}
303

            
304
/// A heterogeneous cell: `nil` rides as a null ref (never an i31 zero), a
305
/// scalar literal as a ratio (never a truncated index), a nested constant
306
/// list as a real `$pair` chain (ADR-0033 Phase 6 — it has no scalar/string
307
/// representation, so it must not fall through to the printed-datum path
308
/// `compile_for_stack` takes for a quoted list used as an ordinary value),
309
/// anything else as its own value boxed to anyref. The arm names what was
310
/// pushed, for a home that must read it back.
311
355353
pub(in crate::compiler) fn push_anyref_arm(
312
355353
    ctx: &mut CompileContext,
313
355353
    emit: &mut FunctionEmitter,
314
355353
    symbols: &mut SymbolTable,
315
355353
    arg: &Expr,
316
355353
) -> Result<Arm> {
317
355353
    let resolved = probe_value(&mut symbols.clone(), arg)?;
318
355353
    push_resolved_arm(ctx, emit, symbols, arg, &resolved)
319
355353
}
320

            
321
/// [`push_anyref_arm`] for a carried constant, which is its own probe: the
322
/// session prologue pushes one per instance field, so it must not clone the
323
/// symbol table.
324
2068676
pub(in crate::compiler) fn push_constant_arm(
325
2068676
    ctx: &mut CompileContext,
326
2068676
    emit: &mut FunctionEmitter,
327
2068676
    symbols: &mut SymbolTable,
328
2068676
    value: &Expr,
329
2068676
) -> Result<Arm> {
330
2068676
    push_resolved_arm(ctx, emit, symbols, value, value)
331
2068676
}
332

            
333
/// [`push_anyref_arm`] for an `arg` whose probe is `resolved`.
334
2424029
fn push_resolved_arm(
335
2424029
    ctx: &mut CompileContext,
336
2424029
    emit: &mut FunctionEmitter,
337
2424029
    symbols: &mut SymbolTable,
338
2424029
    arg: &Expr,
339
2424029
    resolved: &Expr,
340
2424029
) -> Result<Arm> {
341
2424029
    if matches!(resolved, Expr::Nil) {
342
22992
        if !matches!(arg, Expr::Nil) {
343
10626
            compile_for_effect(ctx, emit, symbols, arg)?;
344
12366
        }
345
22992
        emit.ref_null_any();
346
22992
        return Ok(Arm::Nil);
347
2401037
    }
348
2401037
    if is_scalar_literal(resolved) {
349
2365
        compile_for_stack_as(ctx, emit, symbols, arg, WasmType::Ratio)?;
350
2365
        return Ok(Arm::Value(WasmType::Ratio));
351
2398672
    }
352
2398672
    if let Some(Expr::List(members)) = quoted_datum(resolved)
353
75074
        && !members.is_empty()
354
    {
355
        // `members` are DATA, not expressions: a nested `(+ 1 2)` here means
356
        // "the list containing the symbol +, the number 1 and the number 2",
357
        // never a call to evaluate. `emit_constant_chain` (used for the same
358
        // shape in a CONS cdr) quotes every non-self-evaluating member before
359
        // materializing it, so a nested list stays a nested list at every
360
        // recursion level and a bare symbol renders as its printed name
361
        // instead of resolving a lexical variable. And since `resolved` — not
362
        // `arg` — is what carries this datum, `arg`'s own producer (if it has
363
        // one; a literal quote has none) must still run for effect exactly
364
        // once, matching `push_pair_cdr`'s rule for the identical shape.
365
75074
        if !matches!(arg, Expr::Quote(_) | Expr::Datum(_)) {
366
4584
            compile_for_effect(ctx, emit, symbols, arg)?;
367
70490
        }
368
75071
        emit_constant_chain(ctx, emit, symbols, members.clone(), PairElement::AnyRef)?;
369
75071
        return Ok(Arm::Value(WasmType::PairRef(PairElement::AnyRef)));
370
2323598
    }
371
2323598
    let actual = compile_for_stack(ctx, emit, symbols, arg)?;
372
2320029
    emit_box_anyref(ctx, emit, actual);
373
2320029
    Ok(Arm::Value(actual))
374
2424029
}
375

            
376
/// [`push_anyref_arm`] for a caller that only wants the value pushed.
377
233039
pub(in crate::compiler) fn push_anyref_car(
378
233039
    ctx: &mut CompileContext,
379
233039
    emit: &mut FunctionEmitter,
380
233039
    symbols: &mut SymbolTable,
381
233039
    arg: &Expr,
382
233039
) -> Result<()> {
383
233039
    push_anyref_arm(ctx, emit, symbols, arg).map(drop)
384
233039
}
385

            
386
395399
fn push_pair_cdr(
387
395399
    ctx: &mut CompileContext,
388
395399
    emit: &mut FunctionEmitter,
389
395399
    symbols: &mut SymbolTable,
390
395399
    arg: &Expr,
391
395399
    elem: PairElement,
392
395399
    resolved: &Expr,
393
395399
) -> Result<()> {
394
395399
    if matches!(resolved, Expr::Nil) {
395
10617
        if !matches!(arg, Expr::Nil) {
396
416
            compile_for_effect(ctx, emit, symbols, arg)?;
397
10201
        }
398
10409
        emit.ref_null(ctx.ids.ty_pair);
399
10409
        return Ok(());
400
384782
    }
401
384782
    if let Some(Expr::List(members)) = quoted_datum(resolved) {
402
1670
        if !matches!(arg, Expr::Quote(_) | Expr::Datum(_)) {
403
1462
            compile_for_effect(ctx, emit, symbols, arg)?;
404
208
        }
405
1670
        return emit_constant_chain(ctx, emit, symbols, members.clone(), elem);
406
383112
    }
407
383112
    let actual = compile_for_stack(ctx, emit, symbols, arg)?;
408
382690
    match actual {
409
        // The widened-AnyRef case accepts any typed pair as the cdr —
410
        // `$pair` already carries `anyref` cars (a bool car rides the same
411
        // ref.null/`$t` representation in either cell kind, ADR-0033), so no
412
        // per-element rebuild is needed once we've decided to ride the
413
        // heterogeneous variant.
414
378044
        WasmType::PairRef(actual_elem) if actual_elem == elem || elem == PairElement::AnyRef => {
415
378044
            Ok(())
416
        }
417
        WasmType::PairRef(actual_elem) => Err(Error::Compile(format!(
418
            "CONS cdr element type mismatch — expected pair<{elem}>, got pair<{actual_elem}>"
419
        ))),
420
1493
        WasmType::Bool => emit_nil_pair_operand(ctx, emit),
421
3153
        other => Err(Error::Compile(format!(
422
3153
            "CONS cdr must be a pair or nil, got {other}"
423
3153
        ))),
424
    }
425
395399
}