1
mod arithmetic;
2
mod comparison;
3
mod convert;
4
pub(in crate::compiler) mod designator_class;
5
mod entity;
6
mod error_object;
7
pub(in crate::compiler) mod function_operand;
8
mod host_fn;
9
mod io;
10
mod list;
11
pub(in crate::compiler) mod nullable;
12
mod sign;
13
mod string;
14
mod struct_runtime;
15
mod symbol;
16
mod the;
17
mod typed_entity;
18
#[cfg(test)]
19
mod typed_entity_tests;
20

            
21
use super::context::CompileContext;
22
use super::emit::FunctionEmitter;
23
use crate::ast::{Expr, WasmType};
24
use crate::error::{Error, Result};
25
use crate::runtime::SymbolTable;
26

            
27
pub(in crate::compiler) use comparison::same_datum;
28
pub(in crate::compiler) use host_fn::compile_host_fn_for_effect;
29
pub(super) use host_fn::compile_host_fn_for_stack;
30
pub(super) use io::compile_debug_effect;
31
pub(super) use io::{compile_display_effect, compile_newline_effect, compile_print_effect};
32
pub(in crate::compiler) use list::{
33
    chain_pair_element, coerce_anyref_to_pair, compile_constant_list, compile_pair_chain,
34
    emit_pair_car_downcast, literal_pair_element, push_anyref_arm, push_anyref_car,
35
    push_constant_arm, runtime_cell_slot,
36
};
37
pub(in crate::compiler) use struct_runtime::{
38
    COPY as STRUCT_COPY, NEW as STRUCT_NEW, P as STRUCT_P, REF as STRUCT_REF, SET as STRUCT_SET,
39
};
40
pub(in crate::compiler) use the::{Target, emit_narrow, the_result_type};
41

            
42
/// Eval-time handler — folds constants, surfaces a `WasmRuntime` /
43
/// `WasmLocal` stand-in when arguments aren't fully known, validates
44
/// arity. Required for every native; the compile paths build on top.
45
pub(super) type EvalFn = fn(&mut SymbolTable, &[Expr]) -> Result<Expr>;
46

            
47
/// Stack-producing codegen — emits wasm that leaves the form's result
48
/// on the wasm operand stack and returns its `WasmType`. Required for
49
/// natives that compose as sub-expressions (CONS in `(+ x (car xs))`,
50
/// every arithmetic op, entity accessors). Natives whose result has
51
/// no single stack representation (CREATE-TAG, DELETE-ENTITY, MAP)
52
/// set this to `None` — the dispatcher refuses with a structured error.
53
pub(super) type StackFn =
54
    fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<WasmType>;
55

            
56
/// Effect codegen — emits wasm at the top-level / for-effect position.
57
/// Most natives derive this from `stack` by emitting the stack form and
58
/// piping the result through the debug serializer; effect-only natives
59
/// (DEBUG side-effects, MAP folded at compile time) supply their own.
60
pub(super) type EffectFn =
61
    fn(&mut CompileContext, &mut FunctionEmitter, &mut SymbolTable, &[Expr]) -> Result<()>;
62

            
63
/// Canonical metadata for a built-in native fn. Every name appears
64
/// exactly once across the three dispatch paths — adding a new native
65
/// adds one row, and a missing handler is a compile-time error.
66
/// Replaces the three parallel hand-maintained match tables that
67
/// diverged silently before P3a 3a.3.
68
///
69
/// `effect: None` auto-derives the effect path as `stack + serialize`
70
/// — useful for the ~20 natives whose effect codegen is exactly
71
/// "produce the value on the stack, then debug-serialize". Natives
72
/// with custom effect logic (const-fold short-circuits that write
73
/// to output directly, structure forms, etc.) supply an explicit
74
/// EffectFn. `effect: None` requires `stack: Some(_)` — the
75
/// dispatcher refuses an `effect = None, stack = None` spec.
76
pub(super) struct NativeSpec {
77
    pub name: &'static str,
78
    pub eval: EvalFn,
79
    pub stack: Option<StackFn>,
80
    pub effect: Option<EffectFn>,
81
}
82

            
83
const DOMAINS: &[&[NativeSpec]] = &[
84
    arithmetic::NATIVES,
85
    comparison::NATIVES,
86
    convert::NATIVES,
87
    sign::NATIVES,
88
    list::NATIVES,
89
    list::SEARCH_NATIVES,
90
    entity::NATIVES,
91
    typed_entity::NATIVES,
92
    struct_runtime::NATIVES,
93
    string::NATIVES,
94
    symbol::NATIVES,
95
    the::NATIVES,
96
    io::NATIVES,
97
    error_object::NATIVES,
98
];
99

            
100
/// Every native name the compiler can lower; the runtime symbol table defines
101
/// the ones the builtin reference does not list from this single source.
102
3065022
pub(crate) fn registered_names() -> impl Iterator<Item = &'static str> {
103
324892332
    DOMAINS.iter().flat_map(|d| d.iter()).map(|spec| spec.name)
104
3065022
}
105

            
106
54975785
fn lookup(name: &str) -> Option<&'static NativeSpec> {
107
54975785
    DOMAINS
108
54975785
        .iter()
109
144344625
        .flat_map(|d| d.iter())
110
625786318
        .find(|s| s.name == name)
111
54975785
}
112

            
113
49926466
pub(super) fn call(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
114
49926466
    match lookup(name) {
115
49926466
        Some(spec) => (spec.eval)(symbols, args),
116
        None => Err(Error::Compile(format!(
117
            "native function '{}' not yet implemented",
118
            name
119
        ))),
120
    }
121
49926466
}
122

            
123
6358704
pub(super) fn compile_for_stack(
124
6358704
    ctx: &mut CompileContext,
125
6358704
    emit: &mut FunctionEmitter,
126
6358704
    symbols: &mut SymbolTable,
127
6358704
    name: &str,
128
6358704
    args: &[Expr],
129
6358704
) -> Result<WasmType> {
130
6358704
    if ctx.lookup_host_fn(name).is_some() {
131
1560193
        return compile_host_fn_for_stack(ctx, emit, symbols, name, args);
132
4798511
    }
133
4798511
    match lookup(name) {
134
4798511
        Some(spec) => match spec.stack {
135
4798511
            Some(f) => f(ctx, emit, symbols, args),
136
            None => Err(stackless_error(name)),
137
        },
138
        None => Err(Error::Compile(format!(
139
            "native function '{}' not yet implemented",
140
            name
141
        ))),
142
    }
143
6358704
}
144

            
145
/// A native with no value form used as a value is a compile error.
146
fn stackless_error(name: &str) -> Error {
147
    Error::Compile(format!(
148
        "native function '{}' cannot produce stack value",
149
        name
150
    ))
151
}
152

            
153
250670
pub(super) fn compile(
154
250670
    ctx: &mut CompileContext,
155
250670
    emit: &mut FunctionEmitter,
156
250670
    symbols: &mut SymbolTable,
157
250670
    name: &str,
158
250670
    args: &[Expr],
159
250670
) -> Result<()> {
160
250670
    if let Some(entry) = ctx.lookup_host_fn(name) {
161
        // Output position: a result is written like any native's; a host fn
162
        // without one has nothing to write.
163
12
        if entry.result.is_none() {
164
            return compile_host_fn_for_effect(ctx, emit, symbols, name, args);
165
12
        }
166
12
        let ty = compile_host_fn_for_stack(ctx, emit, symbols, name, args)?;
167
12
        return crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty);
168
250658
    }
169
250658
    match lookup(name) {
170
250658
        Some(spec) => match spec.effect {
171
143121
            Some(f) => f(ctx, emit, symbols, args),
172
107537
            None => derived_effect(ctx, emit, symbols, name, args, spec),
173
        },
174
        None => Err(Error::Compile(format!(
175
            "native function '{}' not yet implemented",
176
            name
177
        ))),
178
    }
179
250670
}
180

            
181
/// Default effect path for natives with `effect: None`: compile via
182
/// the stack handler, then debug-serialize the result. Same shape as
183
/// the ~20 wrapper fns this replaces. Refuses if the spec also lacks
184
/// a stack handler — that's a programmer error in the registry, and
185
/// the registry test enforces "effect None implies stack Some".
186
107537
fn derived_effect(
187
107537
    ctx: &mut CompileContext,
188
107537
    emit: &mut FunctionEmitter,
189
107537
    symbols: &mut SymbolTable,
190
107537
    name: &str,
191
107537
    args: &[Expr],
192
107537
    spec: &NativeSpec,
193
107537
) -> Result<()> {
194
107537
    let stack_fn = spec.stack.ok_or_else(|| {
195
        Error::Compile(format!(
196
            "native function '{name}' has neither effect nor stack handler"
197
        ))
198
    })?;
199
107537
    let ty = stack_fn(ctx, emit, symbols, args)?;
200
95881
    super::expr::serialize_stack_to_output(ctx, emit, ty)?;
201
95881
    Ok(())
202
107537
}
203

            
204
#[cfg(test)]
205
mod tests {
206
    use super::*;
207
    use crate::SymbolKind;
208
    use std::collections::HashSet;
209

            
210
    #[test]
211
1
    fn registry_names_unique() {
212
1
        let mut seen = HashSet::new();
213
14
        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
214
106
            assert!(
215
106
                seen.insert(spec.name),
216
                "duplicate native registration: {}",
217
                spec.name
218
            );
219
        }
220
1
    }
221

            
222
    #[test]
223
1
    fn registry_lookup_covers_every_entry() {
224
        // Every registered name must be reachable via the lookup helper —
225
        // catches accidental shadowing if a domain reorders its slice.
226
14
        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
227
106
            assert!(
228
106
                lookup(spec.name).is_some(),
229
                "lookup({}) returned None",
230
                spec.name
231
            );
232
        }
233
1
    }
234

            
235
    #[test]
236
1
    fn registry_none_effect_implies_some_stack() {
237
        // Auto-derived effect path needs the stack handler — a spec with
238
        // both None is a registry programmer error that the dispatcher
239
        // can only surface at runtime. Catch at unit-test time.
240
14
        for spec in DOMAINS.iter().flat_map(|d| d.iter()) {
241
106
            if spec.effect.is_none() {
242
74
                assert!(
243
74
                    spec.stack.is_some(),
244
                    "native {} has neither effect nor stack handler",
245
                    spec.name
246
                );
247
32
            }
248
        }
249
1
    }
250

            
251
    /// Every native NAME the reader registers as a builtin (tangled from
252
    /// `builtin_reference.org` into `builtins_generated::NATIVES`) must have a
253
    /// codegen handler reachable via `lookup`. Without this guard a documented
254
    /// native can exist as a symbol the reader accepts yet codegen rejects with
255
    /// "native function '…' not yet implemented" — the "phantom native" class
256
    /// that hid EQUAL?/EQ?/LENGTH/APPEND/PAIR?/PRINT/DISPLAY/NEWLINE until a
257
    /// script happened to call one. The samples are parse-only, so only this
258
    /// test (and real compile coverage) catches the gap.
259
    #[test]
260
1
    fn every_builtin_native_name_has_a_handler() {
261
1
        for name in crate::runtime::registered_native_names() {
262
44
            assert!(
263
44
                lookup(name).is_some(),
264
                "builtin native '{name}' is registered as a symbol but has no \
265
                 codegen handler — add a NativeSpec or remove it from the registry"
266
            );
267
        }
268
1
    }
269

            
270
    /// Every native the compiler registers is a runtime symbol, and every
271
    /// native-kind runtime symbol has a compiler registration.
272
    #[test]
273
1
    fn runtime_native_symbols_equal_compiler_natives() {
274
1
        let table = SymbolTable::with_builtins();
275
1
        let compiler: HashSet<&str> = registered_names().collect();
276
1
        for name in &compiler {
277
106
            assert!(table.contains(name), "native '{name}' is not a symbol");
278
        }
279
1
        for (name, symbol) in table.iter() {
280
172
            if symbol.kind() == SymbolKind::Native {
281
95
                assert!(
282
95
                    compiler.contains(name.as_str()),
283
                    "symbol '{name}' has no native"
284
                );
285
77
            }
286
        }
287
1
    }
288
}