Lines
88.57 %
Functions
93.67 %
Branches
100 %
pub(crate) mod binding;
mod cell_store;
mod compile_eval;
pub(in crate::compiler) mod control;
mod definition;
mod defstruct;
pub(in crate::compiler::special) mod iteration;
mod labels;
mod lambda;
mod macros;
mod setf_place;
pub(in crate::compiler) mod setf_scan;
mod structure;
use tracing::debug;
use crate::ast::{Expr, Place};
use crate::error::{Error, Result};
use crate::reserved::reject_reserved;
use crate::runtime::SymbolTable;
use crate::ast::WasmType;
use super::context::CompileContext;
use super::emit::FunctionEmitter;
pub(in crate::compiler) use binding::shared::{
MacroStores, expanded_function, fully_macro_expanded, is_closure_factory_call, labels_shadowed,
macro_stores, mentions_expanded, needs_cell, param_names, reads_free, unescaped,
used_as_function,
};
pub(in crate::compiler) use binding::{allocate_instances, calls_form_bound};
pub(in crate::compiler) use binding::{bind_lambda_closure, record_closure_result};
pub(in crate::compiler) use cell_store::{
compile_into_home, compile_store_value, literal_arm, reject_captured_assignment, store_arm,
pub(in crate::compiler) use control::{
ExpectingForm, apply_const_test, compile_test_condition, form_diverges_scratch,
in_runtime_branch, is_runtime_test,
pub(in crate::compiler) use defstruct::struct_function_names;
pub(in crate::compiler) use lambda::monomorph::lookup_or_emit_monomorph;
pub(in crate::compiler) use lambda::{
closure_for_stack, compute_captures, has_type_evidence, has_v1_param_shape, infer_params,
is_capture_free, non_v1_lambda_error, reject_non_v1_lambda, try_emit_lambda_for_host_iter,
try_emit_lambda_for_value,
pub(in crate::compiler) use setf_place::{compound_setf_call, expand_macro_places};
pub(in crate::compiler) use structure::set_place as setf_set_place;
pub(in crate::compiler) use structure::{compile_const_place_setf_rhs, promoted_place};
pub(super) type EvalFn = fn(&mut SymbolTable, &[Expr]) -> Result<Expr>;
pub(super) type CompileFn =
fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<()>;
pub(super) type StackFn =
fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<WasmType>;
/// Canonical metadata for a built-in special form. Mirrors `NativeSpec`
/// in `native/mod.rs` — every name appears exactly once across the four
/// dispatch paths so adding a form is a single row and missing handlers
/// surface at compile time. `compile` is the default effect path; the
/// optional `effect` overrides it when a form has specialized
/// effect-position codegen (e.g. DOLIST drops the loop's result).
pub(super) struct SpecialFormSpec {
pub name: &'static str,
pub eval: EvalFn,
pub compile: CompileFn,
pub stack: Option<StackFn>,
pub effect: Option<CompileFn>,
}
const DOMAINS: &[&[SpecialFormSpec]] = &[
control::FORMS,
control::CASE_FORMS,
binding::FORMS,
lambda::FORMS,
macros::FORMS,
compile_eval::FORMS,
iteration::FORMS,
labels::FORMS,
structure::FORMS,
];
/// Every registered special-form name, for the fold whitelist's default-deny
/// test.
#[cfg(test)]
pub(in crate::compiler) fn registered_names() -> impl Iterator<Item = &'static str> {
DOMAINS.iter().flat_map(|d| d.iter()).map(|spec| spec.name)
fn lookup(name: &str) -> Option<&'static SpecialFormSpec> {
DOMAINS
.iter()
.flat_map(|d| d.iter())
.find(|s| s.name == name)
/// True if `name` is a special form (LET, DEFUN, QUOTE, …). The effect-position
/// fallback uses this to keep routing definition / non-value forms through
/// `eval_value`, while value-producing native / host-fn calls are compiled and
/// their result dropped (so argument effects emit).
pub(in crate::compiler) fn is_special_form(name: &str) -> bool {
lookup(name).is_some()
/// True when `name` is a special form whose ONLY dispatch path is `eval` +
/// `compile` — no `stack` producer and no `effect` override. Such a form's
/// `compile` fallback is written for VALUE position (a closure-value literal
/// that doesn't run its body until called — `LAMBDA`/`FUNCTION`), not for
/// running unconditionally as a side effect. `LABELS` is NOT one of these: it
/// declares a `stack` producer, because it actually compiles and runs its body
/// inline. No definition form is one either: each has an `effect` path, so
/// it reaches the one place that flags the slots it fills.
/// The effect-position dispatcher (`expr::effect::compile_for_effect`) uses
/// this to decide which special forms fall through to the eval-only
/// registration path rather than being force-compiled.
pub(in crate::compiler) fn is_eval_only_special_form(name: &str) -> bool {
lookup(name).is_some_and(|spec| spec.stack.is_none() && spec.effect.is_none())
/// Refuses `form_name` (a definition form — `DEFVAR`/`DEFPARAMETER`/
/// `DEFUN`/`DEFMACRO`/`DEFSTRUCT`) when it is ABOUT TO perform its
/// compile-time-only symbol-table registration while
/// [`SymbolTable::is_under_any_runtime_guard`] is true — inside an
/// IF/COND/HANDLER-CASE arm, an AND/OR continuation or a function body: a COND's false clause
/// registering a definition anyway is
/// exactly as unsound as AND/OR's equivalent (the symbol table has no way
/// to represent "only bound when this runtime branch is taken", whichever
/// control form put it there). Called from each definition form's OWN
/// registration site (not a syntactic pre-scan of a guarded chain's
/// suffix) — every compile path that could reach a definition
/// (`IF`/`COND`/`LET`/`PROGN`/`HANDLER-CASE`/macro expansion/…) threads the
/// SAME `SymbolTable` the guard depths live on, so checking here is exact:
/// it fires only for a definition that would ACTUALLY be compiled under
/// the guard, and sees through macro expansion and any nesting by
/// construction, without hand-listing either.
pub(in crate::compiler) fn reject_definition_under_runtime_guard(
symbols: &SymbolTable,
form_name: &str,
) -> Result<()> {
if !symbols.is_under_any_runtime_guard()
&& !symbols.in_skippable_region()
&& symbols.function_owner().is_none()
{
return Ok(());
Err(definition_not_static(form_name))
/// Refuses a DEFUN, DEFMACRO or DEFSTRUCT `name` with the operands `args` a
/// caught exit may skip: the unit could not tell whether it defined `name`.
pub(in crate::compiler) fn reject_definition_after_exit(
name: &str,
args: &[Expr],
match symbols.skipping_region(args) {
Some(region) => Err(Error::Compile(format!(
"{form_name} {name} follows a form that may leave this {region}; move it \
before that form or out of the block"
))),
None => Ok(()),
/// The structured error of a definition that is reachable but skippable
/// (ADR-0034 decision 1): under a runtime IF/COND/AND/OR/HANDLER-CASE arm,
/// in a runtime loop's body, or in a TAGBODY segment a GO can skip.
pub(in crate::compiler) fn definition_not_static(form_name: &str) -> Error {
Error::Compile(format!(
"{form_name}: a definition must be statically executable; this one runs only when a \
runtime branch, loop or GO reaches it"
))
const DEFINITION_FORMS: &[&str] = &["DEFUN", "DEFMACRO", "DEFVAR", "DEFPARAMETER", "DEFSTRUCT"];
/// Refuses a `SETF` on a compile-time-only place (not backed by a real wasm
/// local/global) while under a genuinely runtime guard — the same
/// reasoning as [`reject_definition_under_runtime_guard`]: the store has no
/// corresponding runtime-conditional bytecode (it only updates the
/// compile-time model), so it would apply unconditionally at compile time
/// regardless of whether the guard is actually taken at runtime.
pub(in crate::compiler) fn reject_compile_time_setf_under_runtime_guard(
if !symbols.is_under_any_runtime_guard() {
Err(Error::Compile(
"SETF on a compile-time (non-runtime-backed) place under a runtime \
IF/COND/AND/OR/HANDLER-CASE branch is not supported: the store has no corresponding runtime-conditional \
bytecode, so it would apply unconditionally regardless of the guard's actual outcome. \
Move the SETF outside the runtime-conditional branch."
.to_string(),
/// Marks the cell `place` names as bound: every store to it counts.
pub(in crate::compiler) fn mark_cell_store(
emit: &mut FunctionEmitter,
place: &Expr,
target: Place,
) {
let (Expr::Symbol(name), Place::Global(_)) = (place, target) else {
return;
if let Some(flag) = symbols.cell_flag(name) {
emit.i32_const(1);
emit.global_set(flag);
/// A store to a global variable that has no runtime home in this unit would
/// land on the compile-time table, which a body compiled on a scratch copy
/// loses and no host ever carries: the scan missed it, so it is refused.
pub(in crate::compiler) fn reject_uncarried_global_store(
let Expr::Symbol(name) = place else {
reject_reserved(symbols, name)?;
let global = !symbols.is_macro_expansion()
&& !symbols.is_lexical_variable(name)
&& symbols
.lookup(name)
.is_none_or(|symbol| symbol.value().is_none_or(|value| !value.is_wasm_runtime()));
match global {
true => Err(Error::Compile(format!(
"{name}: a store the unit cannot carry; the store reaches {name} through a form \
the store scan could not read, so it would be lost; store to {name} where the \
unit can see it"
false => Ok(()),
/// Runs `run` on the rewrite of the form, one level of the shared recursion
/// budget deep: the dynamic-binder rewrite, or the BLOCK NIL around a loop
/// that may `return`. Yields `None` when the form is not rewritten.
fn through_rewrite<T>(
symbols: &mut SymbolTable,
run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
) -> Result<Option<T>> {
if let Some((name, args)) = binding::rewrite_binder(symbols, name, args)? {
return one_level(symbols, name, &args, run).map(Some);
let Some(looped) = control::wrapped_loop(symbols, name, args) else {
return Ok(None);
let block = [Expr::Nil, looped.clone()];
symbols
.with_loop_block(looped, |symbols| one_level(symbols, "BLOCK", &block, run))
.map(Some)
fn one_level<T>(
name: &'static str,
) -> Result<T> {
symbols.enter_shared_recursion()?;
let done = run(symbols, name, args);
let exited = symbols.exit_shared_recursion();
let value = done?;
exited?;
Ok(value)
pub fn call(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
debug!(special_form = %name, args = args.len(), "calling special form");
if let Some(value) = through_rewrite(symbols, name, args, call)? {
return Ok(value);
match lookup(name) {
Some(spec) => (spec.eval)(symbols, args),
None => Err(Error::Compile(format!(
"special form '{name}' not yet implemented"
pub(super) fn compile(
ctx: &mut CompileContext,
debug!(special_form = %name, args = args.len(), "compiling special form");
let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
compile(ctx, emit, symbols, name, args)
})?;
if let Some(value) = rewritten {
Some(spec) => run(ctx, emit, symbols, name, args, spec.compile),
/// Runs a special form's codegen; a definition's goes through the one place
/// that flags the slots it filled.
fn run(
compile: CompileFn,
match DEFINITION_FORMS.contains(&name) {
true => definition::compile_definition(ctx, emit, symbols, name, args, compile),
false => compile(ctx, emit, symbols, args),
pub(super) fn compile_for_effect(
compile_for_effect(ctx, emit, symbols, name, args)
Some(spec) => run(
ctx,
emit,
symbols,
name,
args,
spec.effect.unwrap_or(spec.compile),
),
fn cannot_produce_stack(name: &str) -> Error {
Error::Compile(format!("special form '{name}' cannot produce stack value"))
pub(super) fn compile_for_stack(
) -> Result<WasmType> {
compile_for_stack(ctx, emit, symbols, name, args)
Some(spec) => match spec.stack {
Some(f) => f(ctx, emit, symbols, args),
None if DEFINITION_FORMS.contains(&name) => {
binding::reject_lexical_definition(symbols, name, args)?;
reject_definition_under_runtime_guard(symbols, name)?;
Err(cannot_produce_stack(name))
None => Err(cannot_produce_stack(name)),
},
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn registry_names_unique() {
let mut seen = HashSet::new();
for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
assert!(
seen.insert(spec.name),
"duplicate special-form registration: {}",
spec.name
);
fn registry_lookup_covers_every_entry() {
lookup(spec.name).is_some(),
"lookup({}) returned None",
fn set_place_rejects_a_new_builtin_global() {
let mut symbols = SymbolTable::new();
let place = Expr::Symbol("LIST".to_string());
let result = setf_set_place(&mut symbols, &place, Expr::Nil);
assert!(matches!(result, Err(Error::Compile(msg)) if msg.contains("built-in")));
assert!(symbols.lookup("LIST").is_none());
fn set_place_defines_a_new_plain_global_and_updates_it() {
let place = Expr::Symbol("G".to_string());
assert!(matches!(
setf_set_place(&mut symbols, &place, Expr::Nil),
Ok(Expr::Nil)
));
assert!(symbols.lookup("G").is_some());