1
//! Runtime-type inference for the let-body's tail value: a setf walk that reads
2
//! an accumulator's cons car so the promoted type matches codegen.
3

            
4
use crate::ast::{Expr, PairElement, WasmType};
5
use crate::compiler::expr::{classify_stack_type, eval_value, list_datum_members, quoted_datum};
6
use crate::compiler::join::Arm;
7
use crate::compiler::native::literal_pair_element;
8
use crate::compiler::special::lambda::compute_captures;
9
use crate::error::{Error, Result};
10
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable, with_sufficient_stack};
11

            
12
use super::super::iteration::sizing::{infer_wasm_type, var_type_hint};
13
use super::super::iteration::unrolled_inits;
14
use super::super::setf_scan::{assigns, binder_rebinds, join, setf_rhs_of, step_pair_element};
15
use super::let_bind::home_type;
16
use super::let_eval::as_binding_datum;
17
use super::shared::assigned_scope;
18

            
19
/// `elems[from..]`, never panicking on a malformed/short binder form: a `(do)`
20
/// / `(dolist)` / `(let)` with fewer than `from` elements yields an empty slice
21
/// rather than an out-of-range slice index. This walk is a best-effort
22
/// accumulator-type inference hint, so a too-short form simply has no body to
23
/// scan; the malformed form is rejected by the real binding-compile path later.
24
284034
fn tail(elems: &[Expr], from: usize) -> &[Expr] {
25
284034
    elems.get(from..).unwrap_or(&[])
26
284034
}
27

            
28
96704
pub(super) fn infer_runtime_type(expr: &Expr) -> WasmType {
29
    // Bytes share StringRef's `i8_array` representation but aren't a
30
    // `compile_for_stack` literal, so they're classified here, not in the
31
    // shared `classify_stack_type`.
32
96704
    if let Expr::Bytes(_) = expr {
33
        return WasmType::StringRef;
34
96704
    }
35
    // A closure's type needs its interned signature, which only codegen has.
36
96704
    if let Expr::Lambda(..) = expr {
37
1484
        return WasmType::AnyRef;
38
95220
    }
39
95220
    match crate::compiler::expr::classify_stack_type(expr) {
40
95220
        Some(ty) => ty,
41
        // For any remaining shape (List, Symbol, Quote, etc.) fall
42
        // back to a generic PairRef. PairElement::I32 is the
43
        // least-restrictive guess; downstream consumers refuse it
44
        // explicitly when wrong, so a disagreement surfaces as a
45
        // compile error rather than a runtime trap.
46
        None => WasmType::PairRef(PairElement::I32),
47
    }
48
96704
}
49

            
50
/// Runtime local type for a let-var the body assigns, `None` if never assigned.
51
/// A const-initialized accumulator must become a real wasm local, else its
52
/// `setf` is lost across loop scopes.
53
2951405
pub(super) fn assigned_var_runtime_type(
54
2951405
    body: &[Expr],
55
2951405
    name: &str,
56
2951405
    init_val: &Expr,
57
2951405
    symbols: &SymbolTable,
58
2951405
) -> Result<Option<WasmType>> {
59
2951405
    let Some(body) = &assigned_scope(symbols, name, body)? else {
60
2689188
        return Ok(None);
61
    };
62
262217
    let mut env = symbols.clone();
63
262217
    if let Some(elem) = walk_for_setf_pair_element(body, name, init_val, &mut env) {
64
206286
        return Ok(Some(WasmType::PairRef(elem)));
65
55931
    }
66
    // Size from the first setf rhs with a runtime type (a nil init would
67
    // otherwise give `Bool`), resolved on a clone with the depth-guarded
68
    // inliner; else the init's type. A conflicting later store is codegen's.
69
55931
    for rhs in setf_rhs_of(body, name) {
70
55931
        match eval_value(&mut env.clone(), rhs) {
71
            Ok(value) => {
72
14032
                if let Some(ty) = value.wasm_type().or_else(|| stored_type(&value)) {
73
13818
                    return Ok(Some(ty));
74
214
                }
75
            }
76
21
            Err(err @ Error::Dimension(_)) => return Err(err),
77
41878
            Err(_) => {}
78
        }
79
    }
80
42092
    Ok(Some(infer_runtime_type(init_val)))
81
2951405
}
82

            
83
/// The scope a nil accumulator of a LET is sized in: its siblings' values,
84
/// on the table the inits ran in, are visible to the stores that build it.
85
4236384
pub(super) fn sibling_scope(
86
4236384
    outer: &SymbolTable,
87
4236384
    bindings: &[(String, Option<Expr>)],
88
4236384
    values: impl IntoIterator<Item = Expr>,
89
4236384
) -> Option<SymbolTable> {
90
265797
    let nil_init = |init: &Option<Expr>| matches!(init, None | Some(Expr::Nil));
91
4236384
    if bindings.len() < 2 || !bindings.iter().any(|(_, init)| nil_init(init)) {
92
4112989
        return None;
93
123395
    }
94
123395
    let mut scope = outer.clone();
95
123395
    for ((name, _), value) in bindings.iter().zip(values) {
96
246790
        let value = reads_outer_bindings(outer, bindings, value);
97
246790
        scope.define(Symbol::new(name, SymbolKind::Variable).with_value(value));
98
    }
99
123395
    Some(scope)
100
4236384
}
101

            
102
/// A sibling lambda's body reads the LET's outer bindings, not its siblings.
103
246790
fn reads_outer_bindings(
104
246790
    outer: &SymbolTable,
105
246790
    bindings: &[(String, Option<Expr>)],
106
246790
    value: Expr,
107
246790
) -> Expr {
108
246790
    let Expr::Lambda(params, body) = value else {
109
245539
        return value;
110
    };
111
1251
    let Ok(captures) = compute_captures(outer, &params, &body) else {
112
        return Expr::Lambda(params, body);
113
    };
114
1251
    let rebound: Vec<Expr> = bindings
115
1251
        .iter()
116
2502
        .filter(|(name, _)| captures.reads(name))
117
416
        .filter_map(|(name, _)| {
118
416
            let outer_value = outer.lookup(name)?.value()?.clone();
119
416
            Some(Expr::List(vec![Expr::Symbol(name.clone()), outer_value]))
120
416
        })
121
        .collect();
122
1251
    if rebound.is_empty() {
123
835
        return Expr::Lambda(params, body);
124
416
    }
125
416
    let wrapped = Expr::List(vec![Expr::symbol("LET"), Expr::List(rebound), *body]);
126
416
    Expr::Lambda(params, Box::new(wrapped))
127
246790
}
128

            
129
/// The type a store of the datum `value` sizes a nil-initialised local to: the
130
/// datum's own, as codegen pushes it; a stored `nil` sizes nothing.
131
9178
fn stored_type(value: &Expr) -> Option<WasmType> {
132
9178
    classify_stack_type(value).filter(|_| *value != Expr::Nil)
133
9178
}
134

            
135
/// A let-var the body mutates is a runtime local in codegen even when its init
136
/// is a constant, so eval types it as one. With a hint the binder holds the
137
/// join of its init and the hint, as codegen's `home_type` allocates it.
138
///
139
/// Skipped while `symbols.is_macro_expansion()`: a macro's private body is
140
/// never codegen'd, and promoting would block the compile-time arithmetic it
141
/// uses to build its expansion.
142
3587356
pub(super) fn promote_assigned_binding(
143
3587356
    body: &[Expr],
144
3587356
    name: &str,
145
3587356
    val: Expr,
146
3587356
    key: &Option<HomeKey>,
147
3587356
    symbols: &SymbolTable,
148
3587356
) -> Result<Expr> {
149
3587356
    if symbols.is_macro_expansion() || matches!(val, Expr::Lambda(_, _)) {
150
500380
        return Ok(val);
151
3086976
    }
152
3086976
    if let Some(hint) = key.as_ref().and_then(|key| symbols.hint(key)) {
153
6969
        return Ok(hinted_binding(val, hint));
154
3080007
    }
155
3080007
    if val.is_wasm_runtime() {
156
177876
        return Ok(val);
157
2902131
    }
158
    Ok(
159
2902131
        match assigned_var_runtime_type(body, name, &val, symbols)? {
160
212943
            Some(ty) if key.is_some() && val == Expr::Nil => {
161
164488
                Expr::WasmRuntime(home_type(Arm::Nil, Some(ty)))
162
            }
163
48455
            Some(ty) => Expr::WasmRuntime(ty),
164
2689188
            None => val,
165
        },
166
    )
167
3587356
}
168

            
169
6969
fn hinted_binding(val: Expr, hint: WasmType) -> Expr {
170
6969
    let Some(ty) = classify_stack_type(&val).filter(|_| val.is_wasm_runtime()) else {
171
5070
        return Expr::WasmRuntime(hint);
172
    };
173
1899
    match home_type(Arm::Value(ty), Some(hint)) {
174
1899
        joined if joined == ty => val,
175
1899
        joined => Expr::WasmRuntime(joined),
176
    }
177
6969
}
178

            
179
/// The type of a tail Symbol fed by a `(setf <name> (cons V <name>))`
180
/// accumulator: the cons car's PairElement, with dolist/do loop variables
181
/// resolved on the way.
182
54603
pub(in crate::compiler::special) fn infer_runtime_type_with_body(
183
54603
    val: &Expr,
184
54603
    result_expr: &Expr,
185
54603
    body: &[Expr],
186
54603
    symbols: &SymbolTable,
187
54603
) -> WasmType {
188
54603
    if let Expr::Symbol(name) = result_expr {
189
2747
        let mut env = symbols.clone();
190
2747
        if let Some(elem) = walk_for_setf_pair_element(body, name, val, &mut env) {
191
            return WasmType::PairRef(elem);
192
2747
        }
193
51856
    }
194
54603
    infer_runtime_type(val)
195
54603
}
196

            
197
/// Walks `body` for `(setf <name> <rhs>)` and infers the matching
198
/// PairElement from the cons car of the rhs. Tracks DOLIST/DO/LET
199
/// loop-var bindings into `env` so nested setfs resolve their car
200
/// symbol against the right type.
201
264964
fn walk_for_setf_pair_element(
202
264964
    body: &[Expr],
203
264964
    target: &str,
204
264964
    init: &Expr,
205
264964
    env: &mut SymbolTable,
206
264964
) -> Option<PairElement> {
207
264964
    if matches!(init, Expr::Nil) {
208
213761
        env.define(
209
213761
            Symbol::new(target, SymbolKind::Variable)
210
213761
                .with_value(Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef))),
211
213761
        );
212
51203
    }
213
264964
    let mut joined = None;
214
264964
    for form in body {
215
463934
        walk_form(form, target, env, &mut joined);
216
    }
217
264964
    joined
218
264964
}
219

            
220
3564745
fn walk_form(form: &Expr, target: &str, env: &mut SymbolTable, out: &mut Option<PairElement>) {
221
3564745
    with_sufficient_stack(|| {
222
3564745
        let Expr::List(elems) = form else {
223
2291929
            return;
224
        };
225
        // A binder that rebinds `target` shadows it: any `(setf target …)` inside
226
        // refers to the inner variable, not the accumulator we're typing.
227
1272816
        if binder_rebinds(elems, target) {
228
7
            return;
229
1272809
        }
230
1272809
        let head = elems.first().and_then(|e| match e {
231
1272737
            Expr::Symbol(s) => Some(s.as_str()),
232
72
            _ => None,
233
1272809
        });
234
1272809
        let children = match head {
235
            Some("SETF") => {
236
266317
                fold_setf_stores(&elems[1..], target, env, out);
237
266317
                &elems[1..]
238
            }
239
            Some("DOLIST") => {
240
43587
                bind_dolist_var(elems, env);
241
43587
                tail(elems, 2)
242
            }
243
            Some("DO") | Some("DO*") => {
244
65619
                bind_do_vars(elems, head.unwrap_or_default(), env);
245
65619
                tail(elems, 3)
246
            }
247
            Some("LET") | Some("LET*") => {
248
444
                bind_let_vars(elems, env);
249
444
                tail(elems, 2)
250
            }
251
896842
            _ => elems,
252
        };
253
1272809
        for e in children {
254
3100811
            walk_form(e, target, env, out);
255
        }
256
3564745
    })
257
3564745
}
258

            
259
/// Joins the element built by every `(setf target rhs)` pair into `out`, so a
260
/// local stored with differing elements is sized to the widest, as codegen builds it.
261
266317
fn fold_setf_stores(
262
266317
    pairs: &[Expr],
263
266317
    target: &str,
264
266317
    env: &SymbolTable,
265
266317
    out: &mut Option<PairElement>,
266
266317
) {
267
266317
    for pair in pairs.chunks(2) {
268
266317
        if let Some(Expr::Symbol(var)) = pair.first()
269
266317
            && var == target
270
265434
            && let Some(rhs) = pair.get(1)
271
        {
272
265434
            *out = join([*out, step_pair_element(rhs, env)].into_iter());
273
883
        }
274
    }
275
266317
}
276

            
277
444
fn bind_let_vars(elems: &[Expr], env: &mut SymbolTable) {
278
444
    let Some(Expr::List(bindings)) = elems.get(1) else {
279
        return;
280
    };
281
444
    for b in bindings {
282
444
        if let Expr::List(parts) = b
283
444
            && let Some(Expr::Symbol(bname)) = parts.first()
284
        {
285
444
            let init_val = match parts.get(1) {
286
                Some(init) => {
287
444
                    let mut probe = env.clone();
288
444
                    eval_value(&mut probe, init).unwrap_or(Expr::Nil)
289
                }
290
                None => Expr::Nil,
291
            };
292
444
            env.define(Symbol::new(bname, SymbolKind::Variable).with_value(init_val));
293
        }
294
    }
295
444
}
296

            
297
/// Binds a DOLIST variable as codegen does: the list's datum when it is a
298
/// constant list the body does not store into, else a runtime element.
299
43587
fn bind_dolist_var(elems: &[Expr], env: &mut SymbolTable) {
300
43587
    let Some(Expr::List(spec)) = elems.get(1) else {
301
        return;
302
    };
303
43587
    let (Some(Expr::Symbol(var)), Some(list_expr)) = (spec.first(), spec.get(1)) else {
304
        return;
305
    };
306
43587
    let Ok(list_val) = eval_value(&mut env.clone(), list_expr) else {
307
        return;
308
    };
309
43587
    let Some(WasmType::PairRef(elem)) = classify_stack_type(&list_val) else {
310
        return;
311
    };
312
43587
    let value = literal_representative(&list_val, elem, tail(elems, 2), var)
313
43587
        .map_or(Expr::WasmRuntime(elem.as_wasm_type()), as_binding_datum);
314
43587
    env.define(Symbol::new(var, SymbolKind::Variable).with_value(value));
315
43587
}
316

            
317
/// The first member of a constant list whose members all ride `elem` cells.
318
43587
fn literal_representative(
319
43587
    list_val: &Expr,
320
43587
    elem: PairElement,
321
43587
    body: &[Expr],
322
43587
    var: &str,
323
43587
) -> Option<Expr> {
324
43587
    if assigns(body, var) {
325
636
        return None;
326
42951
    }
327
42951
    let members = list_datum_members(quoted_datum(list_val).unwrap_or(list_val))?;
328
4525
    let first = members.first()?;
329
4525
    members
330
4525
        .iter()
331
84446
        .all(|m| literal_pair_element(m) == Some(elem))
332
4310
        .then(|| first.clone())
333
43587
}
334

            
335
/// Binds the variables of a DO / DO* form as codegen does: the iteration's
336
/// datum for a loop P11 unrolls, a runtime value of the init's type otherwise.
337
65619
fn bind_do_vars(elems: &[Expr], head: &str, env: &mut SymbolTable) {
338
65619
    let Some(Expr::List(vars)) = elems.get(1) else {
339
        return;
340
    };
341
65619
    let unrolled = unrolled_inits(&mut env.clone(), head, tail(elems, 1))
342
65619
        .ok()
343
65619
        .flatten();
344
65619
    for (at, spec) in vars.iter().enumerate() {
345
65619
        let Expr::List(parts) = spec else {
346
            continue;
347
        };
348
65619
        let Some(Expr::Symbol(name)) = parts.first() else {
349
            continue;
350
        };
351
65619
        let value = match unrolled.as_ref().and_then(|inits| inits.get(at)) {
352
441
            Some(init) => as_binding_datum(init.clone()),
353
            None => {
354
65178
                let Some(Ok(init_val)) = parts.get(1).map(|i| eval_value(&mut env.clone(), i))
355
                else {
356
                    continue;
357
                };
358
65178
                let hint = var_type_hint(parts.get(2), tail(elems, 3), name);
359
65178
                Expr::WasmRuntime(infer_wasm_type(&init_val, hint, env).unwrap_or(WasmType::AnyRef))
360
            }
361
        };
362
65619
        env.define(Symbol::new(name, SymbolKind::Variable).with_value(value));
363
    }
364
65619
}