1
//! Shared types and helpers across the DO/DO*/DOLIST family.
2
//!
3
//! Three concerns live here:
4
//! - parsing the form's surface syntax (`parse_do_vars`,
5
//!   `parse_end_clause`, `DoVar`, `DoLoop`);
6
//! - static-time termination + result-type inference
7
//!   (`static_loop_iterations`, `infer_result_pair_element`);
8
//! - the codegen-side setf-target promotion shared by all three
9
//!   constructs (`promote_to_wasm_local`).
10
//!
11
//! Everything is `pub(super)` so the sibling `do_loop` and `dolist`
12
//! modules can use it; nothing escapes to the broader codebase.
13

            
14
use crate::ast::{Expr, PairElement, WasmType};
15
use crate::compiler::binder_key::{SiteKeys, Surface, binder_keys};
16
use crate::compiler::context::CompileContext;
17
use crate::compiler::emit::FunctionEmitter;
18
use crate::compiler::expr::format_form;
19
use crate::compiler::expr::{compile_for_stack, eval_value};
20
use crate::compiler::special::control::form_diverges_scratch;
21
use crate::error::{Error, Result};
22
use crate::reserved::reject_reserved;
23
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
24

            
25
use super::super::binding::reject_duplicate_names;
26

            
27
use super::super::setf_scan::{collect_setf_targets, step_pair_element};
28
use super::runtime::loop_scope;
29
use super::sizing::{infer_compiled_type, infer_wasm_type};
30

            
31
/// Per-binding spec parsed from the variable list of a DO/DO* form.
32
/// `(name init step)` — both `init` and `step` are optional in source
33
/// syntax; the runtime treats absent init as `nil` and absent step as
34
/// "leave the binding alone for this iteration."
35
pub(super) struct DoVar {
36
    pub(super) name: String,
37
    pub(super) init: Option<Expr>,
38
    pub(super) step: Option<Expr>,
39
}
40

            
41
/// Owns the raw shape of a do-loop after the surface form has been
42
/// validated. Reused by both the runtime codegen entry points
43
/// (`compile_do_runtime{,_for_effect,_for_stack}`) and the iterators
44
/// inside each variant.
45
pub(super) struct DoLoop<'a> {
46
    pub(super) vars: &'a [DoVar],
47
    pub(super) end_test: &'a Expr,
48
    pub(super) result_forms: &'a [Expr],
49
    pub(super) body: &'a [Expr],
50
    /// True for DO* (sequential steps), false for DO (parallel).
51
    pub(super) sequential: bool,
52
    /// The binder site of each variable a store can reach.
53
    pub(super) keys: &'a [Option<HomeKey>],
54
}
55

            
56
/// The surface parts of a DO / DO* form.
57
pub(super) struct ParsedLoop<'a> {
58
    pub(super) vars: Vec<DoVar>,
59
    pub(super) end_test: &'a Expr,
60
    pub(super) result_forms: &'a [Expr],
61
    pub(super) body: &'a [Expr],
62
    pub(super) keys: SiteKeys,
63
    sequential: bool,
64
}
65

            
66
impl ParsedLoop<'_> {
67
463570
    pub(super) fn do_loop(&self) -> DoLoop<'_> {
68
463570
        DoLoop {
69
463570
            vars: &self.vars,
70
463570
            end_test: self.end_test,
71
463570
            result_forms: self.result_forms,
72
463570
            body: self.body,
73
463570
            sequential: self.sequential,
74
463570
            keys: &self.keys,
75
463570
        }
76
463570
    }
77
}
78

            
79
/// Parses a DO / DO* form and keys the binder site of each variable.
80
353025
pub(super) fn parse_loop<'a>(
81
353025
    symbols: &SymbolTable,
82
353025
    surface: Surface,
83
353025
    head: &str,
84
353025
    sequential: bool,
85
353025
    args: &'a [Expr],
86
353025
) -> Result<ParsedLoop<'a>> {
87
353025
    let [vars, end_clause, body @ ..] = args else {
88
1456
        return Err(Error::Compile(format!(
89
1456
            "{head} requires a variable list and an end clause"
90
1456
        )));
91
    };
92
351569
    let vars = parse_do_vars(symbols, head, vars)?;
93
351542
    let (end_test, result_forms) = parse_end_clause(head, end_clause)?;
94
351539
    let mut parsed = ParsedLoop {
95
351539
        vars,
96
351539
        end_test,
97
351539
        result_forms,
98
351539
        body,
99
351539
        keys: Vec::new(),
100
351539
        sequential,
101
351539
    };
102
351539
    let dl = parsed.do_loop();
103
351539
    let keys = binder_keys(
104
351539
        symbols,
105
351539
        surface,
106
351539
        (head, args),
107
351539
        dl.vars
108
351539
            .iter()
109
351539
            .enumerate()
110
583963
            .map(|(at, var)| (var.name.as_str(), var.step.is_some(), loop_scope(&dl, at))),
111
    );
112
351539
    parsed.keys = keys;
113
351539
    Ok(parsed)
114
353025
}
115

            
116
pub(super) const MAX_STATIC_LOOP_ITERS: usize = 64;
117

            
118
529917
pub(super) fn parse_do_vars(
119
529917
    symbols: &SymbolTable,
120
529917
    context: &str,
121
529917
    expr: &Expr,
122
529917
) -> Result<Vec<DoVar>> {
123
529917
    let list = expr.as_list().ok_or_else(|| {
124
3
        Error::Compile(format!(
125
3
            "{context}: expected variable list, got {}",
126
3
            format_form(expr)
127
3
        ))
128
3
    })?;
129
529914
    let vars: Vec<DoVar> = list
130
529914
        .iter()
131
859632
        .map(|spec| match spec {
132
            Expr::Symbol(name) => reject_reserved(symbols, name).map(|()| DoVar {
133
                name: name.clone(),
134
                init: None,
135
                step: None,
136
            }),
137
859629
            Expr::List(elems) if !elems.is_empty() && elems.len() <= 3 => {
138
859629
                let name = elems[0].as_symbol().ok_or_else(|| {
139
15
                    Error::Compile(format!(
140
15
                        "{context}: variable name must be a symbol, got {}",
141
15
                        format_form(&elems[0])
142
15
                    ))
143
15
                })?;
144
859614
                reject_reserved(symbols, name)?;
145
859608
                Ok(DoVar {
146
859608
                    name: name.to_string(),
147
859608
                    init: elems.get(1).cloned(),
148
859608
                    step: elems.get(2).cloned(),
149
859608
                })
150
            }
151
3
            _ => Err(Error::Compile(format!(
152
3
                "{context}: malformed variable spec: {}",
153
3
                format_form(spec)
154
3
            ))),
155
859632
        })
156
24
        .collect::<Result<_>>()?;
157
859608
    reject_duplicate_names("variable", context, vars.iter().map(|var| &var.name))?;
158
529890
    Ok(vars)
159
529917
}
160

            
161
529890
pub(super) fn parse_end_clause<'a>(
162
529890
    context: &str,
163
529890
    expr: &'a Expr,
164
529890
) -> Result<(&'a Expr, &'a [Expr])> {
165
529890
    let elems = expr.as_list().ok_or_else(|| {
166
3
        Error::Compile(format!(
167
3
            "{context}: end clause must be a list, got {}",
168
3
            format_form(expr)
169
3
        ))
170
3
    })?;
171
529887
    if elems.is_empty() {
172
        return Err(Error::Compile(format!(
173
            "{context}: end clause must have a test form"
174
        )));
175
529887
    }
176
529887
    Ok((&elems[0], &elems[1..]))
177
529890
}
178

            
179
/// Whether a loop's steps are dead for the eval surface's BLOCK join: its
180
/// `body` always diverges, so codegen never reaches them. Classified only
181
/// while a BLOCK is open outside a macro body, which has no codegen to agree
182
/// with.
183
239508
pub(super) fn steps_are_dead(symbols: &SymbolTable, body: &[Expr]) -> Result<bool> {
184
239508
    if symbols.is_dead_code() {
185
        return Ok(true);
186
239508
    }
187
239508
    if !symbols.has_eval_block() || symbols.is_macro_expansion() {
188
226963
        return Ok(false);
189
12545
    }
190
12545
    for form in body {
191
6585
        if form_diverges_scratch(symbols, form)? {
192
89
            return Ok(true);
193
6496
        }
194
    }
195
12456
    Ok(false)
196
239508
}
197

            
198
/// Looks for an accumulator `(cons V <result-name>)` that determines
199
/// the runtime `PairElement` of the do's result. Two patterns: body
200
/// `(setf acc (cons V acc))` and step `(acc nil (cons V acc))` (or
201
/// nested via if/cond). Without inspecting the step path, a do whose
202
/// accumulator lives in its var-step gets the placeholder I32, and
203
/// consumer dolists downcast to i31 — runtime cast trap.
204
84953
pub(super) fn infer_result_pair_element(
205
84953
    result_form: &Expr,
206
84953
    body: &[Expr],
207
84953
    stepped: &[(String, Option<Expr>)],
208
84953
    symbols: &SymbolTable,
209
84953
) -> Option<PairElement> {
210
84953
    let Expr::Symbol(target) = result_form else {
211
3053
        return None;
212
    };
213
81900
    let from_body = collect_setf_targets(body)
214
81900
        .into_iter()
215
40438
        .find_map(|(name, rhs)| {
216
40438
            (name == *target)
217
40438
                .then_some(rhs)
218
40438
                .flatten()
219
40438
                .as_ref()
220
40438
                .and_then(|r| step_pair_element(r, symbols))
221
40438
        });
222
81900
    if from_body.is_some() {
223
31230
        return from_body;
224
50670
    }
225
93379
    stepped.iter().find_map(|(name, step)| {
226
93379
        if name != target {
227
50220
            return None;
228
43159
        }
229
43159
        step.as_ref().and_then(|s| step_pair_element(s, symbols))
230
93379
    })
231
84953
}
232

            
233
/// Eval-path mirror of [`promote_to_wasm_local`]: when a *runtime* loop body
234
/// `setf`s an OUTER variable, the loop's runtime iteration mutates it, but the
235
/// eval (const-fold) surface never runs that body, so the variable keeps its
236
/// stale const init. Mark each such target as a `WasmRuntime` placeholder of
237
/// its codegen-inferred type so the enclosing eval (an IF-test classification,
238
/// a defun's tail value) sees it as runtime — exactly what codegen's
239
/// accumulator promotion does. Idempotent: re-marking an already-runtime
240
/// target is a no-op, keeping the two-surface re-eval design sound.
241
125442
pub(in crate::compiler::special) fn mark_runtime_setf_targets(
242
125442
    symbols: &mut SymbolTable,
243
125442
    body: &[Expr],
244
125442
    exclude: &[&str],
245
125442
) {
246
125442
    for (name, rhs) in collect_setf_targets(body) {
247
33815
        if exclude.contains(&name.as_str()) {
248
            continue;
249
33815
        }
250
        // Only re-type a var that is ALREADY bound in this scope — never
251
        // synthesize a missing one. A `setf` to an undefined / nested-bound
252
        // name is codegen's concern (`promote_to_wasm_local` errors on it); the
253
        // eval mirror must not mask that by defining a spurious outer symbol.
254
33815
        let Some(current) = symbols.lookup(&name).and_then(|s| s.value().cloned()) else {
255
            continue;
256
        };
257
33815
        if current.is_wasm_runtime() {
258
33391
            continue;
259
424
        }
260
424
        let ty = infer_wasm_type(&current, rhs.as_ref(), symbols).unwrap_or(WasmType::AnyRef);
261
424
        symbols.define(Symbol::new(&name, SymbolKind::Variable).with_value(Expr::WasmRuntime(ty)));
262
    }
263
125442
}
264

            
265
/// Runs a statically-unrolled loop body; true when, in a macro body, a form
266
/// answered a runtime placeholder (an effect or transfer the evaluator cannot run).
267
10621818
pub(super) fn body_yields_runtime(symbols: &mut SymbolTable, body: &[Expr]) -> Result<bool> {
268
10621818
    let in_macro = symbols.is_macro_expansion();
269
10621818
    for expr in body {
270
1021293
        if eval_value(symbols, expr)?.is_wasm_runtime() && in_macro {
271
1490
            return Ok(true);
272
1014679
        }
273
    }
274
10615204
    Ok(false)
275
10621818
}
276

            
277
61768
pub(in crate::compiler::special) fn promote_to_wasm_local(
278
61768
    ctx: &mut CompileContext,
279
61768
    emit: &mut FunctionEmitter,
280
61768
    symbols: &mut SymbolTable,
281
61768
    name: &str,
282
61768
    step_hint: Option<&Expr>,
283
61768
) -> Result<()> {
284
    // A store target nothing defines yet is a definition (DEFPARAMETER) or a
285
    // new global: its own form reports it when the body compiles.
286
61768
    let Some(sym) = symbols.lookup(name) else {
287
6
        return Ok(());
288
    };
289
61762
    if sym.value().is_some_and(Expr::is_wasm_runtime) {
290
61762
        return Ok(());
291
    }
292
    let val = sym.value().cloned().unwrap_or(Expr::Nil);
293
    let ty = infer_compiled_type(ctx, emit, symbols, &val, step_hint)?;
294
    let idx = ctx.alloc_local(ty)?;
295
    if matches!(ty, WasmType::PairRef(_)) && matches!(val, Expr::Nil) {
296
        emit.ref_null(ctx.ids.ty_pair);
297
    } else {
298
        compile_for_stack(ctx, emit, symbols, &val)?;
299
    }
300
    emit.local_set(idx);
301
    symbols.define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmLocal(idx, ty)));
302
    Ok(())
303
61768
}
304

            
305
/// A step result the unroller can apply: a compile-time constant. A runtime
306
/// value (a store into runtime storage, a host call) needs the runtime loop.
307
2654437
fn static_value(value: Result<Expr>) -> Option<Expr> {
308
2654437
    value.ok().filter(|value| !value.is_wasm_runtime())
309
2654437
}
310

            
311
/// [`static_loop_iterations`] with the simulated steps dead when
312
/// `dead_steps` (see [`steps_are_dead`]).
313
17023
pub(super) fn steps_terminate(
314
17023
    local: &mut SymbolTable,
315
17023
    end_test: &Expr,
316
17023
    stepped: &[(String, Option<Expr>)],
317
17023
    sequential: bool,
318
17023
    dead_steps: bool,
319
17023
) -> bool {
320
17023
    let dead = local.is_dead_code();
321
17023
    local.set_dead_code(dead_steps);
322
    let terminates =
323
17023
        static_loop_iterations(local, end_test, stepped, sequential, MAX_STATIC_LOOP_ITERS)
324
17023
            .is_some();
325
17023
    local.set_dead_code(dead);
326
17023
    terminates
327
17023
}
328

            
329
/// The iterations a constant loop runs before its end test holds, `None` when
330
/// it does not end within `max_iterations` or leaves the constants.
331
87404
pub(super) fn static_loop_iterations(
332
87404
    local: &SymbolTable,
333
87404
    end_test: &Expr,
334
87404
    stepped: &[(String, Option<Expr>)],
335
87404
    sequential: bool,
336
87404
    max_iterations: usize,
337
87404
) -> Option<usize> {
338
87404
    let mut sim = local.clone();
339
87404
    for iteration in 0..max_iterations {
340
2585477
        match eval_value(&mut sim, end_test) {
341
2585477
            Ok(test) if test.is_wasm_runtime() => return None,
342
2585477
            Ok(test) if !test.is_nil() => return Some(iteration),
343
2523312
            Ok(_) => {}
344
            Err(_) => return None,
345
        }
346
2523312
        if sequential {
347
34338
            for (name, step) in stepped {
348
64242
                let Some(s) = step else { continue };
349
64242
                let val = static_value(eval_value(&mut sim, s))?;
350
64242
                if let Some(sym) = sim.lookup_mut(name) {
351
64242
                    sym.set_value(val);
352
                }
353
            }
354
        } else {
355
2488974
            let new_vals = stepped
356
2488974
                .iter()
357
3085349
                .filter_map(|(name, step)| {
358
3085349
                    step.as_ref()
359
2590195
                        .map(|s| static_value(eval_value(&mut sim, s)).map(|v| (name.clone(), v)))
360
3085349
                })
361
                .collect::<Option<Vec<_>>>();
362
2488974
            let new_vals = new_vals?;
363
2488762
            for (name, val) in new_vals {
364
2589771
                if let Some(sym) = sim.lookup_mut(&name) {
365
2589771
                    sym.set_value(val);
366
                }
367
            }
368
        }
369
    }
370
25027
    None
371
87404
}