1
//! A closure factory: a function whose body is a lambda reading the
2
//! function's own parameters. The lambda outlives the inlined frame that binds
3
//! them, so each parameter it reads is rebound to a hidden variable of the
4
//! caller's scope, which the ordinary closure capture then picks up.
5

            
6
use crate::ast::{Expr, LambdaParams, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::special::{
10
    MacroStores, macro_stores, mentions_expanded, param_names, reads_free, unescaped,
11
};
12
use crate::error::{Error, Result};
13
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable};
14

            
15
use super::eval::eval_value;
16
use super::lambda_params::compile_and_bind_lambda_params;
17

            
18
/// The lambda `call` returns, closed over the call's argument values, which are
19
/// bound (their effects emitted) in `symbols`.
20
51386
pub(in crate::compiler) fn close_factory_call(
21
51386
    ctx: &mut CompileContext,
22
51386
    emit: &mut FunctionEmitter,
23
51386
    symbols: &mut SymbolTable,
24
51386
    call: &Expr,
25
51386
) -> Result<Expr> {
26
51386
    let Expr::List(items) = call else {
27
1
        return Err(not_a_factory());
28
    };
29
51385
    let [Expr::Symbol(name), args @ ..] = items.as_slice() else {
30
1
        return Err(not_a_factory());
31
    };
32
51384
    let Head::Function(params, body) = symbols.resolve_head(name) else {
33
1
        return Err(not_a_factory());
34
    };
35
51383
    let (params, body) = (params.clone(), body.clone());
36
    let Some(mut frame) =
37
51383
        compile_and_bind_lambda_params(ctx, emit, symbols, &params, &body, args, Some(name))?
38
    else {
39
        return Err(not_a_factory());
40
    };
41
51382
    let lambda = eval_value(&mut frame, &body)?;
42
51382
    match lambda {
43
51382
        Expr::Lambda(..) => close_over_params(symbols, &frame, (name, &params), lambda),
44
        _ => Err(not_a_factory()),
45
    }
46
51386
}
47

            
48
/// `value`, when it is a lambda reading parameters of `params` free, with each
49
/// of them rebound to a hidden variable of `symbols` holding its value in
50
/// `frame`.
51
2241727
pub(in crate::compiler) fn close_over_params(
52
2241727
    symbols: &mut SymbolTable,
53
2241727
    frame: &SymbolTable,
54
2241727
    (factory, params): (&str, &LambdaParams),
55
2241727
    value: Expr,
56
2241727
) -> Result<Expr> {
57
2241727
    let Expr::Lambda(lambda_params, lambda_body) = &value else {
58
1209177
        let names: Vec<String> = param_names(params).map(str::to_string).collect();
59
1209177
        return Ok(unescaped(frame, &names, value));
60
    };
61
1032550
    let mut bindings = Vec::new();
62
1032550
    for name in param_names(params) {
63
1022738
        if defaults_read(symbols, lambda_params, name)? {
64
29
            return Err(Error::Compile(format!(
65
29
                "a parameter default of the lambda a function returns reads the \
66
29
                 captured parameter {name}; read it in the body instead"
67
29
            )));
68
1022709
        }
69
1022709
        if reads_free(symbols, &value, name)? {
70
1021047
            match macro_stores(symbols, lambda_body, name)? {
71
1021002
                MacroStores::Clean => {}
72
                MacroStores::Assigns => {
73
44
                    return Err(Error::Compile(format!(
74
44
                        "the lambda a function returns assigns its parameter {name}; \
75
44
                         a captured parameter is read-only"
76
44
                    )));
77
                }
78
                MacroStores::Unexpanded(head) => {
79
1
                    return Err(Error::Compile(format!(
80
1
                        "the lambda a function returns uses the macro {head}, \
81
1
                         which could not be expanded here"
82
1
                    )));
83
                }
84
            }
85
1021002
            let hidden = symbols.hidden_name(factory, name);
86
1021002
            let mut variable = Symbol::new(&hidden, SymbolKind::Variable);
87
1021002
            if let Some(held) = frame.lookup(name).and_then(Symbol::value) {
88
1021002
                variable = variable.with_value(held.clone());
89
            }
90
1021002
            symbols.define(variable);
91
1021002
            bindings.push(Expr::List(vec![Expr::symbol(name), Expr::symbol(&hidden)]));
92
1662
        }
93
    }
94
1032476
    if bindings.is_empty() {
95
11485
        return Ok(value);
96
1020991
    }
97
1020991
    let scope = [
98
1020991
        Expr::symbol("LET"),
99
1020991
        Expr::List(bindings),
100
1020991
        lambda_body.as_ref().clone(),
101
1020991
    ];
102
1020991
    Ok(Expr::Lambda(
103
1020991
        lambda_params.clone(),
104
1020991
        Box::new(Expr::List(scope.into())),
105
1020991
    ))
106
2241727
}
107

            
108
/// Whether a default of `params` reads `name` from outside the lambda: a
109
/// default sees only the parameters bound before it.
110
1022738
fn defaults_read(symbols: &SymbolTable, params: &LambdaParams, name: &str) -> Result<bool> {
111
1022738
    let mut bound: Vec<&str> = params.required.iter().map(String::as_str).collect();
112
1022738
    let optional = params
113
1022738
        .optional
114
1022738
        .iter()
115
247
        .map(|(n, d)| (n.as_str(), d.as_ref()));
116
1022738
    if group_reads(symbols, optional, name, &mut bound)? {
117
21
        return Ok(true);
118
1022717
    }
119
1022717
    bound.extend(params.rest.as_deref());
120
1022717
    let key = params
121
1022717
        .key
122
1022717
        .iter()
123
4
        .map(|p| (p.name.as_str(), p.default.as_ref()));
124
1022717
    if group_reads(symbols, key, name, &mut bound)? {
125
4
        return Ok(true);
126
1022713
    }
127
1022713
    let aux = params.aux.iter().map(|(n, d)| (n.as_str(), d.as_ref()));
128
1022713
    group_reads(symbols, aux, name, &mut bound)
129
1022738
}
130

            
131
3068168
fn group_reads<'a>(
132
3068168
    symbols: &SymbolTable,
133
3068168
    group: impl Iterator<Item = (&'a str, Option<&'a Expr>)>,
134
3068168
    name: &str,
135
3068168
    bound: &mut Vec<&'a str>,
136
3068168
) -> Result<bool> {
137
3068168
    for (param, default) in group {
138
255
        if let Some(default) = default
139
255
            && !bound.contains(&name)
140
255
            && mentions_expanded(symbols, default, name)?
141
        {
142
29
            return Ok(true);
143
226
        }
144
226
        bound.push(param);
145
    }
146
3068139
    Ok(false)
147
3068168
}
148

            
149
/// The hidden variables a closed lambda's capture scope rebinds.
150
2194375
fn hidden_inits(value: &Expr) -> impl Iterator<Item = &str> {
151
2194375
    let specs = match value {
152
985189
        Expr::Lambda(_, body) => match body.as_ref() {
153
984140
            Expr::List(scope) => scope.get(1),
154
1049
            _ => None,
155
        },
156
1209186
        _ => None,
157
    };
158
2194375
    let specs = match specs {
159
976414
        Some(Expr::List(specs)) => specs.as_slice(),
160
1217961
        _ => &[],
161
    };
162
2194375
    specs.iter().filter_map(|spec| match spec {
163
975096
        Expr::List(pair) => match pair.get(1) {
164
970252
            Some(Expr::Symbol(init)) if SymbolTable::is_hidden_name(init) => Some(init.as_str()),
165
5260
            _ => None,
166
        },
167
3361
        _ => None,
168
978457
    })
169
2194375
}
170

            
171
/// A function value closed over hidden variables that `symbols` does not hold:
172
/// evaluating its call built the lambda where nothing could bind them.
173
4079
pub(in crate::compiler) fn reject_unbound_capture(
174
4079
    symbols: &SymbolTable,
175
4079
    value: &Expr,
176
4079
) -> Result<()> {
177
4079
    match hidden_inits(value).find(|init| symbols.lookup(init).is_none()) {
178
7
        Some(hidden) => Err(Error::undefined_symbol(hidden)),
179
4072
        None => Ok(()),
180
    }
181
4079
}
182

            
183
/// `value`, or the untyped placeholder when it is a lambda closed over a
184
/// hidden variable holding a runtime value no local binds.
185
2190296
pub(in crate::compiler) fn unbound_runtime_capture(symbols: &SymbolTable, value: Expr) -> Expr {
186
2190296
    let runtime = hidden_inits(&value).any(|init| {
187
969828
        symbols
188
969828
            .lookup(init)
189
969828
            .and_then(Symbol::value)
190
969828
            .is_some_and(Expr::is_wasm_runtime)
191
969828
    });
192
2190296
    match runtime {
193
1121
        true => Expr::WasmRuntime(WasmType::AnyRef),
194
2189175
        false => value,
195
    }
196
2190296
}
197

            
198
3
fn not_a_factory() -> Error {
199
3
    Error::Compile("a closure factory call must return a lambda".to_string())
200
3
}
201

            
202
#[cfg(test)]
203
#[path = "closure_factory_tests.rs"]
204
mod tests;