Lines
93.75 %
Functions
100 %
Branches
//! The one place a definition form tells the host it ran (plan 0014
//! PERSIST): every definer, in tail and effect position alike, compiles
//! through [`compile_definition`], which sets one flag for the slots it filled.
//! A host keeps the last definition of a slot whose flag is 1.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::error::Result;
use crate::runtime::{Slot, SymbolTable};
use super::CompileFn;
use super::defstruct::struct_function_names;
/// Compiles the definition form `head` with `run`, then sets the flag of the
/// slots it filled.
pub(super) fn compile_definition(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
head: &str,
args: &[Expr],
run: CompileFn,
) -> Result<()> {
let slots = defined_slots(head, args);
run(ctx, emit, symbols, args)?;
if slots.is_empty() {
return Ok(());
}
let flag = ctx.alloc_mutable_global(WasmType::I32)?;
emit.i32_const(1);
emit.global_set(flag);
for (name, slot) in &slots {
symbols.note_definition(name, *slot, flag);
Ok(())
/// The slots `head` fills: a DEFUN or DEFMACRO the function of its name, a
/// DEFSTRUCT the functions it generates, a DEFVAR or DEFPARAMETER the value
/// of its name. The flag of a cell's DEFVAR says the declaration ran; the
/// cell's own bound flag says it holds a value.
pub(super) fn defined_slots(head: &str, args: &[Expr]) -> Vec<(String, Slot)> {
let Some(name) = args.first().and_then(Expr::as_symbol) else {
return Vec::new();
};
match head {
"DEFUN" | "DEFMACRO" => vec![(name.to_string(), Slot::Function)],
"DEFSTRUCT" => struct_function_names(name, &args[1..])
.into_iter()
.map(|function| (function, Slot::Function))
.chain(std::iter::once((name.to_string(), Slot::Layout)))
.collect(),
"DEFVAR" | "DEFPARAMETER" => vec![(name.to_string(), Slot::Value)],
_ => Vec::new(),
#[cfg(test)]
#[path = "definition_tests.rs"]
mod tests;