1
//! Expression-level compile + eval dispatch.
2
//!
3
//! Split into topic-focused submodules so each file stays under the
4
//! ~500-line CLAUDE.md guideline:
5
//! - [`atoms`] — primitive emit (nil, bool, number, string, symbol,
6
//!   push_ratio) and the `compile_text` plumbing they share.
7
//! - [`compile`] — the generic `compile_expr` / `compile_quoted_expr`
8
//!   dispatch + `serialize_stack_to_output`.
9
//! - [`effect`] — effect-position codegen (`compile_for_effect` plus
10
//!   the SETF / IF specialisations it owns).
11
//! - [`stack`] — stack-position codegen (`compile_for_stack` and the
12
//!   ratio/numeric refinements).
13
//! - [`call`] — function call dispatch (symbol calls, lambda calls,
14
//!   lambda-param binding).
15
//! - [`eval`] — eval-only path (`call`, `eval_value`, `dispatch_symbol`,
16
//!   macro expansion, `resolve_arg`).
17
//! - [`eval_lambda`] — `eval`'s `call_lambda` and its parameter-binding
18
//!   helpers (required / optional / rest / key / aux).
19
//! - [`quasiquote`] — quasiquote / unquote expansion.
20
//! - [`format`] — debug/display formatting for Expr and RuntimeValue.
21
//!
22
//! `LOCAL_*` indices, `compile_program`, and the two `compile_body*`
23
//! helpers stay here in `mod.rs` since they're the cross-submodule
24
//! glue every entry point lands on.
25

            
26
mod any_call;
27
mod atoms;
28
mod boxing;
29
mod call;
30
mod call_runtime;
31
mod closure_factory;
32
mod compile;
33
mod default_check;
34
mod effect;
35
mod eval;
36
mod eval_lambda;
37
pub(crate) mod fold;
38
mod format;
39
mod index_literals;
40
mod lambda_params;
41
mod local_cell;
42
mod operand;
43
mod printed_datum;
44
mod quasiquote;
45
mod respecialise;
46
mod ret_guess;
47
mod serialize_struct;
48
mod serialize_value;
49
mod stack;
50

            
51
use crate::ast::{Expr, Program, WasmType};
52
use crate::error::{Error, Result};
53
use crate::runtime::SymbolTable;
54

            
55
use super::CompileMode;
56
use super::context::CompileContext;
57
use super::emit::FunctionEmitter;
58
use super::special::allocate_instances;
59

            
60
// Reserved local-pool indices the compiler relies on across codegen
61
// paths. The output-base + GC-array slots come first so they're
62
// available before the `next_local` allocator kicks in. See
63
// `CompileContext::build_locals_declaration` for the matching wasm-
64
// side declaration.
65
pub const LOCAL_GC_ARR: u32 = 0;
66
pub const LOCAL_IDX: u32 = 1;
67
pub const LOCAL_OUTPUT_BASE: u32 = 2;
68
pub const LOCAL_TEMP_RATIO: u32 = 3;
69
pub const LOCAL_TEMP_I32: u32 = 4;
70
/// Absolute address of the entity currently being written to the output
71
/// buffer (`output_base + next_write_pos`). Every output writer positions its
72
/// entity header + data fields relative to this so writes APPEND at the runtime
73
/// `next_write_pos` — the single output protocol that lets compile-time-known
74
/// writes (a program result) and dynamic-count writes (a `create-tag` loop)
75
/// share one buffer without overwriting each other.
76
pub const LOCAL_ENTITY_BASE: u32 = 5;
77

            
78
// Submodule re-exports. Keeps `super::expr::<name>` callers stable
79
// across the refactor so neighbouring modules (`native`, `special`,
80
// the compiler root) don't have to learn the submodule layout.
81
pub(super) use any_call::fill_any_call_helpers;
82
pub(super) use atoms::{compile_nil, compile_string, compile_t, emit_nil_default, push_ratio};
83
pub(super) use boxing::{emit_box_anyref, emit_box_cell};
84
pub(super) use call::compile_call;
85
pub(in crate::compiler) use call::{applying_lambda, call_place, pin_hint};
86
pub(in crate::compiler) use closure_factory::{close_factory_call, reject_unbound_capture};
87
pub(super) use compile::{compile_expr, serialize_stack_to_output};
88
pub(super) use effect::compile_for_effect;
89
pub(super) use operand::{
90
    always_raises, compile_diverging_to_end, compile_index_operand, compile_raising,
91
    compile_raising_to_end, compile_ratio_operand, compile_to_local,
92
};
93
pub(super) use stack::{
94
    NilRepr, classify_stack_type, compile_call_for_stack, compile_for_stack, compile_for_stack_as,
95
    compile_for_stack_expecting, index_literal, is_quoted_datum, list_datum_members, nil_repr,
96
    no_list_cell_representation, push_number, quoted_datum, string_designator,
97
};
98

            
99
pub(crate) use eval::{call, eval_value, expand_macro, expand_macro_then};
100
pub(crate) use fold::{
101
    DIVISION_BY_ZERO, describe_operand, fold_call, fold_safe, fold_safe_under, fold_value,
102
    is_division_by_zero, is_instance_leaf, is_probe_rejection, is_untyped, probe_value, reads_only,
103
};
104
pub use format::format_form;
105
pub(crate) use format::{format_datum, format_expr};
106
pub(crate) use index_literals::reject_unindexable_literals;
107
pub(in crate::compiler) use local_cell::{
108
    bind_local, emit_local_read, emit_place_read, store_begin, store_begin_place, store_end,
109
    store_end_place,
110
};
111
pub(in crate::compiler) use ret_guess::recursive_ret_guess;
112

            
113
/// A list member handed out as a value: every member that is not
114
/// self-evaluating (a symbol, a non-empty list, a cons, a quote form, which is
115
/// the list `(QUOTE x)`) is a `Datum`. The one value representation of list
116
/// data on the eval surface.
117
29668397
pub(crate) fn member_value(member: Expr) -> Expr {
118
29668397
    match member {
119
        Expr::Symbol(_) | Expr::List(_) | Expr::Cons(_, _) | Expr::Quote(_) => {
120
744383
            Expr::quoted(member.into_datum_member())
121
        }
122
28924014
        other => other,
123
    }
124
29668397
}
125

            
126
/// An already-resolved value re-entering `call` as an argument: a symbol or a
127
/// list is data there, so it is quoted rather than evaluated a second time.
128
670545
pub(crate) fn as_literal_arg(expr: &Expr) -> Expr {
129
670545
    match expr {
130
9995
        Expr::Symbol(_) | Expr::List(_) | Expr::Cons(_, _) => Expr::quoted(expr.clone()),
131
660550
        _ => expr.clone(),
132
    }
133
670545
}
134

            
135
/// Scans the unit's text for the globals it writes, before any form of it
136
/// compiles (0014 §Stores to globals).
137
2352279
pub(in crate::compiler) fn prepare_unit(
138
2352279
    symbols: &mut SymbolTable,
139
2352279
    unit: &[Expr],
140
2352279
    mode: CompileMode,
141
2352279
) -> Result<fold::stores::StoreScan> {
142
2352279
    index_literals::reject_unindexable_literals(unit)?;
143
2352244
    symbols.expire_homes();
144
2352244
    let scan = fold::stores::scan_stores(symbols, unit, mode)?;
145
2341817
    let (stored, possibly, opaque) = scan.measures();
146
2341817
    symbols
147
2341817
        .measurements()
148
2341817
        .note_store_scan(stored as u64, possibly, opaque as u64);
149
2341817
    symbols.snapshot_pre_unit(scan.written_names());
150
2341817
    symbols.set_stored_globals(scan.stores());
151
2341817
    symbols.set_unit_specials(scan.defined(), scan.dynamic());
152
2341817
    Ok(scan)
153
2352279
}
154

            
155
/// Prepares the unit and makes a cell of every global it writes.
156
2352062
pub(in crate::compiler) fn begin_unit(
157
2352062
    ctx: &mut CompileContext,
158
2352062
    emit: &mut FunctionEmitter,
159
2352062
    symbols: &mut SymbolTable,
160
2352062
    unit: &[Expr],
161
2352062
    mode: CompileMode,
162
2352062
) -> Result<()> {
163
2352062
    symbols.forget_closure_deps();
164
2352062
    let scan = prepare_unit(symbols, unit, mode)?;
165
2341600
    allocate_instances(ctx, emit, symbols, &scan)
166
2352062
}
167

            
168
1616929
pub fn compile_program(
169
1616929
    ctx: &mut CompileContext,
170
1616929
    emit: &mut FunctionEmitter,
171
1616929
    symbols: &mut SymbolTable,
172
1616929
    program: &Program,
173
1616929
) -> Result<()> {
174
1616929
    ctx.serializer().begin_output(emit);
175
1616929
    begin_unit(ctx, emit, symbols, &program.exprs, CompileMode::Script)?;
176
1606698
    compile_unit_forms(ctx, emit, symbols, program)
177
1616929
}
178

            
179
1606698
fn compile_unit_forms(
180
1606698
    ctx: &mut CompileContext,
181
1606698
    emit: &mut FunctionEmitter,
182
1606698
    symbols: &mut SymbolTable,
183
1606698
    program: &Program,
184
1606698
) -> Result<()> {
185
1606698
    let Some((last, init)) = program.exprs.split_last() else {
186
1
        compile_nil(ctx, emit)?;
187
1
        return Ok(());
188
    };
189
2293767
    let has_trigger = program.exprs.iter().any(|e| {
190
2293767
        matches!(
191
2293767
            e,
192
            Expr::List(elems)
193
2228362
                if matches!(elems.first(), Some(Expr::Symbol(name)) if name == "DEFUN")
194
447847
                && matches!(elems.get(1), Some(Expr::Symbol(name)) if name == "SHOULD-APPLY")
195
        )
196
2293767
    });
197
1606697
    if has_trigger {
198
12074
        for expr in &program.exprs {
199
46435
            compile_for_effect(ctx, emit, symbols, expr)?;
200
        }
201
12074
        Ok(())
202
    } else {
203
1594623
        for expr in init {
204
681828
            compile_for_effect(ctx, emit, symbols, expr)?;
205
        }
206
1568006
        compile_expr(ctx, emit, symbols, last)?;
207
1446131
        Ok(())
208
    }
209
1606698
}
210

            
211
337564
pub(in crate::compiler) fn compile_body(
212
337564
    ctx: &mut CompileContext,
213
337564
    emit: &mut FunctionEmitter,
214
337564
    symbols: &mut SymbolTable,
215
337564
    body: &[Expr],
216
337564
) -> Result<()> {
217
337564
    let (last, init) = body
218
337564
        .split_last()
219
        .ok_or_else(|| Error::Compile("empty body".to_string()))?;
220
337564
    for expr in init {
221
72067
        compile_for_effect(ctx, emit, symbols, expr)?;
222
    }
223
329139
    compile_expr(ctx, emit, symbols, last)
224
337564
}
225

            
226
685034
pub(in crate::compiler) fn compile_body_for_stack(
227
685034
    ctx: &mut CompileContext,
228
685034
    emit: &mut FunctionEmitter,
229
685034
    symbols: &mut SymbolTable,
230
685034
    body: &[Expr],
231
685034
) -> Result<WasmType> {
232
685034
    let (last, init) = body
233
685034
        .split_last()
234
        .ok_or_else(|| Error::Compile("empty body".to_string()))?;
235
685034
    for expr in init {
236
245015
        compile_for_effect(ctx, emit, symbols, expr)?;
237
    }
238
671807
    compile_for_stack(ctx, emit, symbols, last)
239
685034
}