1
//! Closure parameter-type inference from body usage.
2
//!
3
//! A value-position `(lambda …)` lifted to a closure needs user-visible param
4
//! types. Defaulting every param to `Ratio` mis-types a list accumulator (a
5
//! param used as a `(cons CAR param)` cdr is a pair, not a scalar), so FOLD /
6
//! MAP over such a closure rejected it. This module infers each required
7
//! param's `WasmType` from how the body uses it; the closure's result type then
8
//! follows from compiling the body under those param types.
9
//!
10
//! Inferred shapes: a param used as the CDR of `(cons CAR param)` →
11
//! `PairRef(<car cell element>)`, a string-native argument → `StringRef`, one
12
//! beside a bound value, a literal or a form of known result type in arithmetic
13
//! or a comparison → that operand's numeric dimension, one handed to a closure
14
//! or a user function → the parameter type the callee gives it, and one under
15
//! `THE` → its type. A param no use pins gets the one dimension under which a
16
//! trial evaluation of the body fits (`trial`), else the first dimension that
17
//! fits is its placeholder (`PLACEHOLDER` when none is decided); a call whose argument does not fit it recompiles the closure
18
//! source for the argument kinds (`expr::respecialise`). The scan is SCOPE-AWARE: a binder
19
//! (`lambda`/`let`/`let*`/`do`/`do*`/`dolist`) that rebinds the name shadows the
20
//! param in its BODY, so a use of the inner variable must not retype the outer
21
//! param, and the names it binds hide those variables as neighbours — but the
22
//! binder's INIT expressions (and a `dolist` list-expr) are in the OUTER scope
23
//! and ARE scanned.
24

            
25
use crate::ast::{Expr, LambdaParams, PairElement, WasmType};
26
use crate::runtime::{SymbolTable, with_sufficient_stack};
27

            
28
/// The type of a parameter nothing decides, the dimension an integer literal
29
/// has: the first trial dimension, kept for a closure a call cannot recompile
30
/// from source.
31
pub(in crate::compiler) const PLACEHOLDER: WasmType = WasmType::I32;
32

            
33
mod scope;
34
mod trial;
35
use scope::Scope;
36

            
37
/// The scan and trial verdicts on a lambda's required params.
38
pub(in crate::compiler) struct Inferred {
39
    /// Each param's type: its pin, else the first dimension the trial fits;
40
    /// `None` where nothing pins it and no dimension fits or no verdict stands.
41
    pub types: Vec<Option<WasmType>>,
42
    /// The params no use pins and several dimensions fit or no verdict stands,
43
    /// so only a THE or a call decides them.
44
    pub ambiguous: Vec<bool>,
45
}
46

            
47
/// Each required param's user-visible `WasmType` pinned by `body`, under the
48
/// variables `symbols` holds where the lambda is created.
49
253098
pub(in crate::compiler) fn infer_params(
50
253098
    symbols: &SymbolTable,
51
253098
    params: &LambdaParams,
52
253098
    body: &Expr,
53
253098
) -> Inferred {
54
253098
    let scope = Scope::new(symbols, &params.required);
55
253098
    let scanned: Vec<_> = params
56
253098
        .required
57
253098
        .iter()
58
194044
        .map(|name| pinned_param_type(body, name, &scope))
59
        .collect();
60
253098
    let fits = trial::fitting_dimensions(symbols, (params, body), &scanned);
61
251310
    let dimensions = |index: usize| fits.as_ref().map(|fits| fits[index].as_slice());
62
253098
    let ambiguous = (0..scanned.len())
63
194044
        .map(|index| scanned[index].is_none() && dimensions(index).is_none_or(|d| d.len() > 1))
64
        .collect();
65
253098
    let types = (0..scanned.len())
66
194044
        .map(|index| scanned[index].or_else(|| dimensions(index)?.first().copied()))
67
        .collect();
68
253098
    Inferred { types, ambiguous }
69
253098
}
70

            
71
/// Whether the body pins parameter `index`'s type, outright or as the one dimension that fits.
72
265
pub(in crate::compiler) fn has_type_evidence(
73
265
    symbols: &SymbolTable,
74
265
    params: &LambdaParams,
75
265
    body: &Expr,
76
265
    index: usize,
77
265
) -> bool {
78
265
    let inferred = infer_params(symbols, params, body);
79
265
    inferred.types.get(index).is_some_and(Option::is_some) && !inferred.ambiguous[index]
80
265
}
81

            
82
/// The `WasmType` `name` is pinned to by a type-constraining use in `body`,
83
/// anywhere `name` still refers to the searched param (not inside a scope that
84
/// rebinds it). The pins:
85
/// - CDR of a `(cons CAR name)` → `PairRef(<car cell element>)` (list accumulator);
86
/// - argument to a string native (`string=`, `upcase-string`) → `StringRef`;
87
/// - operand beside a typed value or a literal in arithmetic or a comparison →
88
///   that operand's dimension, a typed value before a literal;
89
/// - argument of FUNCALL or of a call to a user function → the callee's
90
///   parameter type, a user macro use through its expansion.
91
///
92
/// `None` if no pinning use is found.
93
9244900
fn pinned_param_type(body: &Expr, name: &str, scope: &Scope) -> Option<WasmType> {
94
9244900
    with_sufficient_stack(|| scan_form(body, name, scope))
95
9244900
}
96

            
97
9244900
fn scan_form(body: &Expr, name: &str, scope: &Scope) -> Option<WasmType> {
98
9244900
    let Expr::List(elems) = body else {
99
4604739
        return None;
100
    };
101
4640161
    if let [Expr::Symbol(head), car, Expr::Symbol(cdr)] = elems.as_slice()
102
556185
        && head.eq_ignore_ascii_case("cons")
103
425
        && cdr == name
104
    {
105
213
        return Some(WasmType::PairRef(car_cell_element(car)));
106
4639948
    }
107
4639948
    if let [_, _, Expr::Symbol(subject)] = elems.as_slice()
108
555972
        && subject == name
109
542421
        && let Some(ty) = crate::compiler::native::the_result_type(elems)
110
    {
111
48
        return Some(ty);
112
4639900
    }
113
4639900
    if let Some(Expr::Symbol(head)) = elems.first()
114
4639483
        && is_string_native(head)
115
625
        && elems[1..]
116
625
            .iter()
117
625
            .any(|a| matches!(a, Expr::Symbol(s) if s == name))
118
    {
119
625
        return Some(WasmType::StringRef);
120
4639275
    }
121
4639275
    if let Some(ty) = neighbour_pin(elems, name, scope).or_else(|| funcall_pin(elems, name, scope))
122
    {
123
69012
        return Some(ty);
124
4570263
    }
125
4570263
    match head_upper(elems).as_deref() {
126
        // Quoted forms are data, not evaluated — a param mentioned inside must
127
        // not pin its type. (The `Expr::Quote`/`Expr::Quasiquote` AST variants
128
        // already return `None` above by not being a `List`; this guards the
129
        // `(quote …)` / `(quasiquote …)` list spellings.)
130
2
        Some("QUOTE") | Some("QUASIQUOTE") => None,
131
3447722
        Some("LET") => scan_let(elems, name, false, scope),
132
1
        Some("LET*") => scan_let(elems, name, true, scope),
133
3
        Some("DO") | Some("DO*") => scan_do(elems, name, scope),
134
2
        Some("DOLIST") => scan_dolist(elems, name, scope),
135
1671
        Some("LABELS") => scan_labels(elems, name, scope),
136
        Some("LAMBDA") => {
137
            // The body is shadowed iff `name` is one of the lambda's params; a
138
            // param list carries no scannable outer-scope subform.
139
470
            if lambda_binds(elems, name) {
140
24
                None
141
            } else {
142
446
                scan_each(tail(elems, 1), name, &scope.hiding(lambda_params(elems)))
143
            }
144
        }
145
1120392
        _ => scan_each(tail(elems, 1), name, scope),
146
    }
147
9244900
}
148

            
149
/// Operators whose operands share one dimension; a Commodity operand pins
150
/// only through the additive and comparison ones, since money times or over a
151
/// scalar is legal.
152
67241
fn pins_dimension(head: &str, ty: WasmType) -> bool {
153
67241
    let additive = ["+", "-", "<", ">", "<=", ">=", "=", "/="];
154
67241
    let multiplicative = ["*", "/", "mod"];
155
246498
    let among = |ops: &[&str]| ops.iter().any(|op| head.eq_ignore_ascii_case(op));
156
67241
    among(&additive) || (ty != WasmType::Commodity && among(&multiplicative))
157
67241
}
158

            
159
/// The parameter type of the closure `name` is handed to by FUNCALL.
160
4573185
fn funcall_pin(elems: &[Expr], name: &str, scope: &Scope) -> Option<WasmType> {
161
4573185
    let [Expr::Symbol(head), callee, args @ ..] = elems else {
162
3145
        return None;
163
    };
164
4570040
    if !head.eq_ignore_ascii_case("funcall") {
165
4032539
        return None;
166
537501
    }
167
537501
    let index = args
168
537501
        .iter()
169
537178
        .position(|arg| matches!(arg, Expr::Symbol(symbol) if symbol == name))?;
170
537077
    scope.callee_param(callee, name, index)
171
4573185
}
172

            
173
/// The dimension of a typed value standing beside `name` as an operand.
174
4639275
fn neighbour_pin(elems: &[Expr], name: &str, scope: &Scope) -> Option<WasmType> {
175
4639275
    let (Some(Expr::Symbol(head)), operands) = (elems.first(), tail(elems, 1)) else {
176
417
        return None;
177
    };
178
9898674
    let is_name = |operand: &Expr| matches!(operand, Expr::Symbol(s) if s == name);
179
4638858
    if !operands.iter().any(is_name) {
180
3991813
        return None;
181
647045
    }
182
647045
    let kinds: Vec<(WasmType, bool)> = operands
183
647045
        .iter()
184
1262560
        .filter(|operand| !is_name(operand))
185
615096
        .filter_map(|operand| {
186
615096
            let Some(scope::Bound::Kind(ty)) = scope.value_of(operand, name) else {
187
547855
                return None;
188
            };
189
67241
            Some((ty, matches!(operand, Expr::Number(_))))
190
615096
        })
191
67241
        .filter(|&(ty, _)| pins_dimension(head, ty))
192
        .collect();
193
647045
    let typed = kinds.iter().find(|(_, literal)| !literal);
194
647045
    typed.or(kinds.first()).map(|&(ty, _)| ty)
195
4639275
}
196

            
197
/// Natives that REQUIRE a `StringRef` argument, so a param passed to one is a
198
/// string. (Only these two exist today; extend alongside new string natives.)
199
4639483
fn is_string_native(head: &str) -> bool {
200
4639483
    matches!(
201
4639483
        head.to_ascii_uppercase().as_str(),
202
        "STRING=" | "UPCASE-STRING"
203
    )
204
4639483
}
205

            
206
/// The `PairElement` a car expression contributes. Literal cars pin their slot;
207
/// a variable / sibling-param / captured / computed car has no statically-known cell type,
208
/// so it widens to `AnyRef` — keeping the cdr param's pair element consistent
209
/// with whatever `compile_cons_to_stack` actually produces for that car.
210
220
fn car_cell_element(car: &Expr) -> PairElement {
211
220
    if matches!(car, Expr::Symbol(_)) {
212
210
        return PairElement::AnyRef;
213
10
    }
214
10
    crate::compiler::native::literal_pair_element(car).unwrap_or(PairElement::AnyRef)
215
220
}
216

            
217
4570263
fn head_upper(elems: &[Expr]) -> Option<String> {
218
4570263
    match elems.first() {
219
4569846
        Some(Expr::Symbol(s)) => Some(s.to_ascii_uppercase()),
220
417
        _ => None,
221
    }
222
4570263
}
223

            
224
4570025
fn scan_each(forms: &[Expr], name: &str, scope: &Scope) -> Option<WasmType> {
225
5117390
    forms.iter().find_map(|e| pinned_param_type(e, name, scope))
226
4570025
}
227

            
228
/// `forms[from..]`, but never panics on a malformed/short form: a list with
229
/// fewer than `from` elements (e.g. a bare `()`, `(let)`, `(do)`) yields an
230
/// empty slice rather than an out-of-range slice index. Param-type inference is
231
/// a best-effort hint, so a too-short form simply contributes no pin; the
232
/// malformed form is rejected (or compiled) by the real path later.
233
9209300
fn tail(forms: &[Expr], from: usize) -> &[Expr] {
234
9209300
    forms.get(from..).unwrap_or(&[])
235
9209300
}
236

            
237
/// `(let ((v init)…) body…)` / `(let* …)`. Binding INITs are in the outer scope
238
/// (for LET* up to the binding that introduces `name`); the body is shadowed
239
/// once any binding (re)binds `name`.
240
3447723
fn scan_let(elems: &[Expr], name: &str, sequential: bool, scope: &Scope) -> Option<WasmType> {
241
3447723
    let mut shadowed = false;
242
3447723
    let mut inner = scope.clone();
243
3447723
    if let Some(Expr::List(bindings)) = elems.get(1) {
244
3447721
        for binding in bindings {
245
3447729
            let Expr::List(parts) = binding else { continue };
246
3447729
            let init_scope = if sequential { &inner } else { scope };
247
3447729
            if !(sequential && shadowed)
248
3447729
                && let Some(init) = parts.get(1)
249
3447729
                && let Some(ty) = pinned_param_type(init, name, init_scope)
250
            {
251
209
                return Some(ty);
252
3447520
            }
253
3447520
            if let Some(Expr::Symbol(var)) = parts.first() {
254
3447520
                shadowed |= var == name;
255
3447520
                let value = parts
256
3447520
                    .get(1)
257
3447520
                    .and_then(|init| init_scope.value_of(init, name));
258
3447520
                inner = inner.binding(var, value);
259
            }
260
        }
261
2
    }
262
3447514
    if shadowed {
263
2
        return None;
264
3447512
    }
265
3447512
    scan_each(tail(elems, 2), name, &inner)
266
3447723
}
267

            
268
/// `(labels ((g (params…) body…)…) form…)`: only the forms use the outer parameter.
269
1671
fn scan_labels(elems: &[Expr], name: &str, scope: &Scope) -> Option<WasmType> {
270
1671
    scan_each(tail(elems, 2), name, scope)
271
1671
}
272

            
273
/// `(do ((v init step)…) (end res…) body…)`. Inits are outer scope; steps, the
274
/// end clause, and the body see the loop vars, so they're shadowed once any var
275
/// is `name`.
276
3
fn scan_do(elems: &[Expr], name: &str, scope: &Scope) -> Option<WasmType> {
277
3
    let mut shadowed = false;
278
3
    let mut bound = Vec::new();
279
3
    if let Some(Expr::List(vars)) = elems.get(1) {
280
        for var in vars {
281
            let Expr::List(parts) = var else { continue };
282
            if let Some(init) = parts.get(1)
283
                && let Some(ty) = pinned_param_type(init, name, scope)
284
            {
285
                return Some(ty);
286
            }
287
            if let Some(Expr::Symbol(var)) = parts.first() {
288
                shadowed |= var == name;
289
                bound.push(var.as_str());
290
            }
291
        }
292
3
    }
293
3
    if shadowed {
294
        None
295
    } else {
296
3
        scan_each(tail(elems, 2), name, &scope.hiding(bound))
297
    }
298
3
}
299

            
300
/// `(dolist (var list-expr [result]) body…)`. The list-expr is outer scope; the
301
/// result form and body see the loop var.
302
2
fn scan_dolist(elems: &[Expr], name: &str, scope: &Scope) -> Option<WasmType> {
303
2
    let Some(Expr::List(spec)) = elems.get(1) else {
304
1
        return scan_each(tail(elems, 1), name, scope);
305
    };
306
1
    if let Some(list_expr) = spec.get(1)
307
1
        && let Some(ty) = pinned_param_type(list_expr, name, scope)
308
    {
309
1
        return Some(ty);
310
    }
311
    let Some(Expr::Symbol(var)) = spec.first() else {
312
        return scan_each(tail(elems, 2), name, scope);
313
    };
314
    if var == name {
315
        None
316
    } else {
317
        scan_each(tail(elems, 2), name, &scope.hiding([var.as_str()]))
318
    }
319
2
}
320

            
321
/// The symbols of a `(lambda (params…) …)` parameter list.
322
916
fn lambda_params(elems: &[Expr]) -> impl Iterator<Item = &str> {
323
916
    let params = match elems.get(1) {
324
908
        Some(Expr::List(params)) => params.as_slice(),
325
8
        _ => &[],
326
    };
327
916
    params.iter().filter_map(|p| match p {
328
914
        Expr::Symbol(s) => Some(s.as_str()),
329
        _ => None,
330
914
    })
331
916
}
332

            
333
470
fn lambda_binds(elems: &[Expr], name: &str) -> bool {
334
472
    lambda_params(elems).any(|param| param == name)
335
470
}
336

            
337
#[cfg(test)]
338
mod tests;