1
//! The source a closure keeps for the host to carry on (PERSIST P12).
2

            
3
use crate::ast::{Expr, LambdaParams};
4
use crate::compiler::context::closure::EnvField;
5
use crate::compiler::special::{calls_form_bound, expanded_function};
6
use crate::error::Result;
7
use crate::runtime::{ClosureSource, SymbolTable};
8

            
9
use super::constants::reads_unbound_constant;
10
use super::emit::CallingConvention;
11

            
12
/// The source of the closure a host carries on to the next unit as a lambda,
13
/// its body macro-expanded now so a later macro redefinition cannot change it:
14
/// none when its environment shares a cell, its body holds a resolved runtime
15
/// variable, calls a function that does not outlive the unit, or reads a
16
/// lexical constant that is not plain data.
17
209940
pub(super) fn closure_source(
18
209940
    symbols: &SymbolTable,
19
209940
    (params, body): (&LambdaParams, &Expr),
20
209940
    env_fields: &[EnvField],
21
209940
    cc: CallingConvention,
22
209940
) -> Result<Option<ClosureSource>> {
23
209940
    let (params, body) = expanded_function(symbols, None, params, body)?;
24
209940
    let carryable = cc == CallingConvention::Typed
25
199955
        && env_fields.iter().all(|field| field.cell.is_none())
26
194977
        && !body.any_form(Expr::is_runtime_variable)
27
194977
        && !calls_form_bound(symbols, &body)
28
193722
        && !reads_unbound_constant(symbols, &params, &body);
29
209940
    let fields = env_fields
30
209940
        .iter()
31
21900
        .map(|field| (field.name.clone(), field.ty))
32
        .collect();
33
209940
    Ok(carryable.then(|| ClosureSource::new(&params, &body, fields)))
34
209940
}