1
//! Codegen for the runtime path of `DO` / `DO*`.
2
//!
3
//! `compile_do_runtime_loop` emits the actual wasm `block / loop / br_if`
4
//! prelude + body + step sequence; the three wrapper functions
5
//! (`compile_do_runtime` / `_for_effect` / `_for_stack`) differ only
6
//! in how they consume the result-forms after the loop exits — value
7
//! position, effect-only, or push-to-stack respectively.
8
//!
9
//! Both `DO` and `DO*` parallel/sequential semantics are encoded as
10
//! `DoLoop.sequential`. The step assignment block here is the only
11
//! place that distinction surfaces in the runtime codegen.
12

            
13
use crate::ast::{Expr, WasmType};
14
use crate::compiler::context::CompileContext;
15
use crate::compiler::emit::FunctionEmitter;
16
use crate::compiler::expr::{
17
    compile_body, compile_for_effect, compile_for_stack, compile_nil, probe_value, store_begin,
18
    store_end,
19
};
20
use crate::error::Result;
21
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
22

            
23
use super::super::binding::bind_var_home;
24
use super::super::binding::shared::needs_cell_stepped;
25
use super::super::compile_store_value;
26
use super::super::setf_scan::collect_setf_targets;
27
use super::common::{DoLoop, promote_to_wasm_local};
28
use super::sizing::{infer_compiled_type, var_type_hint};
29

            
30
/// What variable `at` of a DO sees: every step, the end test, the result forms
31
/// and the body, and for DO* the initializers of the variables after it.
32
801137
pub(super) fn loop_scope<'a>(dl: &DoLoop<'a>, at: usize) -> Vec<&'a Expr> {
33
801137
    let vars = dl.vars;
34
801137
    let later_inits = vars[at + 1..]
35
801137
        .iter()
36
296361
        .filter(|_| dl.sequential)
37
10503
        .filter_map(|v| v.init.as_ref());
38
801137
    later_inits
39
1393855
        .chain(vars.iter().filter_map(|v| v.step.as_ref()))
40
801137
        .chain(std::iter::once(dl.end_test))
41
801137
        .chain(dl.result_forms)
42
801137
        .chain(dl.body)
43
        .collect()
44
801137
}
45

            
46
/// Computes every step before any variable changes; a celled variable's value
47
/// waits in a temp because its cell ref must sit below it for the store.
48
97519
fn compile_parallel_steps(
49
97519
    ctx: &mut CompileContext,
50
97519
    emit: &mut FunctionEmitter,
51
97519
    local: &mut SymbolTable,
52
97519
    wasm_vars: &[(Expr, u32, WasmType, Option<Expr>)],
53
97519
) -> Result<()> {
54
97519
    let mut plain = Vec::new();
55
97519
    let mut celled = Vec::new();
56
97519
    for (place, idx, ty, step) in wasm_vars {
57
143501
        let Some(step_expr) = step else { continue };
58
140034
        compile_store_value(ctx, emit, local, place, step_expr, *ty)?;
59
139195
        if ctx.cell_of(*idx).is_some() {
60
12
            let temp = ctx.alloc_local(*ty)?;
61
12
            emit.local_set(temp);
62
12
            celled.push((*idx, temp));
63
        } else {
64
139183
            plain.push(*idx);
65
        }
66
    }
67
96680
    for idx in plain.into_iter().rev() {
68
138552
        emit.local_set(idx);
69
    }
70
96680
    for (idx, temp) in celled {
71
12
        store_begin(ctx, emit, idx);
72
12
        emit.local_get(temp);
73
12
        store_end(ctx, emit, idx, false);
74
    }
75
96680
    Ok(())
76
97519
}
77

            
78
/// Allocates the local of variable `at`, typed by its home: the join of its
79
/// init and the hint the refused stores of the previous attempt left.
80
151151
fn bind_do_var(
81
151151
    ctx: &mut CompileContext,
82
151151
    emit: &mut FunctionEmitter,
83
151151
    (local, peek): (&mut SymbolTable, &mut SymbolTable),
84
151151
    dl: &DoLoop<'_>,
85
151151
    at: usize,
86
151151
) -> Result<(Symbol, u32, WasmType)> {
87
151151
    let v = &dl.vars[at];
88
151151
    let shared = needs_cell_stepped(local, &v.name, v.step.is_some(), loop_scope(dl, at))?;
89
151151
    let init_expr = v.init.clone().unwrap_or(Expr::Nil);
90
    // Probe on a CLONE: the value only sizes the local and detects a nil init;
91
    // the live emission below is the single application of any seed side effects.
92
151151
    let init_val = probe_value(&mut local.clone(), &init_expr)?;
93
151151
    let key = dl.keys.get(at).and_then(Option::as_ref);
94
151151
    let (idx, ty) = bind_var_home(
95
151151
        ctx,
96
151151
        emit,
97
151151
        local,
98
151151
        key,
99
151151
        (Some(&init_expr), &init_val),
100
151151
        shared,
101
41693
        |ctx, emit, _| {
102
41693
            let step_hint = var_type_hint(v.step.as_ref(), dl.body, &v.name);
103
41693
            peek.define(Symbol::new(&v.name, SymbolKind::Variable).with_value(Expr::Nil));
104
41693
            infer_compiled_type(ctx, emit, peek, &init_val, step_hint).map(Some)
105
41693
        },
106
22
    )?;
107
151129
    let var = Symbol::new(&v.name, SymbolKind::Variable)
108
151129
        .with_value(Expr::WasmLocal(idx, ty))
109
151129
        .with_home(key.cloned());
110
151129
    Ok((var, idx, ty))
111
151151
}
112

            
113
101354
fn compile_do_runtime_loop(
114
101354
    ctx: &mut CompileContext,
115
101354
    emit: &mut FunctionEmitter,
116
101354
    local: &mut SymbolTable,
117
101354
    dl: &DoLoop<'_>,
118
101354
) -> Result<()> {
119
    // The DO-vars are declared before the setf targets are promoted, so a
120
    // CONS step can resolve them.
121
101354
    let mut wasm_vars: Vec<(Expr, u32, WasmType, Option<Expr>)> = Vec::new();
122
    // A parallel DO's inits all see the outer scope; `peek` still lets a step
123
    // that mentions an earlier variable type its accumulator.
124
101354
    let mut peek = local.clone();
125
101354
    let mut declared = Vec::new();
126
101354
    for (at, v) in dl.vars.iter().enumerate() {
127
151151
        let (var, idx, ty) = bind_do_var(ctx, emit, (local, &mut peek), dl, at)?;
128
151129
        peek.define(var.clone());
129
151129
        if dl.sequential {
130
6104
            local.define(var);
131
        } else {
132
145025
            declared.push(var);
133
        }
134
151129
        wasm_vars.push((Expr::Symbol(v.name.clone()), idx, ty, v.step.clone()));
135
    }
136
101332
    for var in declared {
137
145007
        local.define(var);
138
    }
139

            
140
151111
    let do_var_names: Vec<_> = dl.vars.iter().map(|v| v.name.clone()).collect();
141
101332
    for (target, rhs) in collect_setf_targets(dl.body) {
142
32890
        if !do_var_names.contains(&target) {
143
30936
            promote_to_wasm_local(ctx, emit, local, &target, rhs.as_ref())?;
144
1954
        }
145
    }
146

            
147
    // block $exit
148
101332
    emit.block_start();
149
    // loop $continue
150
101332
    emit.loop_start();
151

            
152
101332
    if compile_for_stack(ctx, emit, local, dl.end_test)? == crate::ast::WasmType::I32 {
153
        // An index end-test is a count, never nil: the loop ends at once.
154
211
        emit.drop_value();
155
211
        emit.i32_const(1);
156
101120
    }
157
101331
    emit.br_if(1);
158

            
159
101331
    local.enter_skippable()?;
160
101331
    let compiled = dl
161
101331
        .body
162
101331
        .iter()
163
39041
        .try_for_each(|expr| compile_for_effect(ctx, emit, local, expr));
164
101331
    local.exit_skippable()?;
165
101331
    compiled?;
166

            
167
100680
    if dl.sequential {
168
3161
        for (place, idx, ty, step) in &wasm_vars {
169
6104
            if let Some(step_expr) = step {
170
5874
                store_begin(ctx, emit, *idx);
171
5874
                compile_store_value(ctx, emit, local, place, step_expr, *ty)?;
172
5662
                store_end(ctx, emit, *idx, false);
173
230
            }
174
        }
175
    } else {
176
97519
        compile_parallel_steps(ctx, emit, local, &wasm_vars)?;
177
    }
178

            
179
99629
    emit.br(0);
180
99629
    emit.block_end()?; // end loop
181
99629
    emit.block_end()?; // end block
182

            
183
99629
    Ok(())
184
101354
}
185

            
186
16573
pub(super) fn compile_do_runtime(
187
16573
    ctx: &mut CompileContext,
188
16573
    emit: &mut FunctionEmitter,
189
16573
    symbols: &mut SymbolTable,
190
16573
    dl: &DoLoop<'_>,
191
16573
) -> Result<()> {
192
16573
    let mut local = symbols.clone();
193
16573
    compile_do_runtime_loop(ctx, emit, &mut local, dl)?;
194
15085
    if dl.result_forms.is_empty() {
195
1875
        compile_nil(ctx, emit)?;
196
    } else {
197
13210
        compile_body(ctx, emit, &mut local, dl.result_forms)?;
198
    }
199
15085
    Ok(())
200
16573
}
201

            
202
11047
pub(super) fn compile_do_runtime_for_effect(
203
11047
    ctx: &mut CompileContext,
204
11047
    emit: &mut FunctionEmitter,
205
11047
    symbols: &mut SymbolTable,
206
11047
    dl: &DoLoop<'_>,
207
11047
) -> Result<()> {
208
11047
    let mut local = symbols.clone();
209
11047
    compile_do_runtime_loop(ctx, emit, &mut local, dl)?;
210
11047
    for expr in dl.result_forms {
211
8531
        compile_for_effect(ctx, emit, &mut local, expr)?;
212
    }
213
11047
    Ok(())
214
11047
}
215

            
216
73734
pub(super) fn compile_do_runtime_for_stack(
217
73734
    ctx: &mut CompileContext,
218
73734
    emit: &mut FunctionEmitter,
219
73734
    symbols: &mut SymbolTable,
220
73734
    dl: &DoLoop<'_>,
221
73734
) -> Result<WasmType> {
222
73734
    let mut local = symbols.clone();
223
73734
    compile_do_runtime_loop(ctx, emit, &mut local, dl)?;
224
73497
    let Some((last, effects)) = dl.result_forms.split_last() else {
225
        // No result forms ≡ nil — falsy i31, typed `Bool` so it serializes as
226
        // Nil and agrees with the eval mirror's `Expr::Nil`.
227
1941
        emit.i32_const(0);
228
1941
        return Ok(WasmType::Bool);
229
    };
230
71556
    for expr in effects {
231
3
        compile_for_effect(ctx, emit, &mut local, expr)?;
232
    }
233
71556
    compile_for_stack(ctx, emit, &mut local, last)
234
73734
}