Lines
97.96 %
Functions
81.82 %
Branches
100 %
//! Expression-level compile + eval dispatch.
//!
//! Split into topic-focused submodules so each file stays under the
//! ~500-line CLAUDE.md guideline:
//! - [`atoms`] — primitive emit (nil, bool, number, string, symbol,
//! push_ratio) and the `compile_text` plumbing they share.
//! - [`compile`] — the generic `compile_expr` / `compile_quoted_expr`
//! dispatch + `serialize_stack_to_output`.
//! - [`effect`] — effect-position codegen (`compile_for_effect` plus
//! the SETF / IF specialisations it owns).
//! - [`stack`] — stack-position codegen (`compile_for_stack` and the
//! ratio/numeric refinements).
//! - [`call`] — function call dispatch (symbol calls, lambda calls,
//! lambda-param binding).
//! - [`eval`] — eval-only path (`call`, `eval_value`, `dispatch_symbol`,
//! macro expansion, `resolve_arg`).
//! - [`eval_lambda`] — `eval`'s `call_lambda` and its parameter-binding
//! helpers (required / optional / rest / key / aux).
//! - [`quasiquote`] — quasiquote / unquote expansion.
//! - [`format`] — debug/display formatting for Expr and RuntimeValue.
//! `LOCAL_*` indices, `compile_program`, and the two `compile_body*`
//! helpers stay here in `mod.rs` since they're the cross-submodule
//! glue every entry point lands on.
mod any_call;
mod atoms;
mod boxing;
mod call;
mod call_runtime;
mod closure_factory;
mod compile;
mod default_check;
mod effect;
mod eval;
mod eval_lambda;
pub(crate) mod fold;
mod format;
mod index_literals;
mod lambda_params;
mod local_cell;
mod operand;
mod printed_datum;
mod quasiquote;
mod respecialise;
mod ret_guess;
mod serialize_struct;
mod serialize_value;
mod stack;
use crate::ast::{Expr, Program, WasmType};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::CompileMode;
use super::context::CompileContext;
use super::emit::FunctionEmitter;
use super::special::allocate_instances;
// Reserved local-pool indices the compiler relies on across codegen
// paths. The output-base + GC-array slots come first so they're
// available before the `next_local` allocator kicks in. See
// `CompileContext::build_locals_declaration` for the matching wasm-
// side declaration.
pub const LOCAL_GC_ARR: u32 = 0;
pub const LOCAL_IDX: u32 = 1;
pub const LOCAL_OUTPUT_BASE: u32 = 2;
pub const LOCAL_TEMP_RATIO: u32 = 3;
pub const LOCAL_TEMP_I32: u32 = 4;
/// Absolute address of the entity currently being written to the output
/// buffer (`output_base + next_write_pos`). Every output writer positions its
/// entity header + data fields relative to this so writes APPEND at the runtime
/// `next_write_pos` — the single output protocol that lets compile-time-known
/// writes (a program result) and dynamic-count writes (a `create-tag` loop)
/// share one buffer without overwriting each other.
pub const LOCAL_ENTITY_BASE: u32 = 5;
// Submodule re-exports. Keeps `super::expr::<name>` callers stable
// across the refactor so neighbouring modules (`native`, `special`,
// the compiler root) don't have to learn the submodule layout.
pub(super) use any_call::fill_any_call_helpers;
pub(super) use atoms::{compile_nil, compile_string, compile_t, emit_nil_default, push_ratio};
pub(super) use boxing::{emit_box_anyref, emit_box_cell};
pub(super) use call::compile_call;
pub(in crate::compiler) use call::{applying_lambda, call_place, pin_hint};
pub(in crate::compiler) use closure_factory::{close_factory_call, reject_unbound_capture};
pub(super) use compile::{compile_expr, serialize_stack_to_output};
pub(super) use effect::compile_for_effect;
pub(super) use operand::{
always_raises, compile_diverging_to_end, compile_index_operand, compile_raising,
compile_raising_to_end, compile_ratio_operand, compile_to_local,
};
pub(super) use stack::{
NilRepr, classify_stack_type, compile_call_for_stack, compile_for_stack, compile_for_stack_as,
compile_for_stack_expecting, index_literal, is_quoted_datum, list_datum_members, nil_repr,
no_list_cell_representation, push_number, quoted_datum, string_designator,
pub(crate) use eval::{call, eval_value, expand_macro, expand_macro_then};
pub(crate) use fold::{
DIVISION_BY_ZERO, describe_operand, fold_call, fold_safe, fold_safe_under, fold_value,
is_division_by_zero, is_instance_leaf, is_probe_rejection, is_untyped, probe_value, reads_only,
pub use format::format_form;
pub(crate) use format::{format_datum, format_expr};
pub(crate) use index_literals::reject_unindexable_literals;
pub(in crate::compiler) use local_cell::{
bind_local, emit_local_read, emit_place_read, store_begin, store_begin_place, store_end,
store_end_place,
pub(in crate::compiler) use ret_guess::recursive_ret_guess;
/// A list member handed out as a value: every member that is not
/// self-evaluating (a symbol, a non-empty list, a cons, a quote form, which is
/// the list `(QUOTE x)`) is a `Datum`. The one value representation of list
/// data on the eval surface.
pub(crate) fn member_value(member: Expr) -> Expr {
match member {
Expr::Symbol(_) | Expr::List(_) | Expr::Cons(_, _) | Expr::Quote(_) => {
Expr::quoted(member.into_datum_member())
}
other => other,
/// An already-resolved value re-entering `call` as an argument: a symbol or a
/// list is data there, so it is quoted rather than evaluated a second time.
pub(crate) fn as_literal_arg(expr: &Expr) -> Expr {
match expr {
Expr::Symbol(_) | Expr::List(_) | Expr::Cons(_, _) => Expr::quoted(expr.clone()),
_ => expr.clone(),
/// Scans the unit's text for the globals it writes, before any form of it
/// compiles (0014 §Stores to globals).
pub(in crate::compiler) fn prepare_unit(
symbols: &mut SymbolTable,
unit: &[Expr],
mode: CompileMode,
) -> Result<fold::stores::StoreScan> {
index_literals::reject_unindexable_literals(unit)?;
symbols.expire_homes();
let scan = fold::stores::scan_stores(symbols, unit, mode)?;
let (stored, possibly, opaque) = scan.measures();
symbols
.measurements()
.note_store_scan(stored as u64, possibly, opaque as u64);
symbols.snapshot_pre_unit(scan.written_names());
symbols.set_stored_globals(scan.stores());
symbols.set_unit_specials(scan.defined(), scan.dynamic());
Ok(scan)
/// Prepares the unit and makes a cell of every global it writes.
pub(in crate::compiler) fn begin_unit(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
) -> Result<()> {
symbols.forget_closure_deps();
let scan = prepare_unit(symbols, unit, mode)?;
allocate_instances(ctx, emit, symbols, &scan)
pub fn compile_program(
program: &Program,
ctx.serializer().begin_output(emit);
begin_unit(ctx, emit, symbols, &program.exprs, CompileMode::Script)?;
compile_unit_forms(ctx, emit, symbols, program)
fn compile_unit_forms(
let Some((last, init)) = program.exprs.split_last() else {
compile_nil(ctx, emit)?;
return Ok(());
let has_trigger = program.exprs.iter().any(|e| {
matches!(
e,
Expr::List(elems)
if matches!(elems.first(), Some(Expr::Symbol(name)) if name == "DEFUN")
&& matches!(elems.get(1), Some(Expr::Symbol(name)) if name == "SHOULD-APPLY")
)
});
if has_trigger {
for expr in &program.exprs {
compile_for_effect(ctx, emit, symbols, expr)?;
Ok(())
} else {
for expr in init {
compile_expr(ctx, emit, symbols, last)?;
pub(in crate::compiler) fn compile_body(
body: &[Expr],
let (last, init) = body
.split_last()
.ok_or_else(|| Error::Compile("empty body".to_string()))?;
compile_expr(ctx, emit, symbols, last)
pub(in crate::compiler) fn compile_body_for_stack(
) -> Result<WasmType> {
compile_for_stack(ctx, emit, symbols, last)