1
//! The names a parameter scan sees: the enclosing scope's variables, minus the
2
//! names the lambda's own parameters and inner binders hide.
3

            
4
use super::pinned_param_type;
5
use crate::ast::{ClosureSigId, Expr, LambdaParams, WasmType};
6
use crate::compiler::expr::{classify_stack_type, probe_value};
7
use crate::compiler::special::binding::parse_param_list;
8
use crate::compiler::special::binding::shared::mentions;
9
use crate::error::Result;
10
use crate::runtime::{SymbolTable, with_sufficient_stack};
11

            
12
/// What an inner binder binds a name to, as far as the scan can tell.
13
#[derive(Clone)]
14
pub(super) enum Bound {
15
    Kind(WasmType),
16
    /// A lambda: the pins of its parameters.
17
    Closure(Vec<Option<WasmType>>),
18
}
19

            
20
#[derive(Clone)]
21
pub(super) struct Scope<'a> {
22
    symbols: &'a SymbolTable,
23
    hidden: Vec<String>,
24
    bound: Vec<(String, Bound)>,
25
}
26

            
27
538809
fn numeric(ty: WasmType) -> Option<WasmType> {
28
538809
    matches!(ty, WasmType::I32 | WasmType::Ratio | WasmType::Commodity).then_some(ty)
29
538809
}
30

            
31
impl<'a> Scope<'a> {
32
253168
    pub(super) fn new(symbols: &'a SymbolTable, hidden: &[String]) -> Self {
33
253168
        Self {
34
253168
            symbols,
35
253168
            hidden: hidden.to_vec(),
36
253168
            bound: Vec::new(),
37
253168
        }
38
253168
    }
39

            
40
3933638
    pub(super) fn hiding<'n>(&self, names: impl IntoIterator<Item = &'n str>) -> Self {
41
3933638
        let mut scope = self.clone();
42
3933638
        for name in names {
43
3933628
            scope.hidden.push(name.to_string());
44
19508064
            scope.bound.retain(|(bound, _)| bound != name);
45
        }
46
3933638
        scope
47
3933638
    }
48

            
49
    /// The scope inside a binder of `name` to `value`, when the scan knows what it is.
50
3447520
    pub(super) fn binding(&self, name: &str, value: Option<Bound>) -> Self {
51
3447520
        let mut scope = self.hiding([name]);
52
3447520
        scope
53
3447520
            .bound
54
3447520
            .extend(value.map(|value| (name.to_string(), value)));
55
3447520
        scope
56
3447520
    }
57

            
58
    /// What `form` denotes: a variable's binding, a lambda, a closure or a numeric value.
59
4599693
    pub(super) fn value_of(&self, form: &Expr, name: &str) -> Option<Bound> {
60
4599693
        match form {
61
1617873
            Expr::Symbol(variable) if variable == name => None,
62
1617242
            Expr::Symbol(variable) => self.variable(variable),
63
2438197
            Expr::Number(_) => classify_stack_type(form).map(Bound::Kind),
64
            Expr::Lambda(..) | Expr::List(_) => {
65
539399
                if let Some(pins) = self.closure_pins(form, name) {
66
485669
                    return Some(Bound::Closure(pins));
67
53730
                }
68
53730
                match self.result_type(form, name)? {
69
835
                    WasmType::Closure(sig) => self.recorded(sig),
70
3333
                    ty => numeric(ty).map(Bound::Kind),
71
                }
72
            }
73
4224
            _ => None,
74
        }
75
4599693
    }
76

            
77
    /// The parameter pins of the lambda `init` denotes: a lambda form, or what
78
    /// a call not mentioning `name` returns.
79
1024648
    fn closure_pins(&self, init: &Expr, name: &str) -> Option<Vec<Option<WasmType>>> {
80
1024648
        if let Some(params) = self.lambda_form(init) {
81
485669
            let (params, body) = params;
82
485669
            let inner = self.hiding(params.required.iter().map(String::as_str));
83
            return Some(
84
485669
                params
85
485669
                    .required
86
485669
                    .iter()
87
485666
                    .map(|param| pinned_param_type(&body, param, &inner))
88
                    .collect(),
89
            );
90
538979
        }
91
538979
        if matches!(init, Expr::Symbol(_)) || mentions(init, name) {
92
859
            return None;
93
538120
        }
94
538120
        self.deeper(|scratch| {
95
536032
            let Ok(probed) = with_sufficient_stack(|| probe_value(scratch, init)) else {
96
46196
                return Ok(None);
97
            };
98
489836
            let scope = Scope {
99
489836
                symbols: scratch,
100
489836
                ..self.clone()
101
489836
            };
102
489836
            Ok(scope
103
489836
                .lambda_form(&probed)
104
485249
                .and_then(|_| scope.closure_pins(&probed, name)))
105
536032
        })
106
1024648
    }
107

            
108
    /// `run` on a scratch table one level deeper in the shared recursion budget.
109
538120
    fn deeper<T>(&self, run: impl FnOnce(&mut SymbolTable) -> Result<Option<T>>) -> Option<T> {
110
538120
        self.symbols
111
538120
            .clone()
112
538120
            .within_shared_recursion(run)
113
538120
            .ok()
114
538120
            .flatten()
115
538120
    }
116

            
117
1514484
    fn lambda_form(&self, form: &Expr) -> Option<(LambdaParams, Expr)> {
118
1514484
        match form {
119
970914
            Expr::Lambda(params, body) => Some((params.clone(), body.as_ref().clone())),
120
538983
            Expr::List(elems) => match elems.as_slice() {
121
534419
                [Expr::Symbol(head), names, body @ ..] if head.eq_ignore_ascii_case("LAMBDA") => {
122
4
                    let required = parse_param_list(self.symbols, "LAMBDA", names).ok()?;
123
4
                    Some((LambdaParams::simple(required), Expr::body(body)))
124
                }
125
538979
                _ => None,
126
            },
127
4587
            _ => None,
128
        }
129
1514484
    }
130

            
131
1617242
    fn bound(&self, name: &str) -> Option<&Bound> {
132
3566673
        let (_, value) = self.bound.iter().rev().find(|(bound, _)| bound == name)?;
133
972413
        Some(value)
134
1617242
    }
135

            
136
644829
    fn is_hidden(&self, name: &str) -> bool {
137
31493065
        self.hidden.iter().any(|hidden| hidden == name)
138
644829
    }
139

            
140
    /// The type the closure `callee` takes as its argument number `index`.
141
537077
    pub(super) fn callee_param(&self, callee: &Expr, name: &str, index: usize) -> Option<WasmType> {
142
537077
        match self.value_of(callee, name)? {
143
486293
            Bound::Closure(pins) => pins.get(index).copied().flatten(),
144
            Bound::Kind(_) => None,
145
        }
146
537077
    }
147

            
148
2923
    fn recorded(&self, sig: ClosureSigId) -> Option<Bound> {
149
2923
        let params = self.symbols.closure_params(sig)?;
150
2923
        Some(Bound::Closure(params.iter().map(|&ty| Some(ty)).collect()))
151
2923
    }
152

            
153
    /// What the variable `name` is bound to: by an inner binder, or in the enclosing scope.
154
1617242
    fn variable(&self, name: &str) -> Option<Bound> {
155
1617242
        if let Some(bound) = self.bound(name) {
156
972413
            return Some(bound.clone());
157
644829
        }
158
644829
        if self.is_hidden(name) {
159
107263
            return None;
160
537566
        }
161
537566
        let value = self.symbols.lookup(name)?.value()?;
162
537564
        if let Some((_, WasmType::Closure(sig))) = value.place() {
163
2088
            return self.recorded(sig);
164
535476
        }
165
535476
        classify_stack_type(value)
166
535476
            .and_then(numeric)
167
535476
            .map(Bound::Kind)
168
1617242
    }
169

            
170
    /// The type `form` evaluates to, when it mentions neither `name` nor a hidden name.
171
53730
    fn result_type(&self, form: &Expr, name: &str) -> Option<WasmType> {
172
103022
        if mentions(form, name) || self.hidden.iter().any(|hidden| mentions(form, hidden)) {
173
49465
            return None;
174
4265
        }
175
4265
        let probed = with_sufficient_stack(|| probe_value(&mut self.symbols.clone(), form));
176
4265
        classify_stack_type(&probed.ok()?)
177
53730
    }
178
}