1
//! `CAR` / `CDR` selectors. Eval path resolves through quote / cons /
2
//! list shapes; compile path goes through `struct.get $pair` plus the
3
//! shared `emit_pair_car_downcast` helper so the car comes back at
4
//! the type the static `PairRef(elem)` recorded.
5

            
6
use wasm_encoder::BlockType;
7

            
8
use crate::ast::{Expr, PairElement, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::{
12
    compile_for_stack, describe_operand, eval_value, fold_call, format_expr, member_value,
13
    serialize_stack_to_output,
14
};
15
use crate::error::{Error, Result};
16
use crate::runtime::SymbolTable;
17

            
18
use super::datum::{compile_folded_to_stack, emit_folded_output};
19

            
20
257415
pub(super) fn car(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
21
257415
    if args.len() != 1 {
22
211
        return Err(Error::Arity {
23
211
            name: "CAR".to_string(),
24
211
            expected: 1,
25
211
            actual: args.len(),
26
211
        });
27
257204
    }
28
257204
    let arg = eval_value(symbols, &args[0])?;
29
256776
    match arg.wasm_type() {
30
135335
        Some(WasmType::PairRef(elem)) => return Ok(Expr::WasmRuntime(elem.as_wasm_type())),
31
        // A `$pair` cast from an `AnyRef` list operand has an `AnyRef` car
32
        // (ADR-0033: the dispatch throws a catchable `TYPE-ERROR` for
33
        // anything that isn't null or a `$pair`, so the value here — once it
34
        // compiles — is exactly a `PairRef(AnyRef)`'s element).
35
17971
        Some(WasmType::AnyRef) => return Ok(Expr::WasmRuntime(WasmType::AnyRef)),
36
103470
        _ => {}
37
    }
38
103470
    match arg {
39
417
        Expr::Nil => Ok(Expr::Nil),
40
        Expr::List(elems) => {
41
            if elems.is_empty() {
42
                Ok(Expr::Nil)
43
            } else {
44
                Ok(member_value(elems[0].clone()))
45
            }
46
        }
47
4
        Expr::Cons(car, _) => Ok(member_value(*car)),
48
97622
        Expr::Datum(inner) => match *inner {
49
            Expr::List(elems) => {
50
97622
                if elems.is_empty() {
51
                    Ok(Expr::Nil)
52
                } else {
53
97622
                    Ok(member_value(elems[0].clone()))
54
                }
55
            }
56
            Expr::Cons(car, _) => Ok(member_value(*car)),
57
            Expr::Nil => Ok(Expr::Nil),
58
            other => Err(Error::Compile(format!(
59
                "CAR expects a list, got {}",
60
                format_expr(&other)
61
            ))),
62
        },
63
5427
        other => Err(Error::Compile(format!(
64
5427
            "CAR expects a list, got {}",
65
5427
            format_expr(&other)
66
5427
        ))),
67
    }
68
257415
}
69

            
70
119260
pub(super) fn cdr(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
71
119260
    if args.len() != 1 {
72
209
        return Err(Error::Arity {
73
209
            name: "CDR".to_string(),
74
209
            expected: 1,
75
209
            actual: args.len(),
76
209
        });
77
119051
    }
78
119051
    let arg = eval_value(symbols, &args[0])?;
79
119051
    match arg.wasm_type() {
80
33290
        Some(WasmType::PairRef(elem)) => return Ok(Expr::WasmRuntime(WasmType::PairRef(elem))),
81
        // Same coercion as `car`'s eval mirror: a dispatched `AnyRef`
82
        // operand becomes a `PairRef(AnyRef)` chain once it compiles.
83
        Some(WasmType::AnyRef) => {
84
4374
            return Ok(Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef)));
85
        }
86
81387
        _ => {}
87
    }
88
81387
    match arg {
89
10405
        Expr::Nil => Ok(Expr::Nil),
90
        Expr::List(elems) => {
91
2
            if elems.len() <= 1 {
92
                Ok(Expr::Nil)
93
            } else {
94
2
                Ok(Expr::quoted_list(elems[1..].to_vec()))
95
            }
96
        }
97
        Expr::Cons(_, cdr) => Ok(*cdr),
98
70354
        Expr::Datum(inner) => match *inner {
99
            Expr::List(elems) => {
100
69313
                if elems.len() <= 1 {
101
22568
                    Ok(Expr::Nil)
102
                } else {
103
46745
                    let tail = elems[1..].to_vec();
104
46745
                    Ok(Expr::quoted_list(tail))
105
                }
106
            }
107
1041
            Expr::Cons(_, cdr) => Ok(*cdr),
108
            Expr::Nil => Ok(Expr::Nil),
109
            other => Err(Error::Compile(format!(
110
                "CDR expects a list, got {}",
111
                format_expr(&other)
112
            ))),
113
        },
114
626
        other => Err(Error::Compile(format!(
115
626
            "CDR expects a list, got {}",
116
626
            format_expr(&other)
117
626
        ))),
118
    }
119
119260
}
120

            
121
6908
pub(super) fn compile_car(
122
6908
    ctx: &mut CompileContext,
123
6908
    emit: &mut FunctionEmitter,
124
6908
    symbols: &mut SymbolTable,
125
6908
    args: &[Expr],
126
6908
) -> Result<()> {
127
6908
    check_arity("CAR", args)?;
128
6908
    if let Some(folded) = fold_call(symbols, "CAR", args)? {
129
2514
        return emit_folded_output(ctx, emit, symbols, folded);
130
4394
    }
131
4394
    let ty = compile_car_runtime(ctx, emit, symbols, &args[0])?;
132
3562
    serialize_stack_to_output(ctx, emit, ty)
133
6908
}
134

            
135
1668
pub(super) fn compile_cdr(
136
1668
    ctx: &mut CompileContext,
137
1668
    emit: &mut FunctionEmitter,
138
1668
    symbols: &mut SymbolTable,
139
1668
    args: &[Expr],
140
1668
) -> Result<()> {
141
1668
    check_arity("CDR", args)?;
142
1668
    if let Some(folded) = fold_call(symbols, "CDR", args)? {
143
834
        return emit_folded_output(ctx, emit, symbols, folded);
144
834
    }
145
834
    let ty = compile_cdr_runtime(ctx, emit, symbols, &args[0])?;
146
834
    serialize_stack_to_output(ctx, emit, ty)
147
1668
}
148

            
149
87488
pub(super) fn compile_car_to_stack(
150
87488
    ctx: &mut CompileContext,
151
87488
    emit: &mut FunctionEmitter,
152
87488
    symbols: &mut SymbolTable,
153
87488
    args: &[Expr],
154
87488
) -> Result<WasmType> {
155
87488
    check_arity("CAR", args)?;
156
87488
    if let Some(folded) = fold_call(symbols, "CAR", args)? {
157
9459
        return compile_folded_to_stack(ctx, emit, symbols, folded);
158
78029
    }
159
78029
    compile_car_runtime(ctx, emit, symbols, &args[0])
160
87488
}
161

            
162
82423
fn compile_car_runtime(
163
82423
    ctx: &mut CompileContext,
164
82423
    emit: &mut FunctionEmitter,
165
82423
    symbols: &mut SymbolTable,
166
82423
    arg: &Expr,
167
82423
) -> Result<WasmType> {
168
82423
    let arg_ty = compile_for_stack(ctx, emit, symbols, arg)?;
169
82208
    let elem = match arg_ty {
170
73638
        WasmType::PairRef(e) => e,
171
        WasmType::AnyRef => {
172
5233
            coerce_anyref_to_pair(ctx, emit)?;
173
5233
            PairElement::AnyRef
174
        }
175
3337
        other => return reject_non_list(ctx, emit, symbols, "CAR", arg, other),
176
    };
177
78871
    let pair_ty = WasmType::PairRef(elem);
178
78871
    let pair_local = ctx.alloc_local(pair_ty)?;
179
78871
    let car_ty = elem.as_wasm_type();
180
78871
    emit.local_tee(pair_local);
181
78871
    emit.ref_is_null();
182
78871
    emit.if_block(BlockType::Result(ctx.wasm_val_type(car_ty)?));
183
76571
    emit_nil_car(ctx, emit, elem);
184
76571
    emit.else_block();
185
76571
    emit.local_get(pair_local);
186
76571
    emit.struct_get(ctx.ids.ty_pair, 0);
187
76571
    emit_pair_car_downcast(ctx, emit, elem)?;
188
76571
    emit.block_end()?;
189
76571
    Ok(car_ty)
190
82423
}
191

            
192
128345
fn check_arity(name: &str, args: &[Expr]) -> Result<()> {
193
128345
    if args.len() == 1 {
194
128345
        return Ok(());
195
    }
196
    Err(Error::Arity {
197
        name: name.to_string(),
198
        expected: 1,
199
        actual: args.len(),
200
    })
201
128345
}
202

            
203
/// Consumes a compiled list operand that is not a `$pair` chain. Only a `Bool`
204
/// can be nil, so it is nil when zero and a catchable `TYPE-ERROR` otherwise;
205
/// any other static type is no list.
206
6677
pub(in crate::compiler) fn throw_unless_nil(
207
6677
    ctx: &CompileContext,
208
6677
    emit: &mut FunctionEmitter,
209
6677
    symbols: &SymbolTable,
210
6677
    name: &str,
211
6677
    operand: &Expr,
212
6677
    ty: WasmType,
213
6677
) -> Result<()> {
214
6677
    if ty != WasmType::Bool {
215
6261
        let got = describe_operand(symbols, operand, ty);
216
6261
        return emit.reject_if_live(Error::Compile(format!("{name} expects a list, got {got}")));
217
416
    }
218
416
    emit.if_block(BlockType::Empty);
219
416
    emit.call(ctx.ids.not_a_list);
220
416
    emit.unreachable();
221
416
    emit.block_end()
222
6677
}
223

            
224
/// [`throw_unless_nil`] for a value-returning selector: the nil it leaves is a
225
/// zero bool.
226
4793
pub(in crate::compiler) fn reject_non_list(
227
4793
    ctx: &mut CompileContext,
228
4793
    emit: &mut FunctionEmitter,
229
4793
    symbols: &SymbolTable,
230
4793
    name: &str,
231
4793
    operand: &Expr,
232
4793
    ty: WasmType,
233
4793
) -> Result<WasmType> {
234
4793
    throw_unless_nil(ctx, emit, symbols, name, operand, ty)?;
235
1465
    emit.i32_const(0);
236
1465
    Ok(WasmType::Bool)
237
4793
}
238

            
239
/// The car of a null pair (`(car nil)`), typed for its element: `nil` is a bool
240
/// zero or a null reference. An index, scalar, money or closure value is never
241
/// nil, so such a list throws a catchable `TYPE-ERROR` rather than trapping.
242
76571
fn emit_nil_car(ctx: &CompileContext, emit: &mut FunctionEmitter, elem: PairElement) {
243
76571
    match elem {
244
        PairElement::I32
245
        | PairElement::Ratio
246
        | PairElement::Commodity
247
        | PairElement::Closure(_) => {
248
36556
            emit.call(ctx.ids.car_of_nil);
249
36556
            emit.unreachable();
250
        }
251
1248
        PairElement::Bool => emit.i32_const(0),
252
34561
        PairElement::AnyRef => emit.ref_null_any(),
253
624
        PairElement::StringRef => emit.ref_null(ctx.ids.ty_i8_array),
254
43
        PairElement::Symbol => emit.ref_null(ctx.ids.ty_symbol),
255
2289
        PairElement::Entity(kind) => emit.ref_null(ctx.ids.entity_type(kind)),
256
1250
        PairElement::Struct(_) => emit.ref_null(ctx.ids.ty_struct),
257
    }
258
76571
}
259

            
260
/// Runtime-dispatches an `AnyRef` list operand per ADR-0033: pops it and
261
/// pushes an equivalent `(ref null $pair)` — every `$pair` cell physically
262
/// rides the SAME struct regardless of its static element, so once coerced,
263
/// a caller treats the result exactly like an already-`PairRef(AnyRef)`
264
/// value (its car is `AnyRef`, the standard `PairElement::AnyRef` downcast
265
/// no-op). `ref.test` against a NULLABLE `$pair` accepts null too, so this
266
/// is one test: a `$pair` or nil pass through cast; anything else throws the
267
/// catchable `TYPE-ERROR` ("not a list") — never an uncatchable trap.
268
15373
pub(in crate::compiler) fn coerce_anyref_to_pair(
269
15373
    ctx: &mut CompileContext,
270
15373
    emit: &mut FunctionEmitter,
271
15373
) -> Result<()> {
272
15373
    let local = ctx.alloc_local(WasmType::AnyRef)?;
273
15373
    emit.local_set(local);
274
15373
    emit.local_get(local);
275
15373
    emit.ref_test(ctx.ids.ty_pair);
276
15373
    let pair_ty = ctx.wasm_val_type(WasmType::PairRef(PairElement::AnyRef))?;
277
15373
    emit.if_block(BlockType::Result(pair_ty));
278
15373
    emit.local_get(local);
279
15373
    emit.ref_cast_nullable(ctx.ids.ty_pair);
280
15373
    emit.else_block();
281
15373
    emit.call(ctx.ids.not_a_list);
282
15373
    emit.unreachable();
283
15373
    emit.block_end()?;
284
15373
    Ok(())
285
15373
}
286

            
287
/// Downcasts an `anyref` (just popped from `$pair.car`) to the
288
/// element-specific wasm type recorded in the `PairRef(elem)` static
289
/// info. Single source of truth for the i31/struct/ref.null downcast pattern —
290
/// reused by CAR, DOLIST's body, and the eval-mode pair capture.
291
185650
pub(in crate::compiler) fn emit_pair_car_downcast(
292
185650
    ctx: &CompileContext,
293
185650
    emit: &mut FunctionEmitter,
294
185650
    elem: PairElement,
295
185650
) -> Result<()> {
296
185650
    match elem {
297
        PairElement::I32 => {
298
97944
            emit.ref_cast_i31();
299
97944
            emit.i31_get_s();
300
        }
301
        // A bool car is `ref.null` (nil) / the `$t` singleton (t), never an
302
        // i31 (ADR-0033) — unboxing is "is it non-null?".
303
        PairElement::Bool => {
304
2094
            emit.ref_is_null();
305
2094
            emit.i32_eqz();
306
        }
307
6761
        PairElement::Ratio => emit.ref_cast(ctx.ids.ty_ratio),
308
431
        PairElement::Commodity => emit.ref_cast(ctx.ids.ty_commodity),
309
        // `StringRef` / `EntityRef` cells CAN legitimately hold nil (ADR-0033
310
        // Phase 5): a nullable cast keeps it nil rather than trapping the
311
        // engine on `ref.cast`. The `TYPE-ERROR` null check runs later, only
312
        // when a consumer actually dereferences the value.
313
3362
        PairElement::StringRef => emit.ref_cast_nullable(ctx.ids.ty_i8_array),
314
49
        PairElement::Symbol => emit.ref_cast_nullable(ctx.ids.ty_symbol),
315
3953
        PairElement::Entity(kind) => emit.ref_cast_nullable(ctx.ids.entity_type(kind)),
316
8142
        PairElement::Struct(_) => emit.ref_cast_nullable(ctx.ids.ty_struct),
317
        PairElement::Closure(sig) => {
318
18543
            emit.ref_cast_nullable(ctx.closure_sig(sig)?.closure_type_idx);
319
        }
320
44371
        PairElement::AnyRef => {}
321
    }
322
185234
    Ok(())
323
185650
}
324

            
325
32281
pub(super) fn compile_cdr_to_stack(
326
32281
    ctx: &mut CompileContext,
327
32281
    emit: &mut FunctionEmitter,
328
32281
    symbols: &mut SymbolTable,
329
32281
    args: &[Expr],
330
32281
) -> Result<WasmType> {
331
32281
    check_arity("CDR", args)?;
332
32281
    if let Some(folded) = fold_call(symbols, "CDR", args)? {
333
1041
        return compile_folded_to_stack(ctx, emit, symbols, folded);
334
31240
    }
335
31240
    compile_cdr_runtime(ctx, emit, symbols, &args[0])
336
32281
}
337

            
338
32074
fn compile_cdr_runtime(
339
32074
    ctx: &mut CompileContext,
340
32074
    emit: &mut FunctionEmitter,
341
32074
    symbols: &mut SymbolTable,
342
32074
    arg: &Expr,
343
32074
) -> Result<WasmType> {
344
32074
    let arg_ty = compile_for_stack(ctx, emit, symbols, arg)?;
345
31658
    let pair_ty = match arg_ty {
346
26244
        WasmType::PairRef(_) => arg_ty,
347
        WasmType::AnyRef => {
348
4790
            coerce_anyref_to_pair(ctx, emit)?;
349
4790
            WasmType::PairRef(PairElement::AnyRef)
350
        }
351
624
        other => return reject_non_list(ctx, emit, symbols, "CDR", arg, other),
352
    };
353
    // `(cdr nil)` is nil: a null pair stays null rather than trapping.
354
31034
    let pair_local = ctx.alloc_local(pair_ty)?;
355
31034
    emit.local_tee(pair_local);
356
31034
    emit.ref_is_null();
357
31034
    emit.if_block(BlockType::Result(ctx.wasm_val_type(pair_ty)?));
358
31034
    emit.ref_null(ctx.ids.ty_pair);
359
31034
    emit.else_block();
360
31034
    emit.local_get(pair_local);
361
31034
    emit.struct_get(ctx.ids.ty_pair, 1);
362
31034
    emit.block_end()?;
363
31034
    Ok(pair_ty)
364
32074
}