1
//! `BLOCK` / `RETURN-FROM` — Common-Lisp lexical labelled-exit
2
//! primitive. `(block name body...)` opens a wasm `block` whose label
3
//! is bound to `name` for the body's lexical extent;
4
//! `(return-from name value)` walks the BLOCK label stack and emits
5
//! `<value>` followed by `br <relative-depth>` to that block's exit.
6
//!
7
//! The block's wasm result type is discovered at **emit time**: the body
8
//! is compiled into a scratch buffer first; each reachable
9
//! `(return-from name v)` records `v`'s arm into the block frame, and
10
//! the fall-through tail (if control can reach it) contributes its arm
11
//! too. Reconciling those gives the result type `T`; then `block (result T)`
12
//! is opened in the parent and the scratch bytes spliced in. A numeric
13
//! literal arm emitted at another type than `T` makes that first pass a
14
//! discarded `recompile` probe: only `T`, as a `StructuralType`, survives
15
//! it, and a second pass compiles every literal exit and tail at `T`
16
//! (0014 P6a-i). The discarded pass also reports every nested block's join,
17
//! so the second pass compiles each of them once, at its join; a nested
18
//! block left unsettled while an enclosing pass can still be discarded
19
//! defers to it instead of recompiling itself (4.3b). Because only
20
//! *compiled* (reachable) exits record, code stored as a value
21
//! (quote / lambda / labels bodies, discarded macro args) contributes
22
//! nothing — no syntactic pre-scan and no per-form blocklist. The scratch
23
//! emitter is seeded at the depth the block frame will occupy, so every
24
//! relative `br` (incl. RETURN-FROM to an outer block) stays correct
25
//! after splicing.
26
//!
27
//! Lexical-only: a RETURN-FROM whose name doesn't resolve to a BLOCK
28
//! frame in scope is a structured compile error. Dynamic non-local
29
//! exits are Tier 3 territory (try_table + throw).
30

            
31
use wasm_encoder::BlockType;
32

            
33
use crate::ast::{Expr, WasmType};
34
use crate::compiler::context::CompileContext;
35
use crate::compiler::emit::FunctionEmitter;
36
use crate::compiler::expr::{
37
    compile_for_effect, emit_box_anyref, eval_value, probe_value, serialize_stack_to_output,
38
};
39
use crate::compiler::join::NEVER_RETURNS;
40
use crate::compiler::observations::{Observations, ObservedBlock, StructuralType};
41
use crate::compiler::recompile::Trial;
42
use crate::compiler::recompile::recompile;
43
use crate::error::{Error, Result};
44
use crate::runtime::SymbolTable;
45

            
46
use super::super::binding::{eval_body, infer_runtime_type_with_body};
47
use super::arms::{
48
    Arm, Exit, arm_of_form, compile_exit_value, lands_raw, reconcile_arms,
49
    reconcile_arms_expecting, rides,
50
};
51
use super::block_exits::form_diverges;
52
use super::block_parse::{parse_block, parse_return_from};
53
use super::exit_scan::has_exit_to;
54
use super::skip_region::{after_exit, first_skipped, in_region, kept_definitions};
55

            
56
/// A block's value is its body's, except that a `return-from` to it makes the
57
/// value runtime: an exit's value is only known once emitted. The exits
58
/// evaluated against the block join with the tail as the compiled block's
59
/// do; an exit `has_exit_to` sees but the walk never reached leaves the tail
60
/// to type it. A transfer naming this block (raised only while a macro body
61
/// runs, see [`eval_return_from`]) is the block's value.
62
43200
pub(super) fn eval_block(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
63
43200
    symbols.enter_shared_recursion()?;
64
42852
    let evaluated = eval_block_site(symbols, args);
65
42852
    let exited = symbols.exit_shared_recursion();
66
42852
    let value = evaluated?;
67
30616
    exited?;
68
30616
    Ok(value)
69
43200
}
70

            
71
42852
fn eval_block_site(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
72
42852
    let (name, body) = parse_block(args)?;
73
42851
    let (value, exits) = symbols.with_eval_block(name, |symbols| eval_body(symbols, body));
74
42851
    let value = match value {
75
2845
        Err(Error::Transfer { block, value }) if block == name => {
76
2818
            return Ok(*value);
77
        }
78
40033
        other => other?,
79
    };
80
27798
    match body.last() {
81
27798
        Some(_) if raises_transfers(symbols) => Ok(value),
82
25244
        Some(tail) if !exits.is_empty() => {
83
7765
            let ty = exit_join(symbols, body, tail, &value, exits)?;
84
7765
            Ok(Expr::WasmRuntime(ty))
85
        }
86
17479
        Some(tail) if !value.is_wasm_runtime() && has_exit_to(symbols, name, body) => {
87
889
            let ty = infer_runtime_type_with_body(&value, tail, body, symbols);
88
889
            Ok(Expr::WasmRuntime(ty))
89
        }
90
16590
        _ => Ok(value),
91
    }
92
42852
}
93

            
94
/// The block's type from its evaluated exit `arms` and, unless a body form
95
/// diverges, the tail's arm — the arms [`compile_block_pass`] reconciles.
96
7765
fn exit_join(
97
7765
    symbols: &SymbolTable,
98
7765
    body: &[Expr],
99
7765
    tail: &Expr,
100
7765
    value: &Expr,
101
7765
    mut arms: Vec<Arm>,
102
7765
) -> Result<WasmType> {
103
7765
    let mut falls_through = true;
104
7765
    for form in body {
105
12071
        if form_diverges(&mut symbols.clone(), form)? {
106
706
            falls_through = false;
107
706
            break;
108
11365
        }
109
    }
110
7765
    if falls_through {
111
7059
        arms.push(arm_of_form(tail, value)?);
112
706
    }
113
7765
    Ok(reconcile_arms(&arms))
114
7765
}
115

            
116
/// Inside a macro body, outside any runtime branch, the evaluator is the real
117
/// interpreter: a reached exit raises a transfer and a block that completed
118
/// without one has its body's value. Everywhere else evaluation only peeks at
119
/// types for codegen, which compiles the exit itself.
120
205119
fn raises_transfers(symbols: &SymbolTable) -> bool {
121
205119
    symbols.is_macro_expansion() && !symbols.is_under_any_runtime_guard()
122
205119
}
123

            
124
177321
pub(super) fn eval_return_from(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
125
177321
    let (name, value) = parse_return_from(args)?;
126
177321
    symbols.measurements().note_exit();
127
177321
    if raises_transfers(symbols) {
128
3244
        let value = eval_value(symbols, value)?;
129
3244
        return Err(Error::Transfer {
130
3244
            block: name.to_string(),
131
3244
            value: Box::new(value),
132
3244
        });
133
174077
    }
134
174077
    let value_ty = super::block_exits::peek_value_type(symbols, value)?;
135
174077
    if !form_diverges(&mut symbols.clone(), value)? {
136
174076
        let resolved = probe_value(&mut symbols.clone(), value)?;
137
174076
        symbols.record_eval_exit(name, arm_of_form(value, &resolved)?);
138
1
    }
139
173661
    Ok(Expr::WasmRuntime(value_ty))
140
177321
}
141

            
142
28529
pub(super) fn compile_block(
143
28529
    ctx: &mut CompileContext,
144
28529
    emit: &mut FunctionEmitter,
145
28529
    symbols: &mut SymbolTable,
146
28529
    args: &[Expr],
147
28529
) -> Result<()> {
148
28529
    let ty = compile_block_for_stack(ctx, emit, symbols, args)?;
149
20387
    serialize_stack_to_output(ctx, emit, ty)
150
28529
}
151

            
152
10624
pub(super) fn compile_block_for_effect(
153
10624
    ctx: &mut CompileContext,
154
10624
    emit: &mut FunctionEmitter,
155
10624
    symbols: &mut SymbolTable,
156
10624
    args: &[Expr],
157
10624
) -> Result<()> {
158
10624
    compile_block_for_stack(ctx, emit, symbols, args)?;
159
7705
    emit.drop_value();
160
7705
    Ok(())
161
10624
}
162

            
163
60627
pub(super) fn compile_block_for_stack(
164
60627
    ctx: &mut CompileContext,
165
60627
    emit: &mut FunctionEmitter,
166
60627
    symbols: &mut SymbolTable,
167
60627
    args: &[Expr],
168
60627
) -> Result<WasmType> {
169
60627
    compile_block_expecting(ctx, emit, symbols, args, None)
170
60627
}
171

            
172
/// A BLOCK whose consumer expects `expected`: its first pass targets it, so a
173
/// block whose arms are all literals that fit it compiles once, as it.
174
60745
pub(super) fn compile_block_expecting(
175
60745
    ctx: &mut CompileContext,
176
60745
    emit: &mut FunctionEmitter,
177
60745
    symbols: &mut SymbolTable,
178
60745
    args: &[Expr],
179
60745
    expected: Option<WasmType>,
180
60745
) -> Result<WasmType> {
181
60745
    symbols.enter_shared_recursion()?;
182
60739
    let compiled = compile_block_site(ctx, emit, symbols, args, expected);
183
60739
    symbols.leave_shared_recursion(compiled)
184
60745
}
185

            
186
60739
fn compile_block_site(
187
60739
    ctx: &mut CompileContext,
188
60739
    emit: &mut FunctionEmitter,
189
60739
    symbols: &mut SymbolTable,
190
60739
    args: &[Expr],
191
60739
    expected: Option<WasmType>,
192
60739
) -> Result<WasmType> {
193
60739
    let (name, body) = parse_block(args)?;
194
60736
    if body.is_empty() {
195
        // Empty `(block n)` ≡ nil — falsy i31, typed `Bool` to serialize as
196
        // Nil and match the eval mirror (`eval_block` → `Expr::Nil`).
197
3
        emit.i32_const(0);
198
3
        return Ok(WasmType::Bool);
199
60733
    }
200

            
201
    // The block frame sits one structured-control level below the parent's
202
    // current depth. The body compiles into a scratch emitter seeded there,
203
    // so relative `br` targets resolve as if the frame were already open;
204
    // splicing preserves them.
205
60733
    let site = BlockSite {
206
60733
        name,
207
60733
        body,
208
60733
        frame_depth: emit.block_depth() + 1,
209
60733
        start: ctx.block_join_start(),
210
60733
        expected,
211
60733
    };
212
60733
    let guess = ctx.expected_block_join(name, body.len());
213
60733
    let outer = ctx.open_block_probe();
214
60733
    let first = recompile(ctx, symbols, |ctx, symbols| {
215
60733
        probe_block(ctx, symbols, &site, guess.as_ref(), outer.is_open())
216
60733
    });
217
60733
    let deferred = matches!(&first, Ok(Trial::Commit(pass)) if !pass.settled);
218
60733
    ctx.close_block_probe(outer, deferred);
219
60733
    let (pass, passes) = match first? {
220
42270
        Trial::Commit(pass) => (pass, 1),
221
        Trial::Discard(observed) => {
222
6589
            let target = observed.result.intern(ctx)?;
223
6589
            let pass = ctx.expecting_block_joins(observed.blocks, |ctx| {
224
6589
                compile_block_pass(ctx, symbols, &site, Some(target))
225
6589
            })?;
226
6589
            (pass, 2)
227
        }
228
    };
229
48859
    ctx.compile_stats_mut().note_block_passes(passes);
230
48859
    let join = StructuralType::of(pass.result_ty, ctx)?;
231
48859
    ctx.record_block_join(
232
48859
        site.start,
233
48859
        ObservedBlock {
234
48859
            name: name.to_string(),
235
48859
            body_len: body.len(),
236
48859
            join,
237
48859
        },
238
48859
    );
239
48859
    emit.block_start_typed(BlockType::Result(ctx.wasm_val_type(pass.result_ty)?));
240
48859
    if pass.padded {
241
6626
        emit.block_start_typed(BlockType::Result(ctx.wasm_val_type(WasmType::I32)?));
242
42233
    }
243
48859
    emit.splice(&pass.scratch)?;
244
48859
    if pass.padded {
245
6626
        emit.block_end()?;
246
6626
        emit_box_anyref(ctx, emit, WasmType::I32);
247
42233
    }
248
48859
    emit.block_end()?;
249
48859
    Ok(pass.result_ty)
250
60739
}
251

            
252
/// Whether a pass at `target` opens an index pad just inside the block: the
253
/// `(result i32)` block an index exit [`lands_raw`] into, boxed after it.
254
67322
fn pads_index(target: Option<WasmType>) -> bool {
255
67322
    target == Some(WasmType::AnyRef)
256
67322
}
257

            
258
/// Where a BLOCK compiles: its label and body, the depth its frame takes,
259
/// where its join is recorded and the type its consumer expects.
260
struct BlockSite<'a> {
261
    name: &'a str,
262
    body: &'a [Expr],
263
    frame_depth: u32,
264
    start: usize,
265
    expected: Option<WasmType>,
266
}
267

            
268
/// One compilation of a BLOCK body: its bytes, its reconciled result type,
269
/// whether every arm was already emitted as that type and whether the bytes
270
/// sit in an index pad.
271
struct BlockPass {
272
    scratch: FunctionEmitter,
273
    result_ty: WasmType,
274
    settled: bool,
275
    padded: bool,
276
}
277

            
278
/// The first pass, at the join an enclosing pass observed for this block if
279
/// it has one, else at the type its consumer expects. It commits when
280
/// settled, or unsettled when `may_defer` (an enclosing pass will be
281
/// discarded instead); otherwise it is discarded and reports its join and its
282
/// nested blocks' joins.
283
60733
fn probe_block(
284
60733
    ctx: &mut CompileContext,
285
60733
    symbols: &mut SymbolTable,
286
60733
    site: &BlockSite,
287
60733
    guess: Option<&StructuralType>,
288
60733
    may_defer: bool,
289
60733
) -> Result<Trial<BlockPass, Observations>> {
290
60733
    let target = guess
291
2645
        .map(|join| join.intern(ctx))
292
        .transpose()?
293
60733
        .or(site.expected);
294
60733
    let pass = compile_block_pass(ctx, symbols, site, target)?;
295
48859
    if pass.settled || may_defer {
296
42270
        return Ok(Trial::Commit(pass));
297
6589
    }
298
6589
    let result = StructuralType::of(pass.result_ty, ctx)?;
299
6589
    let blocks = ctx.take_block_joins(site.start);
300
6589
    Ok(Trial::Discard(Observations { result, blocks }))
301
60733
}
302

            
303
/// Compiles the body at `target`, or, without one, at each arm's own type. A
304
/// join of literals alone that fit the consumer's expectation is it; a guessed
305
/// `target` is never adopted, so a stale guess cannot settle. The pass is
306
/// settled when every exit's bytes already stand as the join.
307
67322
fn compile_block_pass(
308
67322
    ctx: &mut CompileContext,
309
67322
    symbols: &mut SymbolTable,
310
67322
    site: &BlockSite,
311
67322
    target: Option<WasmType>,
312
67322
) -> Result<BlockPass> {
313
    let BlockSite {
314
        name,
315
        body,
316
        frame_depth,
317
        expected,
318
        ..
319
67322
    } = *site;
320
67322
    let padded = pads_index(target);
321
67322
    let mut scratch = FunctionEmitter::new_seeded(frame_depth + u32::from(padded));
322
67322
    ctx.push_block_label(name, frame_depth, target);
323
67322
    let body_result = compile_block_body(ctx, &mut scratch, symbols, name, body, target);
324
67322
    let exits = ctx.pop_block_label(name)?;
325
67322
    let tail = body_result?;
326
55448
    if let Some((_, stack)) = tail
327
40087
        && padded
328
6622
        && !lands_raw(stack, target)
329
    {
330
6601
        scratch.br(1);
331
48847
    }
332
55448
    let compiled: Vec<Exit> = tail
333
        .map(|(exit, _)| exit)
334
        .into_iter()
335
55448
        .chain(exits)
336
        .collect();
337
82751
    let arms: Vec<Arm> = compiled.iter().map(|exit| exit.arm).collect();
338
55448
    let result_ty = reconcile_arms_expecting(&arms, expected);
339

            
340
55448
    if tail.is_none() {
341
        // The body's tail is dead (an earlier form diverged); its concrete
342
        // value would clash with the block result type, so a trailing
343
        // `unreachable` resets the validator to a polymorphic stack. Live
344
        // values leave only via the recorded `return-from` `br` edges.
345
15361
        scratch.unreachable();
346
40087
    }
347

            
348
    let settled =
349
78172
        !ctx.block_probe_dirty() && compiled.iter().all(|exit| rides(exit.emitted, result_ty));
350
55448
    Ok(BlockPass {
351
55448
        scratch,
352
55448
        result_ty,
353
55448
        settled,
354
55448
        padded,
355
55448
    })
356
67322
}
357

            
358
/// Compile a BLOCK body into `emit`, stopping at the first form that
359
/// unconditionally diverges — sequential forms after it are dead and must
360
/// not be emitted (their `(return-from)`s would record bogus exits, and
361
/// their bytes are unreachable). Returns the tail's exit and the type it left
362
/// on the stack, `None` when control cannot fall through to it. From the
363
/// first form that may exit the block on, a definition is refused.
364
67322
fn compile_block_body(
365
67322
    ctx: &mut CompileContext,
366
67322
    emit: &mut FunctionEmitter,
367
67322
    symbols: &mut SymbolTable,
368
67322
    name: &str,
369
67322
    body: &[Expr],
370
67322
    target: Option<WasmType>,
371
67322
) -> Result<Option<(Exit, WasmType)>> {
372
67322
    let last = body.len() - 1;
373
175419
    let exits = |form: &Expr| has_exit_to(symbols, name, std::slice::from_ref(form));
374
67322
    let first_exit = first_skipped(body, exits);
375
67322
    let kept = kept_definitions(body, first_exit, exits);
376
67322
    for (idx, form) in body.iter().enumerate() {
377
93586
        let region = after_exit(idx, first_exit.at, "BLOCK", &kept);
378
        // Classify divergence on a CLONE: `form_diverges` runs `eval_value`
379
        // (const-folding, macro expansion) which can mutate the symbol
380
        // table via `setf`/`defparameter`. The form is compiled for real
381
        // right after, so letting the classification mutate `symbols` would
382
        // double-apply those effects. The clone keeps the query pure.
383
93586
        let diverges = form_diverges(&mut symbols.clone(), form)?;
384
93584
        if idx == last {
385
51024
            let tail = in_region(symbols, region.as_ref(), |symbols| {
386
51024
                compile_exit_value(ctx, emit, symbols, form, target)
387
51024
            })?;
388
49578
            return Ok((!diverges).then_some(tail));
389
42560
        }
390
        // A diverging non-tail form exits the block; the rest is dead. It is
391
        // compiled for effect so its `return-from` records and its `br` is
392
        // emitted — the tail value comes from the recorded exits, sealed by
393
        // the caller's `unreachable`.
394
42560
        in_region(symbols, region.as_ref(), |symbols| {
395
42560
            compile_for_effect(ctx, emit, symbols, form)
396
42560
        })?;
397
32134
        if diverges {
398
5870
            return Ok(None);
399
26264
        }
400
    }
401
    // Unreachable: an empty body is handled by the caller.
402
    Ok(None)
403
67322
}
404

            
405
26681
pub(super) fn compile_return_from(
406
26681
    ctx: &mut CompileContext,
407
26681
    emit: &mut FunctionEmitter,
408
26681
    symbols: &mut SymbolTable,
409
26681
    args: &[Expr],
410
26681
) -> Result<()> {
411
26681
    compile_return_from_for_stack(ctx, emit, symbols, args)?;
412
26459
    Ok(())
413
26681
}
414

            
415
/// A RETURN-FROM inside a function body (a closure compiles as its own
416
/// function) sees only that body's blocks; the message says so when the
417
/// block it names is open in the code around it.
418
666
fn no_enclosing_block(ctx: &CompileContext, name: &str) -> Error {
419
666
    match ctx.block_is_out_of_reach(name) {
420
217
        true => Error::Compile(format!(
421
217
            "RETURN-FROM '{name}' inside a function or closure cannot exit a BLOCK of its \
422
217
             enclosing code; return a value from the function instead"
423
217
        )),
424
449
        false => Error::Compile(format!(
425
449
            "RETURN-FROM '{name}': no enclosing BLOCK with that name"
426
449
        )),
427
    }
428
666
}
429

            
430
90614
pub(super) fn compile_return_from_for_stack(
431
90614
    ctx: &mut CompileContext,
432
90614
    emit: &mut FunctionEmitter,
433
90614
    symbols: &mut SymbolTable,
434
90614
    args: &[Expr],
435
90614
) -> Result<WasmType> {
436
90614
    let (name, value) = parse_return_from(args)?;
437
90611
    let (target_depth, target) = match ctx.lookup_block_label(name) {
438
89945
        Some(frame) => (frame.wasm_depth, frame.target),
439
666
        None => return Err(no_enclosing_block(ctx, name)),
440
    };
441
89945
    if !emit.is_reachable() {
442
        // Dead code (a DO step after a body that always exits): no value
443
        // leaves, so nothing joins the block and no `br` is needed.
444
100
        compile_for_effect(ctx, emit, symbols, value)?;
445
100
        return Ok(NEVER_RETURNS);
446
89845
    }
447
89845
    let (exit, stack) = compile_exit_value(ctx, emit, symbols, value, target)?;
448
    // Emit-time discovery: the enclosing block reconciles its result type
449
    // from exactly the exits that can carry a value.
450
89845
    if emit.is_reachable() {
451
89633
        ctx.record_block_exit(name, exit);
452
212
    }
453
    // CL unwind semantics: before branching out, run the cleanup of every
454
    // `(unwind-protect)` this exit crosses (innermost-first). The value is
455
    // already on the stack; cleanups compile for effect (stack-neutral) so
456
    // they don't disturb it. `br` then carries the value to the target block.
457
89845
    super::unwind_protect::emit_crossing_cleanups(ctx, emit, symbols, target_depth)?;
458
89845
    let landing = target_depth + u32::from(lands_raw(stack, target));
459
89845
    let current = emit.block_depth();
460
89845
    let relative = current.checked_sub(landing).ok_or_else(|| {
461
        Error::Compile(format!(
462
            "RETURN-FROM '{name}': inconsistent block-depth tracking ({current} < {landing})"
463
        ))
464
    })?;
465
89845
    emit.br(relative);
466
    // After a `br`, control never reaches here. wasm's stack polymorphism
467
    // past `unreachable` lets the validator infer any surrounding-block
468
    // result type, so we don't materialize a typed value.
469
89845
    emit.unreachable();
470
    // A lone arm reconciles to its own type.
471
89845
    Ok(reconcile_arms(&[exit.arm]))
472
90614
}
473

            
474
#[cfg(test)]
475
#[path = "block_tests.rs"]
476
mod tests;
477

            
478
#[cfg(test)]
479
#[path = "block_join_tests.rs"]
480
mod join_tests;
481

            
482
#[cfg(test)]
483
#[path = "block_memo_tests.rs"]
484
mod memo_tests;
485

            
486
#[cfg(test)]
487
#[path = "block_eval_join_tests.rs"]
488
mod eval_join_tests;