1
//! `DOLIST` codegen + eval handler.
2
//!
3
//! Two paths: a *runtime* path when the list expression resolves to a
4
//! `WasmType::PairRef(elem)` (typed pair chain on the wasm side), and
5
//! a *constant-fold* path when the list is a compile-time list literal.
6
//! The runtime path delegates downcast emit to
7
//! `super::super::native::emit_pair_car_downcast` so each element type
8
//! gets the right `ref.cast`.
9
//!
10
//! Three result positions share the loop emit (`emit_dolist_runtime_loop`
11
//! / `emit_dolist_const_loop`) and differ only in how the loop's result
12
//! is produced: effect drops it, the value path serializes it to the
13
//! output buffer, the stack path leaves a typed value on the operand
14
//! stack so a consumer (e.g. a `defun` body tail) can read it.
15

            
16
use crate::ast::{Expr, PairElement, WasmType};
17
use crate::compiler::binder_key::{Surface, binder_keys};
18
use crate::compiler::context::CompileContext;
19
use crate::compiler::emit::FunctionEmitter;
20
use crate::compiler::expr::format_form;
21
use crate::compiler::expr::{
22
    classify_stack_type, compile_expr, compile_for_effect, compile_for_stack, compile_nil,
23
    eval_value, fold_value, member_value,
24
};
25
use crate::compiler::join::Arm;
26
use crate::compiler::native::{coerce_anyref_to_pair, emit_pair_car_downcast};
27
use crate::error::{Error, Result, with_article};
28
use crate::reserved::reject_reserved;
29
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
30

            
31
use super::super::binding::shared::needs_cell;
32
use super::super::binding::{box_into_home, home_type};
33
use super::super::setf_scan::collect_setf_targets;
34
use super::common::{body_yields_runtime, mark_runtime_setf_targets, promote_to_wasm_local};
35

            
36
/// Parsed `(dolist (var list [result]) body...)` form.
37
struct DolistSpec<'a> {
38
    var_name: &'a str,
39
    list_expr: &'a Expr,
40
    result_expr: Option<&'a Expr>,
41
    body: &'a [Expr],
42
    key: Option<HomeKey>,
43
}
44

            
45
115690
fn parse_dolist<'a>(
46
115690
    symbols: &SymbolTable,
47
115690
    surface: Surface,
48
115690
    args: &'a [Expr],
49
115690
) -> Result<DolistSpec<'a>> {
50
115690
    if args.len() < 2 {
51
625
        return Err(Error::Compile(
52
625
            "DOLIST requires a variable specification and at least one body form".to_string(),
53
625
        ));
54
115065
    }
55

            
56
115065
    let var_spec = args[0].as_list().ok_or_else(|| {
57
211
        Error::Compile(format!(
58
211
            "DOLIST: expected variable specification list, got {}",
59
211
            format_form(&args[0])
60
211
        ))
61
211
    })?;
62

            
63
114854
    if var_spec.len() < 2 || var_spec.len() > 3 {
64
208
        return Err(Error::Compile(
65
208
            "DOLIST: variable specification must be (var list) or (var list result)".to_string(),
66
208
        ));
67
114646
    }
68

            
69
114646
    let var_name = var_spec[0].as_symbol().ok_or_else(|| {
70
211
        Error::Compile(format!(
71
211
            "DOLIST: variable must be a symbol, got {}",
72
211
            format_form(&var_spec[0])
73
211
        ))
74
211
    })?;
75

            
76
114435
    reject_reserved(symbols, var_name)?;
77
114432
    let key = binder_keys(
78
114432
        symbols,
79
114432
        surface,
80
114432
        ("DOLIST", args),
81
114432
        [(var_name, false, args[1..].iter().collect())],
82
114432
    )
83
114432
    .pop()
84
114432
    .flatten();
85

            
86
114432
    Ok(DolistSpec {
87
114432
        var_name,
88
114432
        list_expr: &var_spec[1],
89
114432
        result_expr: var_spec.get(2),
90
114432
        body: &args[1..],
91
114432
        key,
92
114432
    })
93
115690
}
94

            
95
/// Elements of a compile-time-constant list value, or an error if the
96
/// list expression didn't fold to a list.
97
35918
fn const_list_elements(list_value: &Expr) -> Result<Vec<Expr>> {
98
35918
    let to_list = |inner: &Expr| match inner {
99
34946
        Expr::List(elems) => Ok(elems.clone()),
100
763
        Expr::Nil => Ok(vec![]),
101
209
        _ => Err(Error::Compile(
102
209
            "DOLIST: list expression must evaluate to a list".to_string(),
103
209
        )),
104
35918
    };
105
35918
    match list_value {
106
34946
        Expr::Datum(inner) => to_list(inner),
107
972
        other => to_list(other),
108
    }
109
35918
}
110

            
111
/// The loop variable bound to one extracted element, as the datum CL gives
112
/// it: a bare symbol element of `'(g)` is bound quoted, so a read of the
113
/// variable is the symbol `G` and never a read of `g` (0014 obligation (f)).
114
/// Binds in the open frame, which restores the variable's value cell.
115
268806
fn bind_loop_var(symbols: &mut SymbolTable, var_name: &str, element: Expr) {
116
268806
    symbols.define_scoped(
117
268806
        Symbol::new(var_name, SymbolKind::Variable).with_value(member_value(element)),
118
268806
    );
119
268806
}
120

            
121
/// Runs `f` (the result form) with the loop variable bound to `nil`, as CL
122
/// binds it once the list is exhausted.
123
5150
fn with_exit_binding<T>(
124
5150
    symbols: &mut SymbolTable,
125
5150
    var_name: &str,
126
5150
    f: impl FnOnce(&mut SymbolTable) -> Result<T>,
127
5150
) -> Result<T> {
128
5150
    symbols.with_scope(|symbols| {
129
5150
        bind_loop_var(symbols, var_name, Expr::Nil);
130
5150
        f(symbols)
131
5150
    })
132
5150
}
133

            
134
/// The DOLIST form `args` spell, for the whole-form fold.
135
52842
fn dolist_form_of(args: &[Expr]) -> Expr {
136
52842
    Expr::List(
137
52842
        std::iter::once(Expr::symbol("DOLIST"))
138
52842
            .chain(args.iter().cloned())
139
52842
            .collect(),
140
52842
    )
141
52842
}
142

            
143
/// Emits the runtime DOLIST loop: walks the typed `$pair` chain, binding
144
/// each car to the loop variable and running the body for effect. Leaves
145
/// the loop variable's symbol-table entry restored and emits no result —
146
/// the caller decides effect/value/stack result handling.
147
34882
fn emit_dolist_runtime_loop(
148
34882
    ctx: &mut CompileContext,
149
34882
    emit: &mut FunctionEmitter,
150
34882
    symbols: &mut SymbolTable,
151
34882
    spec: &DolistSpec<'_>,
152
34882
) -> Result<()> {
153
34882
    let list_ty = compile_for_stack(ctx, emit, symbols, spec.list_expr)?;
154
34881
    let elem = match list_ty {
155
34673
        WasmType::PairRef(elem) => elem,
156
        WasmType::AnyRef => {
157
208
            coerce_anyref_to_pair(ctx, emit)?;
158
208
            PairElement::AnyRef
159
        }
160
        other => {
161
            return Err(Error::Compile(format!(
162
                "DOLIST: list expression must evaluate to a list, got {} value",
163
                with_article(other)
164
            )));
165
        }
166
    };
167
34881
    let pair_local = ctx.alloc_local(WasmType::PairRef(elem))?;
168
34881
    emit.local_set(pair_local);
169
34881
    symbols.with_scope(|symbols| emit_runtime_walk(ctx, emit, symbols, spec, elem, pair_local))
170
34882
}
171

            
172
/// The walk over the `$pair` chain in `pair_local`, inside the frame that
173
/// restores the loop variable.
174
34881
fn emit_runtime_walk(
175
34881
    ctx: &mut CompileContext,
176
34881
    emit: &mut FunctionEmitter,
177
34881
    symbols: &mut SymbolTable,
178
34881
    spec: &DolistSpec<'_>,
179
34881
    elem: PairElement,
180
34881
    pair_local: u32,
181
34881
) -> Result<()> {
182
34881
    let &DolistSpec { var_name, body, .. } = spec;
183
34881
    let key = spec.key.as_ref();
184
34881
    let elem_ty = elem.as_wasm_type();
185
34881
    let hint = key.and_then(|key| symbols.hint(key));
186
34881
    let var_ty = home_type(Arm::Value(elem_ty), hint);
187
34881
    let var_local = if needs_cell(symbols, var_name, body)? {
188
3
        ctx.alloc_cell_local(var_ty)?
189
    } else {
190
34878
        ctx.alloc_local(var_ty)?
191
    };
192
34881
    if let Some(key) = key {
193
2326
        symbols.open_binder(key, Arm::Value(elem_ty), None, var_ty);
194
32555
    }
195
    // The loop variable's entry is declared before the body's setf targets
196
    // are promoted, so their type inference sees its home type.
197
34881
    symbols.define_scoped(
198
34881
        Symbol::new(var_name, SymbolKind::Variable)
199
34881
            .with_value(Expr::WasmLocal(var_local, var_ty))
200
34881
            .with_home(key.cloned()),
201
34881
    );
202

            
203
34881
    for (target, rhs) in collect_setf_targets(body) {
204
20756
        if target != var_name {
205
18427
            promote_to_wasm_local(ctx, emit, symbols, &target, rhs.as_ref())?;
206
2329
        }
207
    }
208

            
209
34881
    let pair_idx = ctx.ids.ty_pair;
210

            
211
34881
    emit.block_start();
212
34881
    emit.loop_start();
213

            
214
34881
    emit.local_get(pair_local);
215
34881
    emit.ref_is_null();
216
34881
    emit.br_if(1);
217

            
218
    // Extract the car as anyref, downcast per the element type.
219
34881
    emit.local_get(pair_local);
220
34881
    emit.struct_get(pair_idx, 0);
221
34881
    emit_pair_car_downcast(ctx, emit, elem)?;
222
34673
    box_into_home(ctx, emit, elem_ty, var_ty);
223
34673
    if let Some(cell) = ctx.cell_of(var_local) {
224
3
        emit.struct_new(cell);
225
34670
    }
226
34673
    emit.local_set(var_local);
227

            
228
34673
    symbols.enter_skippable()?;
229
34673
    let compiled = body
230
34673
        .iter()
231
39692
        .try_for_each(|expr| compile_for_effect(ctx, emit, symbols, expr));
232
34673
    symbols.exit_skippable()?;
233
34673
    compiled?;
234

            
235
32564
    emit.local_get(pair_local);
236
32564
    emit.struct_get(pair_idx, 1);
237
32564
    emit.local_set(pair_local);
238

            
239
32564
    emit.br(0);
240
32564
    emit.block_end()?;
241
32564
    emit.block_end()?;
242
32564
    Ok(())
243
34881
}
244

            
245
/// Emits the constant-fold DOLIST loop: unrolls over the known elements,
246
/// binding the loop variable to each and running the body for effect.
247
/// Leaves the loop variable restored and emits no result.
248
17526
fn emit_dolist_const_loop(
249
17526
    ctx: &mut CompileContext,
250
17526
    emit: &mut FunctionEmitter,
251
17526
    symbols: &mut SymbolTable,
252
17526
    var_name: &str,
253
17526
    elements: Vec<Expr>,
254
17526
    body: &[Expr],
255
17526
) -> Result<()> {
256
    // Promote any outer variable the body `setf`s to a runtime value into a
257
    // wasm local before the unroll — without this a `(setf out <runtime>)`
258
    // leaves a bare `WasmRuntime` placeholder with no stack producer. Same
259
    // pre-pass the runtime path runs; the loop var itself is excluded (it's
260
    // rebound to each constant element below).
261
17526
    for (target, rhs) in collect_setf_targets(body) {
262
9023
        if target != var_name {
263
9023
            promote_to_wasm_local(ctx, emit, symbols, &target, rhs.as_ref())?;
264
        }
265
    }
266

            
267
    // P11: the variable is constant data for the iteration (a store to it
268
    // is a structured error), and each iteration and the bytes it emits are
269
    // charged, so a loop that exhausts the budget is a resource error.
270
17526
    symbols.with_scope(|symbols| {
271
69481
        elements.into_iter().try_for_each(|element| {
272
69481
            symbols.define_scoped(
273
69481
                Symbol::new(var_name, SymbolKind::Variable)
274
69481
                    .with_value(member_value(element))
275
69481
                    .loop_constant(),
276
69481
            );
277
69481
            let before = emit.bytes_ref().len();
278
69481
            symbols.charge_work(1)?;
279
69481
            body.iter()
280
73080
                .try_for_each(|expr| compile_for_effect(ctx, emit, symbols, expr))?;
281
67130
            symbols.charge_work(emit.bytes_ref().len().saturating_sub(before) as u64)
282
69481
        })
283
17526
    })
284
17526
}
285

            
286
/// Runs the loop for effect, leaving no result: a constant list is unrolled
287
/// with the variable bound to each element as data (P11), anything else
288
/// walks the runtime `$pair` chain.
289
52408
fn emit_dolist_loop(
290
52408
    ctx: &mut CompileContext,
291
52408
    emit: &mut FunctionEmitter,
292
52408
    symbols: &mut SymbolTable,
293
52408
    spec: &DolistSpec<'_>,
294
52408
) -> Result<()> {
295
    // A body that stores to the loop variable needs it as a runtime local,
296
    // so even a constant list walks the runtime chain (P11's no-store rule).
297
52408
    let stores_to_var = collect_setf_targets(spec.body)
298
52408
        .iter()
299
27868
        .any(|(target, _)| target == spec.var_name);
300
52408
    let constant_list = if stores_to_var {
301
2329
        None
302
    } else {
303
50079
        fold_value(symbols, spec.list_expr)?
304
    };
305
52408
    match constant_list {
306
        Some(list_value) => {
307
17526
            let elements = const_list_elements(&list_value)?;
308
17526
            emit_dolist_const_loop(ctx, emit, symbols, spec.var_name, elements, spec.body)
309
        }
310
34882
        None => emit_dolist_runtime_loop(ctx, emit, symbols, spec),
311
    }
312
52408
}
313

            
314
/// The whole form's constant value when it is fold-safe: such a loop does
315
/// nothing at runtime, so its value is all that is emitted.
316
52842
fn fold_dolist(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Option<Expr>> {
317
52842
    fold_value(symbols, &dolist_form_of(args))
318
52842
}
319

            
320
41248
pub(super) fn compile_dolist_for_effect(
321
41248
    ctx: &mut CompileContext,
322
41248
    emit: &mut FunctionEmitter,
323
41248
    symbols: &mut SymbolTable,
324
41248
    args: &[Expr],
325
41248
) -> Result<()> {
326
41248
    let spec = parse_dolist(symbols, Surface::Codegen, args)?;
327
41248
    if fold_dolist(symbols, args)?.is_some() {
328
223
        return Ok(());
329
41025
    }
330
41025
    emit_dolist_loop(ctx, emit, symbols, &spec)?;
331
36588
    match spec.result_expr {
332
630
        Some(result) => with_exit_binding(symbols, spec.var_name, |symbols| {
333
630
            compile_for_effect(ctx, emit, symbols, result)
334
630
        }),
335
35958
        None => Ok(()),
336
    }
337
41248
}
338

            
339
2744
pub(super) fn compile_dolist(
340
2744
    ctx: &mut CompileContext,
341
2744
    emit: &mut FunctionEmitter,
342
2744
    symbols: &mut SymbolTable,
343
2744
    args: &[Expr],
344
2744
) -> Result<()> {
345
2744
    let spec = parse_dolist(symbols, Surface::Codegen, args)?;
346
2322
    if let Some(value) = fold_dolist(symbols, args)? {
347
210
        return compile_expr(ctx, emit, symbols, &value);
348
2112
    }
349
2112
    emit_dolist_loop(ctx, emit, symbols, &spec)?;
350
1896
    match spec.result_expr {
351
432
        Some(result) => with_exit_binding(symbols, spec.var_name, |symbols| {
352
432
            compile_expr(ctx, emit, symbols, result)
353
432
        }),
354
        None => {
355
1464
            compile_nil(ctx, emit)?;
356
1464
            Ok(())
357
        }
358
    }
359
2744
}
360

            
361
9275
pub(super) fn compile_dolist_for_stack(
362
9275
    ctx: &mut CompileContext,
363
9275
    emit: &mut FunctionEmitter,
364
9275
    symbols: &mut SymbolTable,
365
9275
    args: &[Expr],
366
9275
) -> Result<WasmType> {
367
9275
    let spec = parse_dolist(symbols, Surface::Codegen, args)?;
368
9272
    if let Some(value) = fold_dolist(symbols, args)? {
369
1
        return compile_for_stack(ctx, emit, symbols, &value);
370
9271
    }
371
9271
    emit_dolist_loop(ctx, emit, symbols, &spec)?;
372
9255
    match spec.result_expr {
373
252
        Some(result) => with_exit_binding(symbols, spec.var_name, |symbols| {
374
252
            compile_for_stack(ctx, emit, symbols, result)
375
252
        }),
376
        None => {
377
            // No result form ≡ nil. Push the falsy i31 the stack convention
378
            // uses for nil (typed `Bool` so it serializes as Nil), matching
379
            // `compile_for_stack(Expr::Nil)` and the DO runtime stack path.
380
9003
            emit.i32_const(0);
381
9003
            Ok(WasmType::Bool)
382
        }
383
    }
384
9275
}
385

            
386
/// The placeholder a DOLIST with an unrunnable body answers, typed as the
387
/// value `compile_dolist_for_stack` pushes: the result form's, else nil.
388
1469
fn runtime_dolist_value(spec: &DolistSpec<'_>, symbols: &mut SymbolTable) -> Result<Expr> {
389
1469
    let ty = match spec.result_expr {
390
        Some(result) => {
391
            let value = with_exit_binding(symbols, spec.var_name, |symbols| {
392
                eval_value(symbols, result)
393
            })?;
394
            value
395
                .wasm_type()
396
                .or_else(|| classify_stack_type(&value))
397
                .unwrap_or(WasmType::Bool)
398
        }
399
1469
        None => WasmType::Bool,
400
    };
401
1469
    Ok(Expr::WasmRuntime(ty))
402
1469
}
403

            
404
62423
pub(super) fn dolist_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
405
62423
    let spec = parse_dolist(symbols, Surface::Eval, args)?;
406
61590
    let list_value = eval_value(symbols, spec.list_expr)?;
407

            
408
61590
    if matches!(
409
61590
        list_value.wasm_type(),
410
        Some(WasmType::PairRef(_) | WasmType::AnyRef)
411
    ) {
412
        // Runtime list: the body executes at runtime. Any OUTER variable the
413
        // body `setf`s (an accumulator / counter) is mutated by that runtime
414
        // iteration; mark it runtime so a const-fold of the enclosing form (an
415
        // eval-inlined `(list-length …)` whose tail is the counter, an IF-test
416
        // classification) doesn't read the stale const init and fold the whole
417
        // branch away.
418
43198
        mark_runtime_setf_targets(symbols, spec.body, &[spec.var_name]);
419
        // The dolist's *value* is its result form (or nil), NOT the list —
420
        // mirror what `compile_dolist_for_stack` pushes so this stack-type
421
        // predictor can't drift from codegen.
422
43198
        return dolist_result_value(&spec, symbols);
423
18392
    }
424

            
425
18392
    let elements = const_list_elements(&list_value)?;
426
    // The variable is restored on the error path too, or a fold that fails
427
    // over would leave it (or clobber an outer one) in the live table.
428
18183
    let walked = symbols.with_scope(|symbols| {
429
18183
        elements
430
18183
            .into_iter()
431
263656
            .find_map(|element| {
432
263656
                bind_loop_var(symbols, spec.var_name, element);
433
263656
                match body_yields_runtime(symbols, spec.body) {
434
257560
                    Ok(false) => None,
435
6096
                    outcome => Some(outcome),
436
                }
437
263656
            })
438
18183
            .unwrap_or(Ok(false))
439
18183
    });
440
18183
    if walked? {
441
1469
        return runtime_dolist_value(&spec, symbols);
442
12087
    }
443

            
444
12087
    dolist_result_value(&spec, symbols)
445
62423
}
446

            
447
/// The result form's value, or `nil` without one.
448
55285
fn dolist_result_value(spec: &DolistSpec<'_>, symbols: &mut SymbolTable) -> Result<Expr> {
449
55285
    match spec.result_expr {
450
3836
        Some(result) => with_exit_binding(symbols, spec.var_name, |symbols| {
451
3836
            eval_value(symbols, result)
452
3836
        }),
453
51449
        None => Ok(Expr::Nil),
454
    }
455
55285
}