Skip to main content

nomiscript/compiler/special/
mod.rs

1pub(crate) mod binding;
2mod cell_store;
3mod compile_eval;
4pub(in crate::compiler) mod control;
5mod definition;
6mod defstruct;
7pub(in crate::compiler::special) mod iteration;
8mod labels;
9mod lambda;
10mod macros;
11mod setf_place;
12pub(in crate::compiler) mod setf_scan;
13mod structure;
14
15use tracing::debug;
16
17use crate::ast::{Expr, Place};
18use crate::error::{Error, Result};
19use crate::reserved::reject_reserved;
20use crate::runtime::SymbolTable;
21
22use crate::ast::WasmType;
23
24use super::context::CompileContext;
25use super::emit::FunctionEmitter;
26
27pub(in crate::compiler) use binding::shared::{
28    MacroStores, expanded_function, fully_macro_expanded, is_closure_factory_call, labels_shadowed,
29    macro_stores, mentions_expanded, needs_cell, param_names, reads_free, unescaped,
30    used_as_function,
31};
32pub(in crate::compiler) use binding::{allocate_instances, calls_form_bound};
33pub(in crate::compiler) use binding::{bind_lambda_closure, record_closure_result};
34pub(in crate::compiler) use cell_store::{
35    compile_into_home, compile_store_value, literal_arm, reject_captured_assignment, store_arm,
36};
37pub(in crate::compiler) use control::{
38    ExpectingForm, apply_const_test, compile_test_condition, form_diverges_scratch,
39    in_runtime_branch, is_runtime_test,
40};
41pub(in crate::compiler) use defstruct::struct_function_names;
42pub(in crate::compiler) use lambda::monomorph::lookup_or_emit_monomorph;
43pub(in crate::compiler) use lambda::{
44    closure_for_stack, compute_captures, has_type_evidence, has_v1_param_shape, infer_params,
45    is_capture_free, non_v1_lambda_error, reject_non_v1_lambda, try_emit_lambda_for_host_iter,
46    try_emit_lambda_for_value,
47};
48pub(in crate::compiler) use setf_place::{compound_setf_call, expand_macro_places};
49pub(in crate::compiler) use structure::set_place as setf_set_place;
50pub(in crate::compiler) use structure::{compile_const_place_setf_rhs, promoted_place};
51
52pub(super) type EvalFn = fn(&mut SymbolTable, &[Expr]) -> Result<Expr>;
53pub(super) type CompileFn =
54    fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<()>;
55pub(super) type StackFn =
56    fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<WasmType>;
57
58/// Canonical metadata for a built-in special form. Mirrors `NativeSpec`
59/// in `native/mod.rs` — every name appears exactly once across the four
60/// dispatch paths so adding a form is a single row and missing handlers
61/// surface at compile time. `compile` is the default effect path; the
62/// optional `effect` overrides it when a form has specialized
63/// effect-position codegen (e.g. DOLIST drops the loop's result).
64pub(super) struct SpecialFormSpec {
65    pub name: &'static str,
66    pub eval: EvalFn,
67    pub compile: CompileFn,
68    pub stack: Option<StackFn>,
69    pub effect: Option<CompileFn>,
70}
71
72const DOMAINS: &[&[SpecialFormSpec]] = &[
73    control::FORMS,
74    control::CASE_FORMS,
75    binding::FORMS,
76    lambda::FORMS,
77    macros::FORMS,
78    compile_eval::FORMS,
79    iteration::FORMS,
80    labels::FORMS,
81    structure::FORMS,
82];
83
84/// Every registered special-form name, for the fold whitelist's default-deny
85/// test.
86#[cfg(test)]
87pub(in crate::compiler) fn registered_names() -> impl Iterator<Item = &'static str> {
88    DOMAINS.iter().flat_map(|d| d.iter()).map(|spec| spec.name)
89}
90
91fn lookup(name: &str) -> Option<&'static SpecialFormSpec> {
92    DOMAINS
93        .iter()
94        .flat_map(|d| d.iter())
95        .find(|s| s.name == name)
96}
97
98/// True if `name` is a special form (LET, DEFUN, QUOTE, …). The effect-position
99/// fallback uses this to keep routing definition / non-value forms through
100/// `eval_value`, while value-producing native / host-fn calls are compiled and
101/// their result dropped (so argument effects emit).
102pub(in crate::compiler) fn is_special_form(name: &str) -> bool {
103    lookup(name).is_some()
104}
105
106/// True when `name` is a special form whose ONLY dispatch path is `eval` +
107/// `compile` — no `stack` producer and no `effect` override. Such a form's
108/// `compile` fallback is written for VALUE position (a closure-value literal
109/// that doesn't run its body until called — `LAMBDA`/`FUNCTION`), not for
110/// running unconditionally as a side effect. `LABELS` is NOT one of these: it
111/// declares a `stack` producer, because it actually compiles and runs its body
112/// inline. No definition form is one either: each has an `effect` path, so
113/// it reaches the one place that flags the slots it fills.
114/// The effect-position dispatcher (`expr::effect::compile_for_effect`) uses
115/// this to decide which special forms fall through to the eval-only
116/// registration path rather than being force-compiled.
117pub(in crate::compiler) fn is_eval_only_special_form(name: &str) -> bool {
118    lookup(name).is_some_and(|spec| spec.stack.is_none() && spec.effect.is_none())
119}
120
121/// Refuses `form_name` (a definition form — `DEFVAR`/`DEFPARAMETER`/
122/// `DEFUN`/`DEFMACRO`/`DEFSTRUCT`) when it is ABOUT TO perform its
123/// compile-time-only symbol-table registration while
124/// [`SymbolTable::is_under_any_runtime_guard`] is true — inside an
125/// IF/COND/HANDLER-CASE arm, an AND/OR continuation or a function body: a COND's false clause
126/// registering a definition anyway is
127/// exactly as unsound as AND/OR's equivalent (the symbol table has no way
128/// to represent "only bound when this runtime branch is taken", whichever
129/// control form put it there). Called from each definition form's OWN
130/// registration site (not a syntactic pre-scan of a guarded chain's
131/// suffix) — every compile path that could reach a definition
132/// (`IF`/`COND`/`LET`/`PROGN`/`HANDLER-CASE`/macro expansion/…) threads the
133/// SAME `SymbolTable` the guard depths live on, so checking here is exact:
134/// it fires only for a definition that would ACTUALLY be compiled under
135/// the guard, and sees through macro expansion and any nesting by
136/// construction, without hand-listing either.
137pub(in crate::compiler) fn reject_definition_under_runtime_guard(
138    symbols: &SymbolTable,
139    form_name: &str,
140) -> Result<()> {
141    if !symbols.is_under_any_runtime_guard()
142        && !symbols.in_skippable_region()
143        && symbols.function_owner().is_none()
144    {
145        return Ok(());
146    }
147    Err(definition_not_static(form_name))
148}
149
150/// Refuses a DEFUN, DEFMACRO or DEFSTRUCT `name` with the operands `args` a
151/// caught exit may skip: the unit could not tell whether it defined `name`.
152pub(in crate::compiler) fn reject_definition_after_exit(
153    symbols: &SymbolTable,
154    form_name: &str,
155    name: &str,
156    args: &[Expr],
157) -> Result<()> {
158    match symbols.skipping_region(args) {
159        Some(region) => Err(Error::Compile(format!(
160            "{form_name} {name} follows a form that may leave this {region}; move it \
161             before that form or out of the block"
162        ))),
163        None => Ok(()),
164    }
165}
166
167/// The structured error of a definition that is reachable but skippable
168/// (ADR-0034 decision 1): under a runtime IF/COND/AND/OR/HANDLER-CASE arm,
169/// in a runtime loop's body, or in a TAGBODY segment a GO can skip.
170pub(in crate::compiler) fn definition_not_static(form_name: &str) -> Error {
171    Error::Compile(format!(
172        "{form_name}: a definition must be statically executable; this one runs only when a \
173         runtime branch, loop or GO reaches it"
174    ))
175}
176
177const DEFINITION_FORMS: &[&str] = &["DEFUN", "DEFMACRO", "DEFVAR", "DEFPARAMETER", "DEFSTRUCT"];
178
179/// Refuses a `SETF` on a compile-time-only place (not backed by a real wasm
180/// local/global) while under a genuinely runtime guard — the same
181/// reasoning as [`reject_definition_under_runtime_guard`]: the store has no
182/// corresponding runtime-conditional bytecode (it only updates the
183/// compile-time model), so it would apply unconditionally at compile time
184/// regardless of whether the guard is actually taken at runtime.
185pub(in crate::compiler) fn reject_compile_time_setf_under_runtime_guard(
186    symbols: &SymbolTable,
187) -> Result<()> {
188    if !symbols.is_under_any_runtime_guard() {
189        return Ok(());
190    }
191    Err(Error::Compile(
192        "SETF on a compile-time (non-runtime-backed) place under a runtime \
193         IF/COND/AND/OR/HANDLER-CASE branch is not supported: the store has no corresponding runtime-conditional \
194         bytecode, so it would apply unconditionally regardless of the guard's actual outcome. \
195         Move the SETF outside the runtime-conditional branch."
196            .to_string(),
197    ))
198}
199
200/// Marks the cell `place` names as bound: every store to it counts.
201pub(in crate::compiler) fn mark_cell_store(
202    emit: &mut FunctionEmitter,
203    symbols: &SymbolTable,
204    place: &Expr,
205    target: Place,
206) {
207    let (Expr::Symbol(name), Place::Global(_)) = (place, target) else {
208        return;
209    };
210    if let Some(flag) = symbols.cell_flag(name) {
211        emit.i32_const(1);
212        emit.global_set(flag);
213    }
214}
215
216/// A store to a global variable that has no runtime home in this unit would
217/// land on the compile-time table, which a body compiled on a scratch copy
218/// loses and no host ever carries: the scan missed it, so it is refused.
219pub(in crate::compiler) fn reject_uncarried_global_store(
220    symbols: &SymbolTable,
221    place: &Expr,
222) -> Result<()> {
223    let Expr::Symbol(name) = place else {
224        return Ok(());
225    };
226    reject_reserved(symbols, name)?;
227    let global = !symbols.is_macro_expansion()
228        && !symbols.is_lexical_variable(name)
229        && symbols
230            .lookup(name)
231            .is_none_or(|symbol| symbol.value().is_none_or(|value| !value.is_wasm_runtime()));
232    match global {
233        true => Err(Error::Compile(format!(
234            "{name}: a store the unit cannot carry; the store reaches {name} through a form \
235             the store scan could not read, so it would be lost; store to {name} where the \
236             unit can see it"
237        ))),
238        false => Ok(()),
239    }
240}
241
242/// Runs `run` on the rewrite of the form, one level of the shared recursion
243/// budget deep: the dynamic-binder rewrite, or the BLOCK NIL around a loop
244/// that may `return`. Yields `None` when the form is not rewritten.
245fn through_rewrite<T>(
246    symbols: &mut SymbolTable,
247    name: &str,
248    args: &[Expr],
249    run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
250) -> Result<Option<T>> {
251    if let Some((name, args)) = binding::rewrite_binder(symbols, name, args)? {
252        return one_level(symbols, name, &args, run).map(Some);
253    }
254    let Some(looped) = control::wrapped_loop(symbols, name, args) else {
255        return Ok(None);
256    };
257    let block = [Expr::Nil, looped.clone()];
258    symbols
259        .with_loop_block(looped, |symbols| one_level(symbols, "BLOCK", &block, run))
260        .map(Some)
261}
262
263fn one_level<T>(
264    symbols: &mut SymbolTable,
265    name: &'static str,
266    args: &[Expr],
267    run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
268) -> Result<T> {
269    symbols.enter_shared_recursion()?;
270    let done = run(symbols, name, args);
271    let exited = symbols.exit_shared_recursion();
272    let value = done?;
273    exited?;
274    Ok(value)
275}
276
277pub fn call(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
278    debug!(special_form = %name, args = args.len(), "calling special form");
279    if let Some(value) = through_rewrite(symbols, name, args, call)? {
280        return Ok(value);
281    }
282    match lookup(name) {
283        Some(spec) => (spec.eval)(symbols, args),
284        None => Err(Error::Compile(format!(
285            "special form '{name}' not yet implemented"
286        ))),
287    }
288}
289
290pub(super) fn compile(
291    ctx: &mut CompileContext,
292    emit: &mut FunctionEmitter,
293    symbols: &mut SymbolTable,
294    name: &str,
295    args: &[Expr],
296) -> Result<()> {
297    debug!(special_form = %name, args = args.len(), "compiling special form");
298    let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
299        compile(ctx, emit, symbols, name, args)
300    })?;
301    if let Some(value) = rewritten {
302        return Ok(value);
303    }
304    match lookup(name) {
305        Some(spec) => run(ctx, emit, symbols, name, args, spec.compile),
306        None => Err(Error::Compile(format!(
307            "special form '{name}' not yet implemented"
308        ))),
309    }
310}
311
312/// Runs a special form's codegen; a definition's goes through the one place
313/// that flags the slots it filled.
314fn run(
315    ctx: &mut CompileContext,
316    emit: &mut FunctionEmitter,
317    symbols: &mut SymbolTable,
318    name: &str,
319    args: &[Expr],
320    compile: CompileFn,
321) -> Result<()> {
322    match DEFINITION_FORMS.contains(&name) {
323        true => definition::compile_definition(ctx, emit, symbols, name, args, compile),
324        false => compile(ctx, emit, symbols, args),
325    }
326}
327
328pub(super) fn compile_for_effect(
329    ctx: &mut CompileContext,
330    emit: &mut FunctionEmitter,
331    symbols: &mut SymbolTable,
332    name: &str,
333    args: &[Expr],
334) -> Result<()> {
335    let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
336        compile_for_effect(ctx, emit, symbols, name, args)
337    })?;
338    if let Some(value) = rewritten {
339        return Ok(value);
340    }
341    match lookup(name) {
342        Some(spec) => run(
343            ctx,
344            emit,
345            symbols,
346            name,
347            args,
348            spec.effect.unwrap_or(spec.compile),
349        ),
350        None => Err(Error::Compile(format!(
351            "special form '{name}' not yet implemented"
352        ))),
353    }
354}
355
356fn cannot_produce_stack(name: &str) -> Error {
357    Error::Compile(format!("special form '{name}' cannot produce stack value"))
358}
359
360pub(super) fn compile_for_stack(
361    ctx: &mut CompileContext,
362    emit: &mut FunctionEmitter,
363    symbols: &mut SymbolTable,
364    name: &str,
365    args: &[Expr],
366) -> Result<WasmType> {
367    let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
368        compile_for_stack(ctx, emit, symbols, name, args)
369    })?;
370    if let Some(value) = rewritten {
371        return Ok(value);
372    }
373    match lookup(name) {
374        Some(spec) => match spec.stack {
375            Some(f) => f(ctx, emit, symbols, args),
376            None if DEFINITION_FORMS.contains(&name) => {
377                binding::reject_lexical_definition(symbols, name, args)?;
378                reject_definition_under_runtime_guard(symbols, name)?;
379                Err(cannot_produce_stack(name))
380            }
381            None => Err(cannot_produce_stack(name)),
382        },
383        None => Err(Error::Compile(format!(
384            "special form '{name}' not yet implemented"
385        ))),
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392    use std::collections::HashSet;
393
394    #[test]
395    fn registry_names_unique() {
396        let mut seen = HashSet::new();
397        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
398            assert!(
399                seen.insert(spec.name),
400                "duplicate special-form registration: {}",
401                spec.name
402            );
403        }
404    }
405
406    #[test]
407    fn registry_lookup_covers_every_entry() {
408        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
409            assert!(
410                lookup(spec.name).is_some(),
411                "lookup({}) returned None",
412                spec.name
413            );
414        }
415    }
416
417    #[test]
418    fn set_place_rejects_a_new_builtin_global() {
419        let mut symbols = SymbolTable::new();
420        let place = Expr::Symbol("LIST".to_string());
421        let result = setf_set_place(&mut symbols, &place, Expr::Nil);
422        assert!(matches!(result, Err(Error::Compile(msg)) if msg.contains("built-in")));
423        assert!(symbols.lookup("LIST").is_none());
424    }
425
426    #[test]
427    fn set_place_defines_a_new_plain_global_and_updates_it() {
428        let mut symbols = SymbolTable::new();
429        let place = Expr::Symbol("G".to_string());
430        assert!(matches!(
431            setf_set_place(&mut symbols, &place, Expr::Nil),
432            Ok(Expr::Nil)
433        ));
434        assert!(symbols.lookup("G").is_some());
435        assert!(matches!(
436            setf_set_place(&mut symbols, &place, Expr::Nil),
437            Ok(Expr::Nil)
438        ));
439    }
440}