1
//! The local type of a DO variable, sized for both surfaces.
2

            
3
use crate::ast::{Expr, WasmType};
4
use crate::compiler::context::CompileContext;
5
use crate::compiler::emit::FunctionEmitter;
6
use crate::compiler::expr::{classify_stack_type, eval_value};
7
use crate::compiler::recompile::compiled_in_trial;
8
use crate::error::Result;
9
use crate::runtime::SymbolTable;
10

            
11
use super::super::setf_scan::{setf_rhs_of, step_pair_element};
12

            
13
/// The form that sizes a DO variable: its step, else the first body store into it.
14
344965
pub(in crate::compiler::special) fn var_type_hint<'a>(
15
344965
    step: Option<&'a Expr>,
16
344965
    body: &'a [Expr],
17
344965
    name: &str,
18
344965
) -> Option<&'a Expr> {
19
344965
    step.or_else(|| setf_rhs_of(body, name).into_iter().next())
20
344965
}
21

            
22
/// The form that yields a step's value: the last form of a `PROGN`, the
23
/// stored value of the last pair of a `SETF`/`SETQ`.
24
135744
fn step_value_form(step: &Expr) -> &Expr {
25
135744
    let Expr::List(elems) = step else {
26
2924
        return step;
27
    };
28
132820
    let Some(Expr::Symbol(head)) = elems.first() else {
29
        return step;
30
    };
31
132820
    match (head.to_ascii_uppercase().as_str(), &elems[1..]) {
32
2288
        ("PROGN", [.., last]) => step_value_form(last),
33
1040
        ("SETF" | "SETQ", [pairs @ .., value]) if pairs.len() % 2 == 1 => step_value_form(value),
34
129492
        _ => step,
35
    }
36
135744
}
37

            
38
/// What the eval surface learns of a nil-init DO variable's step.
39
enum StepFact {
40
    /// No exit form was reached: the step's value types as codegen pushes it.
41
    Typed(Option<WasmType>),
42
    /// The step reached an exit form or the evaluator rejected it; only
43
    /// compiling it tells whether it falls through and what it pushes.
44
    Exits,
45
}
46

            
47
79504
fn step_fact(symbols: &SymbolTable, step: &Expr) -> StepFact {
48
79504
    let exits = symbols.measurements().exits();
49
79504
    match eval_value(&mut symbols.speculative_clone(), step) {
50
63485
        Ok(value) if symbols.measurements().exits() == exits => {
51
6683
            StepFact::Typed(classify_stack_type(&value))
52
        }
53
72821
        _ => StepFact::Exits,
54
    }
55
79504
}
56

            
57
/// What every other init is sized by: the shared classifier, with Bytes as
58
/// StringRef and `I32` for forms it cannot type (their own compile declares the
59
/// real type, so a mismatch is an emit error).
60
345401
fn init_type(expr: &Expr) -> WasmType {
61
345401
    match expr {
62
        Expr::Bytes(_) => WasmType::StringRef,
63
345401
        _ => classify_stack_type(expr).unwrap_or(WasmType::I32),
64
    }
65
345401
}
66

            
67
/// How a DO variable is sized, decided once for both surfaces.
68
enum Sizing<'a> {
69
    Known(WasmType),
70
    /// A step that reaches an exit form: only compiling it tells the type,
71
    /// else `fallback`.
72
    Compile {
73
        step: &'a Expr,
74
        fallback: WasmType,
75
    },
76
}
77

            
78
345401
fn sizing<'a>(expr: &Expr, step_hint: Option<&'a Expr>, symbols: &SymbolTable) -> Sizing<'a> {
79
345401
    let fallback = init_type(expr);
80
345401
    let nil_step = matches!(expr, Expr::Nil).then_some(step_hint).flatten();
81
345401
    let Some(step) = nil_step.map(step_value_form) else {
82
212985
        return Sizing::Known(fallback);
83
    };
84
    // A `(cons V acc)` step is sized from the car's element, which the shared
85
    // classifier (typing a bare nil as `Bool`) cannot see.
86
132416
    if let Some(elem) = step_pair_element(step, symbols) {
87
52912
        return Sizing::Known(WasmType::PairRef(elem));
88
79504
    }
89
79504
    match step_fact(symbols, step) {
90
6683
        StepFact::Typed(ty) => Sizing::Known(ty.unwrap_or(fallback)),
91
72821
        StepFact::Exits => Sizing::Compile { step, fallback },
92
    }
93
345401
}
94

            
95
/// The local type of a DO variable the eval surface sizes; `None` when only
96
/// codegen can tell, so the loop's own type is left to it.
97
303704
pub(in crate::compiler::special) fn infer_wasm_type(
98
303704
    expr: &Expr,
99
303704
    step_hint: Option<&Expr>,
100
303704
    symbols: &SymbolTable,
101
303704
) -> Option<WasmType> {
102
303704
    match sizing(expr, step_hint, symbols) {
103
253148
        Sizing::Known(ty) => Some(ty),
104
50556
        Sizing::Compile { .. } => None,
105
    }
106
303704
}
107

            
108
/// The local type of a DO variable codegen sizes.
109
41697
pub(in crate::compiler::special) fn infer_compiled_type(
110
41697
    ctx: &mut CompileContext,
111
41697
    emit: &FunctionEmitter,
112
41697
    symbols: &mut SymbolTable,
113
41697
    expr: &Expr,
114
41697
    step_hint: Option<&Expr>,
115
41697
) -> Result<WasmType> {
116
41697
    match sizing(expr, step_hint, symbols) {
117
19432
        Sizing::Known(ty) => Ok(ty),
118
        Sizing::Compile { step, fallback } => {
119
22265
            let ty = compiled_in_trial(ctx, symbols, emit, step, |_, ty| Ok(ty))?;
120
22265
            Ok(ty.flatten().unwrap_or(fallback))
121
        }
122
    }
123
41697
}