Skip to main content

nomiscript/runtime/symbol/
closures.rs

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
4use crate::ast::{Expr, LambdaParams, WasmType};
5
6use 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)]
12pub struct ClosureSource {
13    params: LambdaParams,
14    body: Expr,
15    fields: Vec<(String, WasmType)>,
16}
17
18impl ClosureSource {
19    pub(crate) fn new(params: &LambdaParams, body: &Expr, fields: Vec<(String, WasmType)>) -> Self {
20        Self {
21            params: params.clone(),
22            body: body.clone(),
23            fields,
24        }
25    }
26
27    /// The captured variables the closure's environment holds, in field order.
28    #[must_use]
29    pub fn fields(&self) -> &[(String, WasmType)] {
30        &self.fields
31    }
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    pub fn lambda(&self, values: Vec<Expr>) -> Expr {
37        let bindings: Vec<Expr> = self
38            .fields
39            .iter()
40            .map(|(name, _)| name.clone())
41            .zip(values)
42            .map(|(name, value)| Expr::List(vec![Expr::Symbol(name), value]))
43            .collect();
44        let body = match bindings.is_empty() {
45            true => self.body.clone(),
46            false => Expr::List(vec![
47                Expr::symbol("LET"),
48                Expr::List(bindings),
49                self.body.clone(),
50            ]),
51        };
52        Expr::Lambda(self.params.clone(), Box::new(body))
53    }
54}
55
56impl SymbolTable {
57    /// The source of the closure made at `site` in the unit that last compiled.
58    #[must_use]
59    pub fn closure_source(&self, site: i32) -> Option<&ClosureSource> {
60        usize::try_from(site)
61            .ok()
62            .and_then(|at| self.unit_closures.get(at))
63    }
64}
65
66#[cfg(test)]
67#[path = "closures_tests.rs"]
68mod tests;