1
pub(crate) mod binding;
2
mod cell_store;
3
mod compile_eval;
4
pub(in crate::compiler) mod control;
5
mod definition;
6
mod defstruct;
7
pub(in crate::compiler::special) mod iteration;
8
mod labels;
9
mod lambda;
10
mod macros;
11
mod setf_place;
12
pub(in crate::compiler) mod setf_scan;
13
mod structure;
14

            
15
use tracing::debug;
16

            
17
use crate::ast::{Expr, Place};
18
use crate::error::{Error, Result};
19
use crate::reserved::reject_reserved;
20
use crate::runtime::SymbolTable;
21

            
22
use crate::ast::WasmType;
23

            
24
use super::context::CompileContext;
25
use super::emit::FunctionEmitter;
26

            
27
pub(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
};
32
pub(in crate::compiler) use binding::{allocate_instances, calls_form_bound};
33
pub(in crate::compiler) use binding::{bind_lambda_closure, record_closure_result};
34
pub(in crate::compiler) use cell_store::{
35
    compile_into_home, compile_store_value, literal_arm, reject_captured_assignment, store_arm,
36
};
37
pub(in crate::compiler) use control::{
38
    ExpectingForm, apply_const_test, compile_test_condition, form_diverges_scratch,
39
    in_runtime_branch, is_runtime_test,
40
};
41
pub(in crate::compiler) use defstruct::struct_function_names;
42
pub(in crate::compiler) use lambda::monomorph::lookup_or_emit_monomorph;
43
pub(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
};
48
pub(in crate::compiler) use setf_place::{compound_setf_call, expand_macro_places};
49
pub(in crate::compiler) use structure::set_place as setf_set_place;
50
pub(in crate::compiler) use structure::{compile_const_place_setf_rhs, promoted_place};
51

            
52
pub(super) type EvalFn = fn(&mut SymbolTable, &[Expr]) -> Result<Expr>;
53
pub(super) type CompileFn =
54
    fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<()>;
55
pub(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).
64
pub(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

            
72
const 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)]
87
1
pub(in crate::compiler) fn registered_names() -> impl Iterator<Item = &'static str> {
88
43
    DOMAINS.iter().flat_map(|d| d.iter()).map(|spec| spec.name)
89
1
}
90

            
91
22104206
fn lookup(name: &str) -> Option<&'static SpecialFormSpec> {
92
22104206
    DOMAINS
93
22104206
        .iter()
94
79533119
        .flat_map(|d| d.iter())
95
429474067
        .find(|s| s.name == name)
96
22104206
}
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).
102
1627847
pub(in crate::compiler) fn is_special_form(name: &str) -> bool {
103
1627847
    lookup(name).is_some()
104
1627847
}
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.
117
1170187
pub(in crate::compiler) fn is_eval_only_special_form(name: &str) -> bool {
118
1170187
    lookup(name).is_some_and(|spec| spec.stack.is_none() && spec.effect.is_none())
119
1170187
}
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.
137
7635876
pub(in crate::compiler) fn reject_definition_under_runtime_guard(
138
7635876
    symbols: &SymbolTable,
139
7635876
    form_name: &str,
140
7635876
) -> Result<()> {
141
7635876
    if !symbols.is_under_any_runtime_guard()
142
7629210
        && !symbols.in_skippable_region()
143
7628152
        && symbols.function_owner().is_none()
144
    {
145
7625656
        return Ok(());
146
10220
    }
147
10220
    Err(definition_not_static(form_name))
148
7635876
}
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`.
152
7058332
pub(in crate::compiler) fn reject_definition_after_exit(
153
7058332
    symbols: &SymbolTable,
154
7058332
    form_name: &str,
155
7058332
    name: &str,
156
7058332
    args: &[Expr],
157
7058332
) -> Result<()> {
158
7058332
    match symbols.skipping_region(args) {
159
14572
        Some(region) => Err(Error::Compile(format!(
160
14572
            "{form_name} {name} follows a form that may leave this {region}; move it \
161
14572
             before that form or out of the block"
162
14572
        ))),
163
7043760
        None => Ok(()),
164
    }
165
7058332
}
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.
170
10856
pub(in crate::compiler) fn definition_not_static(form_name: &str) -> Error {
171
10856
    Error::Compile(format!(
172
10856
        "{form_name}: a definition must be statically executable; this one runs only when a \
173
10856
         runtime branch, loop or GO reaches it"
174
10856
    ))
175
10856
}
176

            
177
const 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.
185
204993
pub(in crate::compiler) fn reject_compile_time_setf_under_runtime_guard(
186
204993
    symbols: &SymbolTable,
187
204993
) -> Result<()> {
188
204993
    if !symbols.is_under_any_runtime_guard() {
189
204993
        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
204993
}
199

            
200
/// Marks the cell `place` names as bound: every store to it counts.
201
574851
pub(in crate::compiler) fn mark_cell_store(
202
574851
    emit: &mut FunctionEmitter,
203
574851
    symbols: &SymbolTable,
204
574851
    place: &Expr,
205
574851
    target: Place,
206
574851
) {
207
574851
    let (Expr::Symbol(name), Place::Global(_)) = (place, target) else {
208
234755
        return;
209
    };
210
340096
    if let Some(flag) = symbols.cell_flag(name) {
211
340096
        emit.i32_const(1);
212
340096
        emit.global_set(flag);
213
    }
214
574851
}
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.
219
1050
pub(in crate::compiler) fn reject_uncarried_global_store(
220
1050
    symbols: &SymbolTable,
221
1050
    place: &Expr,
222
1050
) -> Result<()> {
223
1050
    let Expr::Symbol(name) = place else {
224
        return Ok(());
225
    };
226
1050
    reject_reserved(symbols, name)?;
227
836
    let global = !symbols.is_macro_expansion()
228
836
        && !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
836
    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
836
        false => Ok(()),
239
    }
240
1050
}
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.
245
19318332
fn through_rewrite<T>(
246
19318332
    symbols: &mut SymbolTable,
247
19318332
    name: &str,
248
19318332
    args: &[Expr],
249
19318332
    run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
250
19318332
) -> Result<Option<T>> {
251
19318332
    if let Some((name, args)) = binding::rewrite_binder(symbols, name, args)? {
252
4075
        return one_level(symbols, name, &args, run).map(Some);
253
19314254
    }
254
19314254
    let Some(looped) = control::wrapped_loop(symbols, name, args) else {
255
19306129
        return Ok(None);
256
    };
257
8125
    let block = [Expr::Nil, looped.clone()];
258
8125
    symbols
259
8125
        .with_loop_block(looped, |symbols| one_level(symbols, "BLOCK", &block, run))
260
8125
        .map(Some)
261
19318332
}
262

            
263
12200
fn one_level<T>(
264
12200
    symbols: &mut SymbolTable,
265
12200
    name: &'static str,
266
12200
    args: &[Expr],
267
12200
    run: impl FnOnce(&mut SymbolTable, &'static str, &[Expr]) -> Result<T>,
268
12200
) -> Result<T> {
269
12200
    symbols.enter_shared_recursion()?;
270
12196
    let done = run(symbols, name, args);
271
12196
    let exited = symbols.exit_shared_recursion();
272
12196
    let value = done?;
273
11439
    exited?;
274
11439
    Ok(value)
275
12200
}
276

            
277
14785147
pub fn call(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
278
14785147
    debug!(special_form = %name, args = args.len(), "calling special form");
279
14785147
    if let Some(value) = through_rewrite(symbols, name, args, call)? {
280
7107
        return Ok(value);
281
14778006
    }
282
14778006
    match lookup(name) {
283
14778006
        Some(spec) => (spec.eval)(symbols, args),
284
        None => Err(Error::Compile(format!(
285
            "special form '{name}' not yet implemented"
286
        ))),
287
    }
288
14785147
}
289

            
290
1531047
pub(super) fn compile(
291
1531047
    ctx: &mut CompileContext,
292
1531047
    emit: &mut FunctionEmitter,
293
1531047
    symbols: &mut SymbolTable,
294
1531047
    name: &str,
295
1531047
    args: &[Expr],
296
1531047
) -> Result<()> {
297
1531047
    debug!(special_form = %name, args = args.len(), "compiling special form");
298
1531047
    let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
299
490
        compile(ctx, emit, symbols, name, args)
300
490
    })?;
301
1530824
    if let Some(value) = rewritten {
302
269
        return Ok(value);
303
1530555
    }
304
1530555
    match lookup(name) {
305
1530555
        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
1531047
}
311

            
312
/// Runs a special form's codegen; a definition's goes through the one place
313
/// that flags the slots it filled.
314
2700742
fn run(
315
2700742
    ctx: &mut CompileContext,
316
2700742
    emit: &mut FunctionEmitter,
317
2700742
    symbols: &mut SymbolTable,
318
2700742
    name: &str,
319
2700742
    args: &[Expr],
320
2700742
    compile: CompileFn,
321
2700742
) -> Result<()> {
322
2700742
    match DEFINITION_FORMS.contains(&name) {
323
1857779
        true => definition::compile_definition(ctx, emit, symbols, name, args, compile),
324
842963
        false => compile(ctx, emit, symbols, args),
325
    }
326
2700742
}
327

            
328
1172881
pub(super) fn compile_for_effect(
329
1172881
    ctx: &mut CompileContext,
330
1172881
    emit: &mut FunctionEmitter,
331
1172881
    symbols: &mut SymbolTable,
332
1172881
    name: &str,
333
1172881
    args: &[Expr],
334
1172881
) -> Result<()> {
335
1172881
    let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
336
2694
        compile_for_effect(ctx, emit, symbols, name, args)
337
2694
    })?;
338
1172670
    if let Some(value) = rewritten {
339
2483
        return Ok(value);
340
1170187
    }
341
1170187
    match lookup(name) {
342
1170187
        Some(spec) => run(
343
1170187
            ctx,
344
1170187
            emit,
345
1170187
            symbols,
346
1170187
            name,
347
1170187
            args,
348
1170187
            spec.effect.unwrap_or(spec.compile),
349
1170187
        ),
350
        None => Err(Error::Compile(format!(
351
            "special form '{name}' not yet implemented"
352
        ))),
353
    }
354
1172881
}
355

            
356
419
fn cannot_produce_stack(name: &str) -> Error {
357
419
    Error::Compile(format!("special form '{name}' cannot produce stack value"))
358
419
}
359

            
360
1829257
pub(super) fn compile_for_stack(
361
1829257
    ctx: &mut CompileContext,
362
1829257
    emit: &mut FunctionEmitter,
363
1829257
    symbols: &mut SymbolTable,
364
1829257
    name: &str,
365
1829257
    args: &[Expr],
366
1829257
) -> Result<WasmType> {
367
1829257
    let rewritten = through_rewrite(symbols, name, args, |symbols, name, args| {
368
1872
        compile_for_stack(ctx, emit, symbols, name, args)
369
1872
    })?;
370
1828961
    if let Some(value) = rewritten {
371
1580
        return Ok(value);
372
1827381
    }
373
1827381
    match lookup(name) {
374
1827377
        Some(spec) => match spec.stack {
375
1826324
            Some(f) => f(ctx, emit, symbols, args),
376
1053
            None if DEFINITION_FORMS.contains(&name) => {
377
1053
                binding::reject_lexical_definition(symbols, name, args)?;
378
1045
                reject_definition_under_runtime_guard(symbols, name)?;
379
419
                Err(cannot_produce_stack(name))
380
            }
381
            None => Err(cannot_produce_stack(name)),
382
        },
383
4
        None => Err(Error::Compile(format!(
384
4
            "special form '{name}' not yet implemented"
385
4
        ))),
386
    }
387
1829257
}
388

            
389
#[cfg(test)]
390
mod tests {
391
    use super::*;
392
    use std::collections::HashSet;
393

            
394
    #[test]
395
1
    fn registry_names_unique() {
396
1
        let mut seen = HashSet::new();
397
9
        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
398
43
            assert!(
399
43
                seen.insert(spec.name),
400
                "duplicate special-form registration: {}",
401
                spec.name
402
            );
403
        }
404
1
    }
405

            
406
    #[test]
407
1
    fn registry_lookup_covers_every_entry() {
408
9
        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
409
43
            assert!(
410
43
                lookup(spec.name).is_some(),
411
                "lookup({}) returned None",
412
                spec.name
413
            );
414
        }
415
1
    }
416

            
417
    #[test]
418
1
    fn set_place_rejects_a_new_builtin_global() {
419
1
        let mut symbols = SymbolTable::new();
420
1
        let place = Expr::Symbol("LIST".to_string());
421
1
        let result = setf_set_place(&mut symbols, &place, Expr::Nil);
422
1
        assert!(matches!(result, Err(Error::Compile(msg)) if msg.contains("built-in")));
423
1
        assert!(symbols.lookup("LIST").is_none());
424
1
    }
425

            
426
    #[test]
427
1
    fn set_place_defines_a_new_plain_global_and_updates_it() {
428
1
        let mut symbols = SymbolTable::new();
429
1
        let place = Expr::Symbol("G".to_string());
430
1
        assert!(matches!(
431
1
            setf_set_place(&mut symbols, &place, Expr::Nil),
432
            Ok(Expr::Nil)
433
        ));
434
1
        assert!(symbols.lookup("G").is_some());
435
1
        assert!(matches!(
436
1
            setf_set_place(&mut symbols, &place, Expr::Nil),
437
            Ok(Expr::Nil)
438
        ));
439
1
    }
440
}