Lines
95.92 %
Functions
100 %
Branches
//! `FUNCALL` and `APPLY`: the function operand's effects run first, then the
//! other operands left to right. A call the compiler can see cannot be made (a
//! literal that is no function, an unknown function, a wrong arity, a last
//! operand that is no list, a function operand it cannot name) is a compile
//! error.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::fold::walk::is_lambda_literal;
use crate::compiler::expr::{
compile_call, compile_call_for_stack, compile_expr, compile_for_effect, compile_for_stack,
eval_value, fold_safe, fold_value,
};
use crate::compiler::join::NEVER_RETURNS;
use crate::compiler::native::function_operand::{
effect_prefix, function_operand, hoist_call_function,
use super::{build_apply_call, resolve_apply_designator, spread_apply_last_arg};
use crate::error::{Error, Result};
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
pub(super) fn compile_funcall(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
original: &[Expr],
) -> Result<()> {
let Some(args) = funcall_operands(ctx, emit, symbols, original)? else {
return Ok(());
compile_call(ctx, emit, symbols, &args)
}
pub(super) fn compile_funcall_for_stack(
) -> Result<WasmType> {
return Ok(NEVER_RETURNS);
compile_call_for_stack(ctx, emit, symbols, &args)
/// `args` with the function operand's effects run once, ahead of the call, and
/// the function left in its place; `None` when the function operand always
/// raises.
fn funcall_operands(
args: &[Expr],
) -> Result<Option<Vec<Expr>>> {
if args.is_empty() {
return Err(Error::Compile(
"funcall requires at least a function argument".to_string(),
));
let Some(mut hoisted) = hoist_call_function(ctx, emit, symbols, args)? else {
return Ok(None);
hoisted[0] = function_operand(symbols, &hoisted[0])?;
Ok(Some(hoisted))
/// The call APPLY makes: each leading operand with an effect is compiled once
/// into a local of `bindings`, in order, then the last operand's `effects` run,
/// so every operand runs once, left to right; the function operand's effects
/// have already run.
pub(super) struct ApplyCall {
bindings: Vec<(String, Expr)>,
effects: Vec<Expr>,
call: Vec<Expr>,
impl ApplyCall {
/// Emits the bindings and effects, then `finish` of the call form, inside a
/// scope that holds the locals.
fn emit<T>(
self,
finish: impl FnOnce(
&mut CompileContext,
&mut FunctionEmitter,
&mut SymbolTable,
&Expr,
) -> Result<T>,
) -> Result<T> {
symbols.push_scope();
let result = self.emit_in_scope(ctx, emit, symbols, finish);
symbols.pop_scope()?;
result
fn emit_in_scope<T>(
for (name, operand) in &self.bindings {
let ty = compile_for_stack(ctx, emit, symbols, operand)?;
let idx = ctx.alloc_local(ty)?;
emit.local_set(idx);
let local =
Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmLocal(idx, ty));
symbols.define_scoped(local);
for effect in &self.effects {
compile_for_effect(ctx, emit, symbols, effect)?;
finish(ctx, emit, symbols, &Expr::List(self.call))
pub(super) fn compile_apply_form(
let Some(call) = apply_call(ctx, emit, symbols, args)? else {
call.emit(ctx, emit, symbols, compile_expr)
pub(super) fn compile_apply_form_for_stack(
call.emit(ctx, emit, symbols, compile_for_stack)
/// The call APPLY makes. A call needing no operand compilation is built the
/// way the evaluator builds it; `None` when the function operand always raises.
fn apply_call(
) -> Result<Option<ApplyCall>> {
if original.len() < 2 {
return Ok(Some(ApplyCall {
bindings: Vec::new(),
effects: Vec::new(),
call: build_apply_call(symbols, original)?,
}));
plan_apply(symbols, &args).map(Some)
/// Nothing is emitted here: the operands are compiled by [`ApplyCall::emit`].
fn plan_apply(symbols: &mut SymbolTable, args: &[Expr]) -> Result<ApplyCall> {
let Some((last, leading)) = args.split_last() else {
return Err(Error::Compile("apply requires a function".to_string()));
let mut call = vec![resolve_apply_designator(symbols, &leading[0])?];
let mut bindings = Vec::new();
for arg in &leading[1..] {
call.push(apply_leading_operand(symbols, arg, &mut bindings)?);
let (prefix, tail) = effect_prefix(last);
call.extend(spread_apply_last_arg(&mut symbols.clone(), tail)?);
let effects = match tail {
Expr::List(items) if is_list_constructor(items) => prefix.to_vec(),
_ if fold_safe(symbols, last) => Vec::new(),
_ => vec![last.clone()],
Ok(ApplyCall {
bindings,
effects,
call,
})
fn is_list_constructor(items: &[Expr]) -> bool {
matches!(items.first(), Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("LIST"))
/// A leading operand as the call sees it: its value when it folds, and
/// otherwise a variable bound to it, so it is compiled once and never
/// evaluated at compile time.
fn apply_leading_operand(
arg: &Expr,
bindings: &mut Vec<(String, Expr)>,
) -> Result<Expr> {
if is_lambda_literal(symbols, arg) {
return eval_value(symbols, arg);
if let Some(value) = fold_value(symbols, arg)? {
return Ok(value);
let name = format!("%APPLY-ARG-{}", bindings.len());
bindings.push((name.clone(), arg.clone()));
Ok(Expr::Symbol(name))