Lines
100 %
Functions
Branches
//! A `LIST` holding a lambda literal. Closure creation reads its captures by
//! value, so every non-literal member is evaluated into a local in source
//! order first; the chain's element type is then read off the compiled values.
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{compile_for_stack, emit_box_anyref, emit_box_cell};
use crate::compiler::special::record_closure_result;
use crate::error::Result;
use crate::runtime::SymbolTable;
use super::cons::{close_pair_chain, push_pair_car};
use super::infer::chain_pair_element;
enum Member {
Literal,
Spilled { local: u32, ty: WasmType },
}
/// A macro body runs at expansion time, where a lambda stays data.
pub(super) fn lambda_runs_at_runtime(symbols: &SymbolTable, values: &[Expr]) -> bool {
!symbols.is_macro_expansion() && values.iter().any(|value| matches!(value, Expr::Lambda(..)))
pub(super) fn compile_spilled_chain(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
resolved: &[Expr],
) -> Result<WasmType> {
let members = args
.iter()
.map(|arg| spill_member(ctx, emit, symbols, arg))
.collect::<Result<Vec<_>>>()?;
let typed: Vec<Expr> = members
.zip(resolved)
.map(|(member, value)| match member {
Member::Literal => value.clone(),
Member::Spilled { ty, .. } => Expr::WasmRuntime(*ty),
})
.collect();
let elem = chain_pair_element(&typed)?;
for (member, arg) in members.iter().zip(args) {
match member {
Member::Literal => push_pair_car(ctx, emit, symbols, arg, elem)?,
Member::Spilled { local, ty } => push_spilled(ctx, emit, *local, *ty, elem),
close_pair_chain(ctx, emit, args.len());
Ok(WasmType::PairRef(elem))
fn spill_member(
arg: &Expr,
) -> Result<Member> {
if is_literal(arg) {
return Ok(Member::Literal);
let ty = compile_for_stack(ctx, emit, symbols, arg)?;
let local = ctx.alloc_local(ty)?;
emit.local_set(local);
record_closure_result(symbols, ctx, &Expr::WasmLocal(local, ty))?;
Ok(Member::Spilled { local, ty })
fn is_literal(arg: &Expr) -> bool {
matches!(
arg,
Expr::Number(_)
| Expr::String(_)
| Expr::T
| Expr::Nil
| Expr::Keyword(_)
| Expr::Quote(_)
| Expr::Datum(_)
)
fn push_spilled(
ctx: &CompileContext,
local: u32,
ty: WasmType,
elem: PairElement,
) {
emit.local_get(local);
match elem {
PairElement::AnyRef => emit_box_anyref(ctx, emit, ty),
_ => emit_box_cell(ctx, emit, elem, elem),