1
//! The source of the closures a unit created (plan 0014 PERSIST P12): what a
2
//! host needs to carry a closure value on to the next unit as a lambda.
3

            
4
use crate::ast::{Expr, LambdaParams, WasmType};
5

            
6
use super::table::SymbolTable;
7

            
8
/// A lambda as it stood where a unit made a closure of it. The closure value
9
/// holds its `site`, the index of its source among the unit's, and an
10
/// environment with one field per entry of `fields`.
11
#[derive(Clone, Debug, PartialEq)]
12
pub struct ClosureSource {
13
    params: LambdaParams,
14
    body: Expr,
15
    fields: Vec<(String, WasmType)>,
16
}
17

            
18
impl ClosureSource {
19
193726
    pub(crate) fn new(params: &LambdaParams, body: &Expr, fields: Vec<(String, WasmType)>) -> Self {
20
193726
        Self {
21
193726
            params: params.clone(),
22
193726
            body: body.clone(),
23
193726
            fields,
24
193726
        }
25
193726
    }
26

            
27
    /// The captured variables the closure's environment holds, in field order.
28
    #[must_use]
29
147686
    pub fn fields(&self) -> &[(String, WasmType)] {
30
147686
        &self.fields
31
147686
    }
32

            
33
    /// The lambda this closure is as source: a capture-free one whose body
34
    /// binds every captured variable to its value, `values` for the fields.
35
    #[must_use]
36
73431
    pub fn lambda(&self, values: Vec<Expr>) -> Expr {
37
73431
        let bindings: Vec<Expr> = self
38
73431
            .fields
39
73431
            .iter()
40
3745
            .map(|(name, _)| name.clone())
41
73431
            .zip(values)
42
3745
            .map(|(name, value)| Expr::List(vec![Expr::Symbol(name), value]))
43
            .collect();
44
73431
        let body = match bindings.is_empty() {
45
69686
            true => self.body.clone(),
46
3745
            false => Expr::List(vec![
47
3745
                Expr::symbol("LET"),
48
3745
                Expr::List(bindings),
49
3745
                self.body.clone(),
50
3745
            ]),
51
        };
52
73431
        Expr::Lambda(self.params.clone(), Box::new(body))
53
73431
    }
54
}
55

            
56
impl SymbolTable {
57
    /// The source of the closure made at `site` in the unit that last compiled.
58
    #[must_use]
59
76142
    pub fn closure_source(&self, site: i32) -> Option<&ClosureSource> {
60
76142
        usize::try_from(site)
61
76142
            .ok()
62
73853
            .and_then(|at| self.unit_closures.get(at))
63
76142
    }
64
}
65

            
66
#[cfg(test)]
67
#[path = "closures_tests.rs"]
68
mod tests;