1
//! `LET` / `LET*` codegen (effect, stack, value-position variants).
2
//!
3
//! Six entry points share the same shape: parse the bindings list,
4
//! resolve each init (parallel for LET, sequential for LET*), bind via
5
//! `bind_variable` to either a constant or a freshly-allocated
6
//! wasm local inside a symbol-table scope frame, then compile the body.
7
//! The frame shadows without copying the table, so a definition the body
8
//! makes outlives it (0014 Stage 2, ISS-039). The only difference between
9
//! the entry points is what the body-compile target is.
10

            
11
use crate::ast::{Expr, WasmType};
12
use crate::compiler::binder_key::Surface;
13
use crate::compiler::context::CompileContext;
14
use crate::compiler::emit::FunctionEmitter;
15
use crate::compiler::expr::{
16
    compile_body, compile_body_for_stack, compile_diverging_to_end, compile_for_effect,
17
    probe_value, serialize_stack_to_output,
18
};
19
use crate::compiler::join::NEVER_RETURNS;
20
use crate::error::Result;
21
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
22

            
23
use super::super::control::protect;
24
use super::super::{compile_store_value, form_diverges_scratch};
25
use super::dynamic::{
26
    DynamicHome, bind, dynamic_home, reject_missed_specials, restore_forms, save_all,
27
};
28
use super::infer::sibling_scope;
29
use super::let_bind::{Bind, bind_variable, resolve_binding};
30
use super::parse::{reject_duplicate_names, split_let};
31
use super::shared::needs_cell;
32
use super::shared::star_scope;
33

            
34
/// What the body compiles to.
35
#[derive(Clone, Copy)]
36
enum Target {
37
    Value,
38
    Stack,
39
    Effect,
40
}
41

            
42
253632
pub(super) fn compile_let(
43
253632
    ctx: &mut CompileContext,
44
253632
    emit: &mut FunctionEmitter,
45
253632
    symbols: &mut SymbolTable,
46
253632
    args: &[Expr],
47
253632
) -> Result<()> {
48
253632
    in_live_frame(ctx, emit, symbols, args, Target::Value, compile_parallel).map(|_| ())
49
253632
}
50

            
51
487201
pub(super) fn compile_let_for_stack(
52
487201
    ctx: &mut CompileContext,
53
487201
    emit: &mut FunctionEmitter,
54
487201
    symbols: &mut SymbolTable,
55
487201
    args: &[Expr],
56
487201
) -> Result<WasmType> {
57
487201
    in_live_frame(ctx, emit, symbols, args, Target::Stack, compile_parallel)
58
487201
}
59

            
60
16149
pub(super) fn compile_let_for_effect(
61
16149
    ctx: &mut CompileContext,
62
16149
    emit: &mut FunctionEmitter,
63
16149
    symbols: &mut SymbolTable,
64
16149
    args: &[Expr],
65
16149
) -> Result<()> {
66
16149
    in_live_frame(ctx, emit, symbols, args, Target::Effect, compile_parallel).map(|_| ())
67
16149
}
68

            
69
52643
pub(super) fn compile_let_star(
70
52643
    ctx: &mut CompileContext,
71
52643
    emit: &mut FunctionEmitter,
72
52643
    symbols: &mut SymbolTable,
73
52643
    args: &[Expr],
74
52643
) -> Result<()> {
75
52643
    in_live_frame(ctx, emit, symbols, args, Target::Value, compile_sequential).map(|_| ())
76
52643
}
77

            
78
11997
pub(super) fn compile_let_star_for_stack(
79
11997
    ctx: &mut CompileContext,
80
11997
    emit: &mut FunctionEmitter,
81
11997
    symbols: &mut SymbolTable,
82
11997
    args: &[Expr],
83
11997
) -> Result<WasmType> {
84
11997
    in_live_frame(ctx, emit, symbols, args, Target::Stack, compile_sequential)
85
11997
}
86

            
87
9380
pub(super) fn compile_let_star_for_effect(
88
9380
    ctx: &mut CompileContext,
89
9380
    emit: &mut FunctionEmitter,
90
9380
    symbols: &mut SymbolTable,
91
9380
    args: &[Expr],
92
9380
) -> Result<()> {
93
9380
    in_live_frame(ctx, emit, symbols, args, Target::Effect, compile_sequential).map(|_| ())
94
9380
}
95

            
96
/// LET: every init resolves and binds against the enclosing scope before
97
/// anything is saved; a dynamic special's init is staged in a local. The
98
/// save, the store of the staged values and the body are the protected region.
99
756982
fn compile_parallel(
100
756982
    ctx: &mut CompileContext,
101
756982
    emit: &mut FunctionEmitter,
102
756982
    symbols: &mut SymbolTable,
103
756982
    args: &[Expr],
104
756982
    target: Target,
105
756982
) -> Result<WasmType> {
106
756982
    let (bindings, keys, body) = split_let(symbols, Surface::Codegen, "LET", false, args)?;
107
756126
    reject_duplicate_names("variable", "LET", bindings.iter().map(|(name, _)| name))?;
108
772555
    reject_missed_specials(symbols, bindings.iter().map(|(name, _)| name.as_str()))?;
109
756123
    let mut bound = Vec::with_capacity(bindings.len());
110
756123
    let mut staged = Vec::new();
111
756123
    let mut homes = Vec::new();
112
756123
    let probed = bindings.iter().map(|(_, init)| match init {
113
        Some(init) => {
114
17312
            probe_value(&mut symbols.clone(), init).unwrap_or(Expr::WasmRuntime(WasmType::AnyRef))
115
        }
116
208
        None => Expr::Nil,
117
17520
    });
118
756123
    let sizing = sibling_scope(symbols, &bindings, probed);
119
756123
    for ((name, init), key) in bindings.iter().zip(&keys) {
120
772555
        if init_raises(ctx, emit, symbols, init.as_ref())? {
121
222
            return Ok(NEVER_RETURNS);
122
772333
        }
123
772333
        if let Some(home) = dynamic_home(symbols, name) {
124
22150
            compile_store_value(
125
22150
                ctx,
126
22150
                emit,
127
22150
                symbols,
128
22150
                &Expr::Symbol(name.clone()),
129
22150
                init.as_ref().unwrap_or(&Expr::Nil),
130
22150
                home.ty,
131
22150
            )?;
132
19848
            if !emit.is_reachable() {
133
                return Ok(NEVER_RETURNS);
134
19848
            }
135
19848
            let tmp = ctx.alloc_local(home.ty)?;
136
19848
            emit.local_set(tmp);
137
19848
            staged.push((home, tmp));
138
19848
            homes.push(home);
139
19848
            continue;
140
750183
        }
141
750183
        let (init_expr, init) = resolve_binding(symbols, init.clone())?;
142
747887
        let shared = needs_cell(symbols, name, body)?;
143
747887
        let value = bind_variable(
144
747887
            ctx,
145
747887
            emit,
146
747887
            symbols,
147
747887
            &Bind {
148
747887
                name,
149
747887
                body,
150
747887
                shared,
151
747887
                sizing: sizing.as_ref(),
152
747887
                key: key.as_ref(),
153
747887
            },
154
747887
            init_expr.as_ref(),
155
747887
            &init,
156
747887
        )?;
157
695429
        if !emit.is_reachable() {
158
15
            return Ok(NEVER_RETURNS);
159
695414
        }
160
695414
        bound.push((name, value));
161
    }
162
698830
    with_dynamic(
163
698830
        ctx,
164
698830
        emit,
165
698830
        symbols,
166
698830
        ("LET", args),
167
698830
        &homes,
168
698830
        target,
169
698830
        |ctx, emit, symbols, target| {
170
698830
            for (home, tmp) in staged {
171
19848
                emit.local_get(tmp);
172
19848
                bind(emit, home);
173
            }
174
698830
            symbols.push_scope();
175
698830
            for (name, (value, home)) in bound {
176
695414
                record_closure_result(symbols, ctx, &value)?;
177
695414
                symbols.define_scoped(
178
695414
                    Symbol::new(name, SymbolKind::Variable)
179
695414
                        .with_value(value)
180
695414
                        .with_home(home),
181
695414
                );
182
            }
183
698830
            let compiled = compile_target(ctx, emit, symbols, body, target);
184
698830
            symbols.pop_scope()?;
185
698830
            compiled
186
698830
        },
187
    )
188
756982
}
189

            
190
/// LET*: only reached when no spec binds a dynamic special (`rebind` nests
191
/// those); the frame opens first and each init sees the bindings before it.
192
74020
fn compile_sequential(
193
74020
    ctx: &mut CompileContext,
194
74020
    emit: &mut FunctionEmitter,
195
74020
    symbols: &mut SymbolTable,
196
74020
    args: &[Expr],
197
74020
    target: Target,
198
74020
) -> Result<WasmType> {
199
74020
    let (bindings, keys, body) = split_let(symbols, Surface::Codegen, "LET*", true, args)?;
200
73598
    symbols.push_scope();
201
    let compiled =
202
73598
        bind_sequentially(ctx, emit, symbols, &bindings, &keys, body).and_then(|live| match live {
203
73590
            true => compile_target(ctx, emit, symbols, body, target),
204
6
            false => Ok(NEVER_RETURNS),
205
73596
        });
206
73598
    symbols.pop_scope()?;
207
73598
    compiled
208
74020
}
209

            
210
/// Binds the LET* variables in order; `false` once an init diverges.
211
73598
fn bind_sequentially(
212
73598
    ctx: &mut CompileContext,
213
73598
    emit: &mut FunctionEmitter,
214
73598
    symbols: &mut SymbolTable,
215
73598
    bindings: &[(String, Option<Expr>)],
216
73598
    keys: &[Option<HomeKey>],
217
73598
    body: &[Expr],
218
73598
) -> Result<bool> {
219
73598
    for (at, ((name, init), key)) in bindings.iter().zip(keys).enumerate() {
220
156113
        if init_raises(ctx, emit, symbols, init.as_ref())? {
221
3
            return Ok(false);
222
156110
        }
223
156110
        let (init_expr, init) = resolve_binding(symbols, init.clone())?;
224
156110
        let scope: Vec<Expr> = star_scope(bindings, at, body, true)
225
156110
            .into_iter()
226
156110
            .cloned()
227
156110
            .collect();
228
156110
        let shared = needs_cell(symbols, name, &scope)?;
229
156110
        let value = bind_variable(
230
156110
            ctx,
231
156110
            emit,
232
156110
            symbols,
233
156110
            &Bind {
234
156110
                name,
235
156110
                body: &scope,
236
156110
                shared,
237
156110
                sizing: None,
238
156110
                key: key.as_ref(),
239
156110
            },
240
156110
            init_expr.as_ref(),
241
156110
            &init,
242
156110
        )?;
243
156108
        if !emit.is_reachable() {
244
3
            return Ok(false);
245
156105
        }
246
156105
        record_closure_result(symbols, ctx, &value.0)?;
247
156105
        symbols.define_scoped(
248
156105
            Symbol::new(name, SymbolKind::Variable)
249
156105
                .with_value(value.0)
250
156105
                .with_home(value.1),
251
156105
        );
252
    }
253
73590
    Ok(true)
254
73598
}
255

            
256
928668
fn init_raises(
257
928668
    ctx: &mut CompileContext,
258
928668
    emit: &mut FunctionEmitter,
259
928668
    symbols: &mut SymbolTable,
260
928668
    init: Option<&Expr>,
261
928668
) -> Result<bool> {
262
928668
    let Some(init) = init else {
263
208
        return Ok(false);
264
    };
265
928460
    compile_diverging_to_end(ctx, emit, symbols, init, form_diverges_scratch)
266
928668
}
267

            
268
type LetCompile = fn(
269
    &mut CompileContext,
270
    &mut FunctionEmitter,
271
    &mut SymbolTable,
272
    &[Expr],
273
    Target,
274
) -> Result<WasmType>;
275

            
276
/// A LET entered in dead code compiles once on a live scratch, so an init that
277
/// never returns ends it there as it does in live code.
278
831002
fn in_live_frame(
279
831002
    ctx: &mut CompileContext,
280
831002
    emit: &mut FunctionEmitter,
281
831002
    symbols: &mut SymbolTable,
282
831002
    args: &[Expr],
283
831002
    target: Target,
284
831002
    compile: LetCompile,
285
831002
) -> Result<WasmType> {
286
831002
    if emit.is_reachable() {
287
830977
        return compile(ctx, emit, symbols, args, target);
288
25
    }
289
25
    let (ty, _) = emit.on_live_scratch(|scratch| compile(ctx, scratch, symbols, args, target))?;
290
25
    Ok(ty)
291
831002
}
292

            
293
/// Saves the dynamic specials at `homes`, then runs `inner` with each
294
/// restored on every exit of it; without one, `inner` runs as it is.
295
698830
fn with_dynamic(
296
698830
    ctx: &mut CompileContext,
297
698830
    emit: &mut FunctionEmitter,
298
698830
    symbols: &mut SymbolTable,
299
698830
    (head, args): (&str, &[Expr]),
300
698830
    homes: &[DynamicHome],
301
698830
    target: Target,
302
698830
    inner: impl FnOnce(
303
698830
        &mut CompileContext,
304
698830
        &mut FunctionEmitter,
305
698830
        &mut SymbolTable,
306
698830
        Target,
307
698830
    ) -> Result<WasmType>,
308
698830
) -> Result<WasmType> {
309
698830
    let saved = save_all(ctx, emit, symbols, homes)?;
310
698830
    if saved.is_empty() {
311
678985
        return inner(ctx, emit, symbols, target);
312
19845
    }
313
19845
    let form = Expr::List(
314
19845
        std::iter::once(Expr::symbol(head))
315
19845
            .chain(args.iter().cloned())
316
19845
            .collect(),
317
19845
    );
318
19845
    let diverges = form_diverges_scratch(symbols, &form)?;
319
19845
    let cleanup = restore_forms(&saved);
320
19845
    let ty = protect(
321
19845
        ctx,
322
19845
        emit,
323
19845
        symbols,
324
19845
        &cleanup,
325
19845
        diverges,
326
19845
        |ctx, scratch, symbols| inner(ctx, scratch, symbols, Target::Stack),
327
716
    )?;
328
19129
    match target {
329
9013
        Target::Stack => Ok(ty),
330
7343
        Target::Value => serialize_stack_to_output(ctx, emit, ty).map(|()| WasmType::Bool),
331
        Target::Effect => {
332
2773
            emit.drop_value();
333
2773
            Ok(WasmType::Bool)
334
        }
335
    }
336
698830
}
337

            
338
772420
fn compile_target(
339
772420
    ctx: &mut CompileContext,
340
772420
    emit: &mut FunctionEmitter,
341
772420
    symbols: &mut SymbolTable,
342
772420
    body: &[Expr],
343
772420
    target: Target,
344
772420
) -> Result<WasmType> {
345
772420
    match target {
346
289718
        Target::Value => compile_body(ctx, emit, symbols, body).map(|()| WasmType::Bool),
347
460383
        Target::Stack => compile_body_for_stack(ctx, emit, symbols, body),
348
        Target::Effect => {
349
22319
            for form in body {
350
24653
                compile_for_effect(ctx, emit, symbols, form)?;
351
            }
352
20635
            Ok(WasmType::Bool)
353
        }
354
    }
355
772420
}
356

            
357
/// When a binding's emitted value is a closure, record its signature's result
358
/// type into the body's symbol table so the ctx-less eval surface (FOLD's
359
/// accumulator probe, binding-local sizing) can predict a HOF result type that
360
/// agrees with codegen — see `SymbolTable::closure_results`.
361
2219318
pub(in crate::compiler) fn record_closure_result(
362
2219318
    local: &mut SymbolTable,
363
2219318
    ctx: &CompileContext,
364
2219318
    bound: &Expr,
365
2219318
) -> Result<()> {
366
2219318
    if let Some((_, WasmType::Closure(sig))) = bound.place() {
367
178859
        let shape = ctx.closure_sig(sig)?;
368
178859
        local.record_closure_result(sig, shape.result);
369
178859
        local.record_closure_params(sig, &shape.params);
370
2040459
    }
371
2219318
    Ok(())
372
2219318
}