Lines
100 %
Functions
Branches
//! The source of the closures a unit created (plan 0014 PERSIST P12): what a
//! host needs to carry a closure value on to the next unit as a lambda.
use crate::ast::{Expr, LambdaParams, WasmType};
use super::table::SymbolTable;
/// A lambda as it stood where a unit made a closure of it. The closure value
/// holds its `site`, the index of its source among the unit's, and an
/// environment with one field per entry of `fields`.
#[derive(Clone, Debug, PartialEq)]
pub struct ClosureSource {
params: LambdaParams,
body: Expr,
fields: Vec<(String, WasmType)>,
}
impl ClosureSource {
pub(crate) fn new(params: &LambdaParams, body: &Expr, fields: Vec<(String, WasmType)>) -> Self {
Self {
params: params.clone(),
body: body.clone(),
fields,
/// The captured variables the closure's environment holds, in field order.
#[must_use]
pub fn fields(&self) -> &[(String, WasmType)] {
&self.fields
/// The lambda this closure is as source: a capture-free one whose body
/// binds every captured variable to its value, `values` for the fields.
pub fn lambda(&self, values: Vec<Expr>) -> Expr {
let bindings: Vec<Expr> = self
.fields
.iter()
.map(|(name, _)| name.clone())
.zip(values)
.map(|(name, value)| Expr::List(vec![Expr::Symbol(name), value]))
.collect();
let body = match bindings.is_empty() {
true => self.body.clone(),
false => Expr::List(vec![
Expr::symbol("LET"),
Expr::List(bindings),
self.body.clone(),
]),
};
Expr::Lambda(self.params.clone(), Box::new(body))
impl SymbolTable {
/// The source of the closure made at `site` in the unit that last compiled.
pub fn closure_source(&self, site: i32) -> Option<&ClosureSource> {
usize::try_from(site)
.ok()
.and_then(|at| self.unit_closures.get(at))
#[cfg(test)]
#[path = "closures_tests.rs"]
mod tests;