Lines
67.35 %
Functions
75 %
Branches
100 %
use crate::ast::{Expr, Place, WasmType};
use crate::compiler::expr::format_form;
use crate::error::{Error, Result};
use crate::reserved::reject_reserved;
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
use super::super::context::CompileContext;
use super::super::emit::FunctionEmitter;
use super::super::expr::{
compile_for_effect, compile_for_stack, compile_for_stack_as, eval_value, fold_value,
format_expr, probe_value, serialize_stack_to_output, store_begin_place, store_end_place,
};
use super::defstruct::{compile_defstruct, compile_defstruct_for_effect, defstruct};
use super::{SpecialFormSpec, compound_setf_call, expand_macro_places};
pub(super) const FORMS: &[SpecialFormSpec] = &[
SpecialFormSpec {
name: "DEFSTRUCT",
eval: defstruct,
compile: compile_defstruct,
stack: None,
effect: Some(compile_defstruct_for_effect),
},
name: "SETF",
eval: setf,
compile: compile_setf,
stack: Some(compile_setf_for_stack),
effect: None,
];
pub(super) fn compile_setf(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
// Value/effect position (`compile_expr` dispatch — e.g. a body/program tail
// `(setf x v)`): SETF's value (it returns the assigned value) must be
// SERIALIZED to the output buffer, leaving the wasm stack empty — the
// `compile_expr` contract. The `stack` handler keeps the value on the stack
// for genuine stack consumers (`(list … (setf n …))`); leaving it here would
// strand a value at the end of the enclosing block (invalid wasm).
let ty = compile_setf_for_stack(ctx, emit, symbols, args)?;
serialize_stack_to_output(ctx, emit, ty)
}
/// SETF in stack/value position: assign and LEAVE the assigned value on the
/// stack (so `(list … (setf n …))` / `(+ (setf n …) …)` work). A runtime-local
/// symbol place emits the value then `local.tee` (last pair) / `local.set`
/// (earlier pairs); const places fall back to the eval-rebind
/// path, then materialize the resulting value.
pub(super) fn compile_setf_for_stack(
) -> Result<WasmType> {
if !args.len().is_multiple_of(2) {
return Err(Error::Compile(
"SETF requires an even number of arguments (place value pairs)".to_string(),
));
let args = &expand_macro_places(symbols, args)?;
let pairs: Vec<&[Expr]> = args.chunks(2).collect();
let Some(last) = pairs.len().checked_sub(1) else {
// `(setf)` with no pairs ≡ nil — push the falsy i31 (typed Bool so it
// serializes as Nil), matching `setf`'s empty-arg result.
emit.i32_const(0);
return Ok(WasmType::Bool);
// Process each place/value pair INDIVIDUALLY (mirroring the effect path): a
// runtime-local place emits a typed store; a const place takes
// the eval-rebind path (no wasm store). A whole-form fallback to `setf` would
// silently DROP a runtime-local store in a MIXED form — `set_place` is a
// no-op for a `WasmLocal` symbol, so its `local.set` would never be emitted.
let mut result_ty = WasmType::Bool;
for (i, pair) in pairs.iter().enumerate() {
let place = &pair[0];
let value_expr = &pair[1];
let is_last = i == last;
if let Some(call) = compound_setf_call(symbols, place, value_expr)? {
let ty = compile_for_stack(ctx, emit, symbols, &call)?;
match is_last {
true => result_ty = ty,
false => emit.drop_value(),
continue;
match promoted_place(symbols, place) {
Some((target, ty)) => {
// Coerce the rhs to the LOCAL's declared type — a dimension-flexible
// literal (`(setf ratio-local 1)`) crosses the Index↔Scalar
// boundary and `nil` lands on the typed default; a genuine clash is
// a clean compile error, not an invalid `local.set`.
store_begin_place(ctx, emit, target);
super::compile_store_value(ctx, emit, symbols, place, value_expr, ty)?;
// Reassigning a closure local invalidates any source body recorded
// for it at bind time: the local now holds a DIFFERENT closure (or
// nil), so inlining the old body in a later FOLD would apply the
// wrong function. Forget AFTER compiling the rhs (it may FOLD the
// OLD closure) and before the store — FOLD then `call_ref`s.
if matches!(ty, WasmType::Closure(_)) {
symbols.forget_closure_body(target);
store_end_place(ctx, emit, target, is_last);
super::mark_cell_store(emit, symbols, place, target);
if is_last {
result_ty = ty;
None => {
// const place, no PRE-EXISTING runtime
// storage of its own — unsafe under a runtime guard, same
// as the effect handler (see
// `reject_compile_time_setf_under_runtime_guard`).
super::reject_compile_time_setf_under_runtime_guard(symbols)?;
super::reject_uncarried_global_store(symbols, place)?;
let value = compile_const_place_setf_rhs(ctx, emit, symbols, place, value_expr)?;
let assigned = set_place(symbols, place, value)?;
result_ty = compile_for_stack(ctx, emit, symbols, &assigned)?;
Ok(result_ty)
/// Compiles a const SETF place's RHS for its real effects and
/// returns the value to register for `place`. Mirrors DEFVAR/DEFPARAMETER's
/// own promotion (`binding::define::finish_def_binding`): a genuinely
/// RUNTIME RHS (a host-fn call, an `(error …)` raise, a nested SETF onto an
/// existing `WasmLocal`, …) needs real bytecode, and — since a compile-time
/// symbol has no storage of its own — a `Expr::Symbol` place is promoted
/// into a backing `WasmLocal` so later reads see the real value instead of a
/// dangling placeholder. A compile-time-constant RHS may
/// still carry a real side effect of its own, so it is unconditionally
/// compiled for effect too — never modelled via `eval_value` alone.
///
/// Compiling `value_expr` can ITSELF promote `place` to a real `WasmLocal`
/// — e.g. `(setf p (progn (setf p (host-fn)) 2))`, where the INNER `setf`
/// promotes `p` before the OUTER one's own value is ready. `place` is
/// RE-CHECKED after `value_expr` compiles, and if it now has real storage,
/// the outer value is stored into THAT storage for real — `set_place`
/// deliberately no-ops on an already-runtime-backed place (see its own doc
/// comment), so skipping this re-check would silently drop the outer
/// store. `value_expr` is never compiled a second time: the post-promotion
/// store consumes either the ALREADY-probed constant (a fresh,
/// side-effect-free compile of the literal via `compile_for_stack_as`) or
/// the value already sitting on the wasm stack from the runtime branch's
/// own `compile_for_stack`. Shared by both `compile_setf_for_effect` and
/// `compile_setf_for_stack`'s const-place branch.
pub(in crate::compiler) fn compile_const_place_setf_rhs(
place: &Expr,
value_expr: &Expr,
) -> Result<Expr> {
if let Some(datum) = fold_value(symbols, value_expr)? {
return store_into_promoted_place(ctx, emit, symbols, place, &datum);
let probed = probe_value(&mut symbols.clone(), value_expr)?;
if probed.is_wasm_runtime() {
return compile_const_place_setf_runtime(ctx, emit, symbols, place, value_expr);
compile_for_effect(ctx, emit, symbols, value_expr)?;
store_into_promoted_place(ctx, emit, symbols, place, &probed)
/// `place`'s existing runtime storage, if it has any (from its definition,
/// or promoted before this SETF ran at all, or by one of `value_expr`'s own
/// nested effects).
pub(in crate::compiler) fn promoted_place(
symbols: &SymbolTable,
) -> Option<(Place, WasmType)> {
match place {
Expr::Symbol(name) => symbols.lookup(name)?.value()?.place(),
other => other.place(),
/// The RHS resolved to a genuinely runtime value: compile it for real, then
/// store into `place`'s promoted local if `value_expr` itself just created
/// one (a nested SETF on the SAME symbol), otherwise allocate a fresh one —
/// mirrors DEFVAR/DEFPARAMETER's own promotion
/// (`binding::define::finish_def_binding`).
fn compile_const_place_setf_runtime(
let actual_ty = compile_for_stack(ctx, emit, symbols, value_expr)?;
if let Some((target, ty)) = promoted_place(symbols, place) {
if ty != actual_ty {
return Err(Error::Compile(format!(
"SETF: {} was promoted to {ty} by a nested assignment inside its own \
value expression, but this assignment's value is {actual_ty}",
format_form(place)
)));
set_promoted(emit, target);
return Ok(promoted_value(target, ty));
let idx = ctx.alloc_local(actual_ty)?;
emit.local_set(idx);
Ok(Expr::WasmLocal(idx, actual_ty))
/// The RHS resolved to a compile-time constant `probed`: if `place` was
/// promoted to a real local by one of `value_expr`'s own nested effects,
/// the constant must still be stored into it for real (a fresh,
/// side-effect-free compile of the literal `probed`, never `value_expr`
/// again); otherwise there is no storage to write and `probed` is simply
/// the value to register via `set_place`.
fn store_into_promoted_place(
probed: &Expr,
let Some((target, ty)) = promoted_place(symbols, place) else {
return Ok(probed.clone());
compile_for_stack_as(ctx, emit, symbols, probed, ty)?;
Ok(promoted_value(target, ty))
fn set_promoted(emit: &mut FunctionEmitter, target: Place) {
match target {
Place::Local(idx) => emit.local_set(idx),
Place::Global(idx) => emit.global_set(idx),
fn promoted_value(target: Place, ty: WasmType) -> Expr {
Place::Local(idx) => Expr::WasmLocal(idx, ty),
Place::Global(idx) => Expr::WasmGlobal(idx, ty),
/// A store to a global cell of the unit is a runtime effect: the evaluator
/// answers the value, and notes the store so a fold over it is refused.
fn stores_to_cell(symbols: &SymbolTable, place: &Expr) -> bool {
matches!(place, Expr::Symbol(name) if symbols.cell_global(name).is_some())
pub(super) fn setf(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.is_empty() {
return Ok(Expr::Nil);
let mut last_value = Expr::Nil;
for pair in args.chunks(2) {
if let Some(call) = compound_setf_call(symbols, place, &pair[1])? {
last_value = eval_value(symbols, &call)?;
if let Expr::Symbol(name) = place
&& symbols.is_macro_expansion()
&& !symbols.is_macro_local(name)
{
"{name}: a macro body may not mutate a global; an expansion makes no commits"
// A place already backed by a runtime value is a no-op here (see
// `set_place` below) — either a real `WasmLocal` (codegen already
// promoted it), or a `WasmRuntime` placeholder (the EVAL-ONLY
// surface's classification for a runtime-backed `LET`/`LET*`
// binding, which never allocates a real local: `let_eval.rs` binds
// a runtime initializer straight to `Expr::WasmRuntime`, never
// `WasmLocal`, so checking `WasmLocal` alone here wrongly treated
// it as compile-time-only). Codegen's own `let_compile.rs` ALWAYS
// promotes a `WasmRuntime` binding to a real `WasmLocal` before
// its body compiles, so codegen never reaches this function with
// a bare `WasmRuntime` place — this broadening only affects the
// eval-only surface. Anything else is a PURE compile-time-model
// update with no real bytecode, unsafe under a runtime guard, same
// as the codegen paths (`compile_setf_for_effect`/
// `compile_setf_for_stack`) — checked here too so eval-only
// classification and codegen agree on what's rejected.
let is_runtime_backed = matches!(
place,
Expr::Symbol(name) if symbols
.lookup(name)
.and_then(|s| s.value())
.is_some_and(Expr::is_wasm_runtime)
);
if !is_runtime_backed {
let value = eval_value(symbols, &pair[1])?;
if stores_to_cell(symbols, place) {
symbols.measurements().note_cell_store();
last_value = set_place(symbols, place, value)?;
Ok(last_value)
pub(in crate::compiler) fn set_place(
value: Expr,
Expr::Symbol(name) => {
reject_reserved(symbols, name)?;
if symbols.lookup(name).is_some_and(Symbol::is_loop_constant) {
"{name}: a statically unrolled loop's variable may not be assigned"
super::reject_captured_assignment(symbols, name)?;
match symbols.lookup_mut(name) {
// A var already backed by a runtime value keeps that
// binding, whether a real `WasmLocal` (the local IS its
// storage, and codegen emits the runtime store —
// overwriting it here would drop the local index, so a
// later read or assign would compile a producerless
// `WasmRuntime` → invalid wasm) or the eval-only surface's
// `WasmRuntime` placeholder (compile-time UNKNOWABLE, so
// overwriting it with the assigned value's constant would
// make a later eval-only read see a value the guard
// governing this SETF might never actually have produced
// at runtime). `setf` still returns the assigned value.
//
// The return here is deliberately the RAW `value` — not
// coerced to the place's declared type — even when the
// place is runtime-backed: this function is shared by the
// pure eval-only `setf` entry point AND codegen's own
// internal plumbing (`compile_setf_for_stack`'s
// const-place branch calls this, then feeds the result
// straight into `compile_for_stack`, which requires a
// genuinely compile-for-stack-able value, never a bare
// `WasmRuntime` placeholder with no backing local). See
// `setf` below for where the coercion-aware value belongs.
Some(sym) if sym.value().is_some_and(Expr::is_wasm_runtime) => {}
Some(sym) => sym.set_value(value.clone()),
symbols.define_special(
Symbol::new(name, SymbolKind::Variable).with_value(value.clone()),
Ok(value)
_ => Err(Error::Compile(format!(
"Invalid place in SETF: {}",
format_expr(place)
))),