1
//! Result-type reconciliation shared by the multi-arm special forms (IF,
2
//! HANDLER-CASE). Each reachable arm is an already-compiled value, a
3
//! dimension-flexible numeric literal, or `nil`; the latter two are emitted only
4
//! once the unified block type is known, so a literal crosses Index↔Scalar
5
//! (ADR-0028) and a `nil` beside a list stays a null pair.
6

            
7
use crate::ast::{Expr, WasmType};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::{
11
    classify_stack_type, compile_for_effect, compile_for_stack, compile_for_stack_as,
12
    compile_for_stack_expecting, emit_box_anyref, emit_nil_default, eval_value, fold_safe,
13
    fold_value, format_form,
14
};
15
pub(super) use crate::compiler::join::{
16
    Arm, Exit, reconcile_arms, reconcile_arms_expecting, rides,
17
};
18
use crate::compiler::join::{NilRepr, literal_fits, nil_repr};
19
use crate::compiler::native::{chain_pair_element, compile_constant_list};
20
use crate::error::{Error, Result};
21
use crate::runtime::SymbolTable;
22

            
23
use super::block_exits::form_diverges;
24

            
25
const PROGN: &str = "progn";
26

            
27
/// Compiles one arm into `scratch`: a diverging arm emits its exit and yields
28
/// `None`; a literal / `nil` arm is deferred to [`finish_arm`]; any other arm
29
/// is compiled now as a [`Arm::Value`], expecting `expected`.
30
///
31
/// A diverging arm is sealed here, before the enclosing `else`/`end`: code
32
/// compiled past its `throw`/`br` (`(+ 1 (error …))`) leaves a concrete value
33
/// on the polymorphic stack, and only `unreachable` truncates it to the frame
34
/// floor — `block_end`'s seal after `end` comes too late. Under
35
/// UNWIND-PROTECT's conditional rethrow the frame even sees the arm live.
36
2723017
pub(super) fn compile_arm(
37
2723017
    ctx: &mut CompileContext,
38
2723017
    scratch: &mut FunctionEmitter,
39
2723017
    symbols: &mut SymbolTable,
40
2723017
    expr: &Expr,
41
2723017
    expected: Option<WasmType>,
42
2723017
) -> Result<Option<Arm>> {
43
2723017
    if form_diverges(&mut symbols.clone(), expr)? {
44
78294
        compile_for_stack(ctx, scratch, symbols, expr)?;
45
77656
        scratch.unreachable();
46
77656
        return Ok(None);
47
2643885
    }
48
2643885
    if let Some(arm) = deferred_arm(symbols, expr) {
49
2382940
        return Ok(Some(arm));
50
260945
    }
51
260945
    Ok(Some(Arm::Value(compile_for_stack_expecting(
52
260945
        ctx, scratch, symbols, expr, expected,
53
260945
    )?)))
54
2723017
}
55

            
56
/// Compiles a BLOCK exit's or tail's value `expr` into its [`Exit`] and the
57
/// type it leaves on the stack. Its arm keeps a numeric literal or `nil`
58
/// distinct from a computed value. At a reconciled `target` a deferred arm is
59
/// emitted as it, and a computed value is compiled expecting it; at `AnyRef`
60
/// it is boxed, except an index, which [`lands_raw`] leaves to the join.
61
140869
pub(super) fn compile_exit_value(
62
140869
    ctx: &mut CompileContext,
63
140869
    emit: &mut FunctionEmitter,
64
140869
    symbols: &mut SymbolTable,
65
140869
    expr: &Expr,
66
140869
    target: Option<WasmType>,
67
140869
) -> Result<(Exit, WasmType)> {
68
    let deferred =
69
140869
        deferred_arm(symbols, expr).filter(|arm| matches!(arm, Arm::NumberLiteral(_) | Arm::Nil));
70
140869
    match (deferred, target) {
71
        (Some(arm @ Arm::NumberLiteral(_)), Some(WasmType::AnyRef)) => {
72
25317
            let raw = compile_for_stack(ctx, emit, symbols, expr)?;
73
25317
            Ok(land(ctx, emit, arm, raw, target))
74
        }
75
205
        (Some(arm), Some(result)) if finishes_at(arm, result) => {
76
204
            finish_arm(ctx, emit, symbols, expr, arm, result)?;
77
204
            Ok((
78
204
                Exit {
79
204
                    arm,
80
204
                    emitted: result,
81
204
                },
82
204
                result,
83
204
            ))
84
        }
85
        (Some(arm), _) => {
86
73107
            let emitted = compile_for_stack(ctx, emit, symbols, expr)?;
87
72684
            Ok((Exit { arm, emitted }, emitted))
88
        }
89
        (None, _) => {
90
42241
            let ty = compile_for_stack_expecting(ctx, emit, symbols, expr, target)?;
91
41218
            Ok(land(ctx, emit, Arm::Value(ty), ty, target))
92
        }
93
    }
94
140869
}
95

            
96
/// Whether an exit value of `stack` type, bound for `target`, is left raw for
97
/// the join to box where it lands: boxing an index can raise INDEX-OVERFLOW,
98
/// which no handler the exit crosses may catch (0011 F2/S12).
99
163006
pub(super) fn lands_raw(stack: WasmType, target: Option<WasmType>) -> bool {
100
163006
    stack == WasmType::I32 && target == Some(WasmType::AnyRef)
101
163006
}
102

            
103
/// The [`Exit`] of an emitted `raw` value bound for `target`, boxed now
104
/// unless it [`lands_raw`], and the type left on the stack.
105
66535
fn land(
106
66535
    ctx: &CompileContext,
107
66535
    emit: &mut FunctionEmitter,
108
66535
    arm: Arm,
109
66535
    raw: WasmType,
110
66535
    target: Option<WasmType>,
111
66535
) -> (Exit, WasmType) {
112
66535
    let emitted = match target {
113
32779
        Some(WasmType::AnyRef) => WasmType::AnyRef,
114
33756
        _ => raw,
115
    };
116
66535
    if lands_raw(raw, target) {
117
25771
        return (Exit { arm, emitted }, raw);
118
40764
    }
119
40764
    box_arm_value(ctx, emit, raw, emitted);
120
40764
    (Exit { arm, emitted }, emitted)
121
66535
}
122

            
123
/// Whether [`finish_arm`] emits the deferred `arm` as `result`: a literal
124
/// that fits it or is boxed into it, a `nil` that has a representation in it.
125
205
fn finishes_at(arm: Arm, result: WasmType) -> bool {
126
205
    match arm {
127
155
        Arm::NumberLiteral(lit) => literal_fits(result, lit) || result == WasmType::AnyRef,
128
50
        Arm::Nil => nil_repr(&result) != NilRepr::Never,
129
        Arm::Value(_) | Arm::ConstantList(_) => false,
130
    }
131
205
}
132

            
133
/// Runs `f` inside a runtime-conditional branch, so a compile-time-only
134
/// definition or SETF reached from it is refused rather than applied
135
/// unconditionally.
136
5325041
pub(in crate::compiler) fn in_runtime_branch<T>(
137
5325041
    symbols: &mut SymbolTable,
138
5325041
    f: impl FnOnce(&mut SymbolTable) -> Result<T>,
139
5325041
) -> Result<T> {
140
5325041
    symbols.enter_runtime_branch()?;
141
5325041
    let result = f(symbols);
142
5325041
    let exited = symbols.exit_runtime_branch();
143
5325041
    result.and_then(|value| exited.map(|()| value))
144
5325041
}
145

            
146
/// [`compile_arm`] for an arm that runs only when a runtime test selects it.
147
2577482
pub(super) fn compile_branch_arm(
148
2577482
    ctx: &mut CompileContext,
149
2577482
    scratch: &mut FunctionEmitter,
150
2577482
    symbols: &mut SymbolTable,
151
2577482
    expr: &Expr,
152
2577482
    expected: Option<WasmType>,
153
2577482
) -> Result<Option<Arm>> {
154
2577482
    in_runtime_branch(symbols, |symbols| {
155
2577482
        compile_arm(ctx, scratch, symbols, expr, expected)
156
2577482
    })
157
2577482
}
158

            
159
/// [`finish_arm`] for an arm that runs only when a runtime test selects it:
160
/// a deferred arm's effects compile here, so they need the same guard.
161
2576074
pub(super) fn finish_branch_arm(
162
2576074
    ctx: &mut CompileContext,
163
2576074
    scratch: &mut FunctionEmitter,
164
2576074
    symbols: &mut SymbolTable,
165
2576074
    expr: &Expr,
166
2576074
    arm: Arm,
167
2576074
    result: WasmType,
168
2576074
) -> Result<()> {
169
2576074
    in_runtime_branch(symbols, |symbols| {
170
2576074
        finish_arm(ctx, scratch, symbols, expr, arm, result)
171
2576074
    })
172
2576074
}
173

            
174
/// The deferred arm of a non-diverging `expr` that resolves to a numeric
175
/// literal or `nil`; `None` when the arm must be compiled up front. Probes on a
176
/// clone so no compile-time effect is applied.
177
2784754
fn deferred_arm(symbols: &SymbolTable, expr: &Expr) -> Option<Arm> {
178
2784754
    if let Some(arm) = progn_value_arm(expr) {
179
21262
        return Some(arm);
180
2763492
    }
181
2763492
    match eval_value(&mut symbols.clone(), expr).ok()? {
182
73245
        Expr::Nil => Some(Arm::Nil),
183
        // Only a fold-safe constant list is deferred: any other list-valued
184
        // arm is compiled, so the effects it carries are emitted.
185
18323
        Expr::Datum(inner) if fold_safe(symbols, expr) => match *inner {
186
13718
            Expr::List(members) => chain_pair_element(&members).ok().map(Arm::ConstantList),
187
3955
            _ => None,
188
        },
189
650
        Expr::Datum(_) => None,
190
2630576
        value => literal_arm(&value),
191
    }
192
2784754
}
193

            
194
/// The arm of a PROGN whose value form is literally `nil` or a number: that
195
/// is its value whatever runtime effects precede it, though the evaluator
196
/// types such a body as runtime.
197
3678602
fn progn_value_arm(expr: &Expr) -> Option<Arm> {
198
3678602
    match progn_value(expr)? {
199
2088
        Expr::Nil => Some(Arm::Nil),
200
71550
        value => literal_arm(value),
201
    }
202
3678602
}
203

            
204
/// The form a PROGN nest takes its value from; `None` when `expr` is no PROGN.
205
5964005
fn progn_value(expr: &Expr) -> Option<&Expr> {
206
5964005
    let mut value = None;
207
5964005
    let mut form = expr;
208
6054931
    while let Expr::List(elems) = form
209
674929
        && let (Some(Expr::Symbol(head)), Some(last)) = (elems.first(), elems.last())
210
674929
        && elems.len() > 1
211
658377
        && head.eq_ignore_ascii_case(PROGN)
212
    {
213
90926
        value = Some(last);
214
90926
        form = last;
215
    }
216
5964005
    value
217
5964005
}
218

            
219
/// The arm a non-diverging `expr` contributes on the ctx-less eval surface,
220
/// peeked on a clone inside a runtime branch — the mirror of
221
/// [`compile_branch_arm`]. A constant list lowers to
222
/// a pair chain typed by the LIST rule; an unclassifiable value is `I32`.
223
954762
pub(super) fn eval_arm(symbols: &SymbolTable, expr: &Expr) -> Result<Option<Arm>> {
224
954762
    let mut probe = symbols.clone();
225
954762
    probe.enter_runtime_branch()?;
226
954762
    let mut pristine = probe.clone();
227
954762
    let exits = probe.measurements().exits();
228
954762
    let value = eval_value(&mut probe, expr);
229
954762
    let exited = probe.measurements().exits() != exits;
230
954762
    if (exited || value.is_err()) && form_diverges(&mut pristine, expr)? {
231
139239
        probe.measurements().note_exit();
232
139239
        return Ok(None);
233
815523
    }
234
815523
    Ok(Some(arm_of_form(expr, &value?)?))
235
954762
}
236

            
237
/// The arm of a form whose resolved eval value is `value`.
238
893842
pub(super) fn arm_of_form(expr: &Expr, value: &Expr) -> Result<Arm> {
239
893842
    match progn_value_arm(expr) {
240
2389
        Some(arm) => Ok(arm),
241
891453
        None => arm_of_value(value),
242
    }
243
893842
}
244

            
245
/// The arm a resolved eval value contributes; a value with no stack type is
246
/// a structured error.
247
891453
fn arm_of_value(value: &Expr) -> Result<Arm> {
248
891453
    match value {
249
173625
        Expr::Nil => Ok(Arm::Nil),
250
15001
        Expr::Datum(inner) if let Expr::List(members) = inner.as_ref() => {
251
11248
            Ok(Arm::Value(WasmType::PairRef(chain_pair_element(members)?)))
252
        }
253
706580
        _ => match (literal_arm(value), classify_stack_type(value)) {
254
306558
            (Some(arm), _) => Ok(arm),
255
396067
            (None, Some(ty)) => Ok(Arm::Value(ty)),
256
3955
            (None, None) => Err(Error::Compile(format!(
257
3955
                "no runtime value type for {}",
258
3955
                format_form(value)
259
3955
            ))),
260
        },
261
    }
262
891453
}
263

            
264
3408706
fn literal_arm(value: &Expr) -> Option<Arm> {
265
3408706
    match value {
266
2703564
        Expr::Number(_) => classify_stack_type(value).map(Arm::NumberLiteral),
267
705142
        _ => None,
268
    }
269
3408706
}
270

            
271
/// Completes an arm into its `scratch` at the unified `result`: a compiled
272
/// value is boxed when the block is `AnyRef`, a deferred literal is compiled at
273
/// the result stratum, a deferred `nil` emits its effects then the typed nil.
274
2576278
pub(super) fn finish_arm(
275
2576278
    ctx: &mut CompileContext,
276
2576278
    scratch: &mut FunctionEmitter,
277
2576278
    symbols: &mut SymbolTable,
278
2576278
    expr: &Expr,
279
2576278
    arm: Arm,
280
2576278
    result: WasmType,
281
2576278
) -> Result<()> {
282
2576278
    let raw = finish_arm_raw(ctx, scratch, symbols, expr, arm, result)?;
283
2575654
    box_arm_value(ctx, scratch, raw, result);
284
2575654
    Ok(())
285
2576278
}
286

            
287
/// [`finish_arm`] short of the box, for a caller that boxes where the value
288
/// lands; returns the type left on the stack.
289
2625568
pub(super) fn finish_arm_raw(
290
2625568
    ctx: &mut CompileContext,
291
2625568
    scratch: &mut FunctionEmitter,
292
2625568
    symbols: &mut SymbolTable,
293
2625568
    expr: &Expr,
294
2625568
    arm: Arm,
295
2625568
    result: WasmType,
296
2625568
) -> Result<WasmType> {
297
2625568
    match arm {
298
245217
        Arm::Value(ty) => Ok(ty),
299
2298047
        Arm::NumberLiteral(lit) if literal_fits(result, lit) => {
300
2285403
            match progn_value(expr) {
301
                Some(value) => {
302
17287
                    compile_for_effect(ctx, scratch, symbols, expr)?;
303
15414
                    compile_for_stack_as(ctx, scratch, symbols, value, result)?;
304
                }
305
2268116
                None => compile_for_stack_as(ctx, scratch, symbols, expr, result)?,
306
            }
307
2283530
            Ok(result)
308
        }
309
12644
        Arm::NumberLiteral(_) => compile_for_stack(ctx, scratch, symbols, expr),
310
        Arm::Nil => {
311
70683
            if !matches!(expr, Expr::Nil) {
312
3580
                compile_for_effect(ctx, scratch, symbols, expr)?;
313
67103
            }
314
69643
            emit_nil_default(ctx, scratch, result)?;
315
69643
            Ok(result)
316
        }
317
        Arm::ConstantList(own) => {
318
11621
            let elem = match result {
319
8083
                WasmType::PairRef(elem) => elem,
320
3538
                _ => own,
321
            };
322
11621
            let members = constant_list_members(symbols, expr)?;
323
11621
            compile_constant_list(ctx, scratch, symbols, members, elem)
324
        }
325
    }
326
2625568
}
327

            
328
/// The members of a constant-list arm, which `deferred_arm` admitted only
329
/// when fold-safe.
330
11621
fn constant_list_members(symbols: &mut SymbolTable, expr: &Expr) -> Result<Vec<Expr>> {
331
11621
    match fold_value(symbols, expr)? {
332
11621
        Some(Expr::Datum(inner)) => match *inner {
333
11621
            Expr::List(members) => Ok(members),
334
            other => Err(not_a_constant_list(&other)),
335
        },
336
        Some(other) => Err(not_a_constant_list(&other)),
337
        None => Err(not_a_constant_list(expr)),
338
    }
339
11621
}
340

            
341
fn not_a_constant_list(value: &Expr) -> Error {
342
    Error::Compile(format!(
343
        "constant-list arm resolved to {value:?}, not a list"
344
    ))
345
}
346

            
347
/// Retypes an already-emitted arm value of `ty` to the block `result`: an
348
/// i32-repr value boxes into an anyref block. A `PairRef` widening never
349
/// needs a rebuild — a bool car already rides the same ref.null/`$t`
350
/// representation as an anyref car (ADR-0033).
351
2684369
pub(super) fn box_arm_value(
352
2684369
    ctx: &CompileContext,
353
2684369
    scratch: &mut FunctionEmitter,
354
2684369
    ty: WasmType,
355
2684369
    result: WasmType,
356
2684369
) {
357
2684369
    if result == WasmType::AnyRef {
358
96674
        emit_box_anyref(ctx, scratch, ty);
359
2587695
    }
360
2684369
}
361

            
362
/// Pushes `nil` typed as the block `result` — an alias for
363
/// [`emit_nil_default`], kept for `IF`'s missing-else call site.
364
11242
pub(super) fn emit_typed_nil(
365
11242
    ctx: &CompileContext,
366
11242
    scratch: &mut FunctionEmitter,
367
11242
    result: WasmType,
368
11242
) -> Result<()> {
369
11242
    emit_nil_default(ctx, scratch, result)
370
11242
}
371

            
372
#[cfg(test)]
373
#[path = "arms_tests.rs"]
374
mod tests;
375

            
376
#[cfg(test)]
377
#[path = "landing_tests.rs"]
378
mod landing_tests;