1
//! `DO` (parallel-step variant) compile + eval handlers.
2
//!
3
//! The three compile entry points (`compile_do`, `_for_effect`,
4
//! `_for_stack`) hand the loop to `unroll::compile_loop`, which unrolls it
5
//! statically when P11 applies and otherwise emits the runtime loop.
6
//! `do_form` is the eval-only handler for value-position use.
7

            
8
use crate::ast::{Expr, PairElement, WasmType};
9
use crate::compiler::binder_key::Surface;
10
use crate::compiler::context::CompileContext;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::compiler::expr::{classify_stack_type, eval_value};
13
use crate::compiler::join::Arm;
14
use crate::error::{Error, Result};
15
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
16

            
17
use super::super::binding::{eval_body, var_home_type};
18
use super::super::literal_arm;
19
use super::common::{
20
    DoVar, MAX_STATIC_LOOP_ITERS, ParsedLoop, body_yields_runtime, infer_result_pair_element,
21
    mark_runtime_setf_targets, parse_loop, static_loop_iterations, steps_are_dead, steps_terminate,
22
};
23
use super::sizing::{infer_wasm_type, var_type_hint};
24
use super::unroll::{Pos, compile_loop, iteration_share, left_to_runtime_loop};
25

            
26
113101
pub(super) fn compile_in(
27
113101
    ctx: &mut CompileContext,
28
113101
    emit: &mut FunctionEmitter,
29
113101
    symbols: &mut SymbolTable,
30
113101
    (head, sequential): (&str, bool),
31
113101
    args: &[Expr],
32
113101
    pos: Pos,
33
113101
) -> Result<Option<WasmType>> {
34
113101
    let parsed = parse_loop(symbols, Surface::Codegen, head, sequential, args)?;
35
112031
    compile_loop(ctx, emit, symbols, &parsed.do_loop(), pos)
36
113101
}
37

            
38
18881
pub(super) fn compile_do(
39
18881
    ctx: &mut CompileContext,
40
18881
    emit: &mut FunctionEmitter,
41
18881
    symbols: &mut SymbolTable,
42
18881
    args: &[Expr],
43
18881
) -> Result<()> {
44
18881
    compile_in(ctx, emit, symbols, ("DO", false), args, Pos::Value).map(|_| ())
45
18881
}
46

            
47
74917
pub(super) fn compile_do_for_stack(
48
74917
    ctx: &mut CompileContext,
49
74917
    emit: &mut FunctionEmitter,
50
74917
    symbols: &mut SymbolTable,
51
74917
    args: &[Expr],
52
74917
) -> Result<WasmType> {
53
74917
    compile_in(ctx, emit, symbols, ("DO", false), args, Pos::Stack)?
54
        .ok_or_else(|| Error::Compile("internal: DO in stack position left no value".to_string()))
55
74917
}
56

            
57
15063
pub(super) fn compile_do_for_effect(
58
15063
    ctx: &mut CompileContext,
59
15063
    emit: &mut FunctionEmitter,
60
15063
    symbols: &mut SymbolTable,
61
15063
    args: &[Expr],
62
15063
) -> Result<()> {
63
15063
    compile_in(ctx, emit, symbols, ("DO", false), args, Pos::Effect).map(|_| ())
64
15063
}
65

            
66
/// The runtime type a DO loop yields, mirroring `compile_do_runtime_for_stack`:
67
/// the last result form's type, `Bool` when there is none. A grown cons
68
/// accumulator is a list typed by its car; any other form takes its own type.
69
89719
pub(super) fn runtime_result_type(
70
89719
    result_forms: &[Expr],
71
89719
    body: &[Expr],
72
89719
    stepped: &[(String, Option<Expr>)],
73
89719
    infer_env: &SymbolTable,
74
89719
) -> WasmType {
75
89719
    let Some(last) = result_forms.last() else {
76
4766
        return WasmType::Bool;
77
    };
78
84953
    if let Some(elem) = infer_result_pair_element(last, body, stepped, infer_env) {
79
70348
        return WasmType::PairRef(elem);
80
14605
    }
81
    // A runtime value reports its own type; a constant goes through the classifier.
82
14605
    let resolved = eval_value(&mut infer_env.clone(), last).unwrap_or(Expr::Nil);
83
14605
    resolved
84
14605
        .wasm_type()
85
39
        .or_else(|| classify_stack_type(&resolved))
86
14605
        .unwrap_or(WasmType::PairRef(PairElement::I32))
87
89719
}
88

            
89
/// Evaluates the body and every step once, as codegen compiles them, so the
90
/// exits a runtime loop holds reach the BLOCKs they leave.
91
89719
fn record_loop_exits(
92
89719
    env: &mut SymbolTable,
93
89719
    init_values: &[(String, Expr, Option<Expr>)],
94
89719
    body: &[Expr],
95
89719
    dead_steps: bool,
96
89719
) -> Result<()> {
97
89719
    eval_body(&mut env.clone(), body)?;
98
89719
    let outer_dead = env.is_dead_code();
99
89719
    env.set_dead_code(outer_dead || dead_steps);
100
136985
    for step in init_values.iter().filter_map(|(_, _, step)| step.as_ref()) {
101
130738
        eval_value(&mut env.clone(), step)?;
102
    }
103
89719
    env.set_dead_code(outer_dead);
104
89719
    Ok(())
105
89719
}
106

            
107
/// The type the eval surface reports for a loop left to codegen. Each variable
108
/// is bound as the runtime type codegen sizes it, so the result form resolves
109
/// as it does there; `Err` when a variable's type is known only to codegen.
110
140272
pub(super) fn eval_result_type(
111
140272
    base: &SymbolTable,
112
140272
    init_values: &[(String, Expr, Option<Expr>)],
113
140272
    keys: &[Option<HomeKey>],
114
140272
    result_forms: &[Expr],
115
140272
    body: &[Expr],
116
140272
    dead_steps: bool,
117
140272
) -> Result<WasmType> {
118
140272
    let mut infer_env = base.clone();
119
140272
    infer_env.set_dead_code(dead_steps);
120
140272
    for ((name, val, step), key) in init_values.iter().zip(keys) {
121
238091
        infer_env.define(Symbol::new(name, SymbolKind::Variable).with_value(val.clone()));
122
238091
        let sized = infer_wasm_type(val, var_type_hint(step.as_ref(), body, name), &infer_env)
123
50553
            .ok_or_else(|| {
124
50553
                Error::Compile(format!("DO: the type of {name} is known only to codegen"))
125
50553
            })?;
126
187538
        let arm = literal_arm(val).unwrap_or(Arm::Value(sized));
127
187538
        let hint = key.as_ref().and_then(|key| base.hint(key));
128
187538
        let ty = var_home_type(arm, hint, || Ok(Some(sized)))?;
129
187538
        infer_env.define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmRuntime(ty)));
130
    }
131
89719
    infer_env.set_dead_code(base.is_dead_code());
132
89719
    record_loop_exits(&mut infer_env, init_values, body, dead_steps)?;
133
89719
    let stepped: Vec<(String, Option<Expr>)> = init_values
134
89719
        .iter()
135
136985
        .map(|(name, _, step)| (name.clone(), step.clone()))
136
        .collect();
137
89719
    Ok(runtime_result_type(
138
89719
        result_forms,
139
89719
        body,
140
89719
        &stepped,
141
89719
        &infer_env,
142
89719
    ))
143
140272
}
144

            
145
236452
pub(super) fn do_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
146
236452
    eval_loop(symbols, ("DO", false), args)
147
236452
}
148

            
149
419475
fn variable(name: &str, value: &Expr) -> Symbol {
150
419475
    Symbol::new(name, SymbolKind::Variable).with_value(value.clone())
151
419475
}
152

            
153
type InitValues = Vec<(String, Expr, Option<Expr>)>;
154

            
155
/// Evaluates the inits: each against the enclosing scope for DO, against the
156
/// variables before it for DO*. Returns the scope the loop runs in.
157
239508
fn eval_inits(
158
239508
    symbols: &mut SymbolTable,
159
239508
    vars: Vec<DoVar>,
160
239508
    sequential: bool,
161
239508
) -> Result<(SymbolTable, InitValues)> {
162
239508
    let mut sequential_scope = sequential.then(|| symbols.clone());
163
239508
    let mut inits = Vec::with_capacity(vars.len());
164
239508
    for v in vars {
165
419475
        let scope = sequential_scope.as_mut().unwrap_or(&mut *symbols);
166
419475
        let val = match v.init {
167
419475
            Some(expr) => eval_value(scope, &expr)?,
168
            None => Expr::Nil,
169
        };
170
419475
        if let Some(local) = sequential_scope.as_mut() {
171
5979
            local.define(variable(&v.name, &val));
172
413496
        }
173
419475
        inits.push((v.name, val, v.step));
174
    }
175
239508
    let local = sequential_scope.unwrap_or_else(|| {
176
236244
        let mut local = symbols.clone();
177
236244
        for (name, val, _) in &inits {
178
413496
            local.define(variable(name, val));
179
        }
180
236244
        local
181
236244
    });
182
239508
    Ok((local, inits))
183
239508
}
184

            
185
18395128
fn set_variable(local: &mut SymbolTable, head: &str, name: &str, value: Expr) -> Result<()> {
186
18395128
    local
187
18395128
        .lookup_mut(name)
188
        .ok_or_else(|| Error::Compile(format!("{head}: variable '{name}' is not bound")))?
189
18395128
        .set_value(value);
190
18395128
    Ok(())
191
18395128
}
192

            
193
10357643
fn step_variables(
194
10357643
    local: &mut SymbolTable,
195
10357643
    (head, sequential): (&str, bool),
196
10357643
    stepped: &[(String, Option<Expr>)],
197
10357643
) -> Result<()> {
198
10357643
    let mut pending = Vec::new();
199
10357643
    for (name, step) in stepped {
200
18404350
        let Some(step) = step else { continue };
201
18395173
        let value = eval_value(local, step)?;
202
18395134
        if sequential {
203
793975
            set_variable(local, head, name, value)?;
204
        } else {
205
17601159
            pending.push((name, value));
206
        }
207
    }
208
10357604
    pending
209
10357604
        .into_iter()
210
17601153
        .try_for_each(|(name, value)| set_variable(local, head, name, value))
211
10357643
}
212

            
213
239924
pub(super) fn eval_loop(
214
239924
    symbols: &mut SymbolTable,
215
239924
    (head, sequential): (&str, bool),
216
239924
    args: &[Expr],
217
239924
) -> Result<Expr> {
218
    let ParsedLoop {
219
        vars,
220
        end_test,
221
        result_forms,
222
        body,
223
        keys,
224
        ..
225
239924
    } = parse_loop(symbols, Surface::Eval, head, sequential, args)?;
226
239508
    let end_test = end_test.clone();
227
239508
    let result_forms: Vec<Expr> = result_forms.to_vec();
228
239508
    let (mut local, init_values) = eval_inits(symbols, vars, sequential)?;
229
417779
    let needs_runtime = init_values.iter().any(|(_, v, _)| v.is_wasm_runtime());
230
239508
    let stepped: Vec<(String, Option<Expr>)> = init_values
231
239508
        .iter()
232
419475
        .map(|(name, _, step)| (name.clone(), step.clone()))
233
        .collect();
234

            
235
239508
    let dead_steps = steps_are_dead(&local, body)?;
236
239508
    let base = symbols.speculative_clone();
237
    let result_ty =
238
140272
        || eval_result_type(&base, &init_values, &keys, &result_forms, body, dead_steps);
239

            
240
239508
    if needs_runtime || eval_value(&mut local, &end_test)?.is_wasm_runtime() {
241
44327
        return Ok(Expr::WasmRuntime(result_ty()?));
242
195181
    }
243

            
244
195181
    if left_to_runtime_loop(symbols, head, args)?
245
99267
        || (!symbols.is_macro_expansion()
246
17023
            && !steps_terminate(&mut local, &end_test, &stepped, sequential, dead_steps))
247
    {
248
95925
        return Ok(Expr::WasmRuntime(result_ty()?));
249
99256
    }
250

            
251
99256
    if symbols.is_macro_expansion() {
252
162986
        let vars: Vec<&str> = stepped.iter().map(|(name, _)| name.as_str()).collect();
253
82244
        mark_runtime_setf_targets(symbols, body, &vars);
254
17012
    }
255

            
256
    // Simulating the steps of a macro's own loop would evaluate their effects.
257
99256
    let iterations = match symbols.is_macro_expansion() {
258
82244
        true => None,
259
17012
        false => static_loop_iterations(
260
17012
            &local,
261
17012
            &end_test,
262
17012
            &stepped,
263
17012
            sequential,
264
17012
            MAX_STATIC_LOOP_ITERS,
265
17012
        ),
266
    };
267
99256
    let share = iteration_share(symbols, iterations.unwrap_or(1));
268
    loop {
269
10456860
        let test = eval_value(&mut local, &end_test)?;
270
10456860
        if !test.is_nil() {
271
98700
            return if result_forms.is_empty() {
272
2551
                Ok(Expr::Nil)
273
            } else {
274
96149
                eval_body(&mut local, &result_forms)
275
            };
276
10358160
        }
277
10358160
        if local.with_unroll_allowance(share, |local| body_yields_runtime(local, body))? {
278
20
            return Ok(Expr::WasmRuntime(result_ty()?));
279
10357643
        }
280
10357643
        step_variables(&mut local, (head, sequential), &stepped)?;
281
    }
282
239924
}