1
//! Eval-only path — value-level interpretation that runs at compile
2
//! time for constant folding, macro expansion, and the type-inference
3
//! peek-ahead. `eval_value` is the entry point; everything else here
4
//! exists to support it.
5
//!
6
//! Distinct from the codegen path: `eval_value` doesn't emit any
7
//! wasm. The codegen entry points in [`super::compile`] /
8
//! [`super::effect`] / [`super::stack`] are the ones that produce
9
//! bytes; they use `eval_value` to decide whether a form is
10
//! constant-foldable or needs runtime emit.
11

            
12
use crate::ast::{ClosureSigId, Expr, KeyParam, LambdaParams, Place, WasmType};
13
use crate::error::{Error, Result};
14
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable, with_sufficient_stack};
15

            
16
use super::call::{CallTarget, applying_lambda, call_target};
17
use super::eval_lambda::{call_lambda, check_keyword_args, find_keyword_value};
18
use super::format::not_callable;
19
use super::member_value;
20
use super::quasiquote::{quasiquote_datum, quasiquote_form};
21
use super::respecialise::respecialised;
22
use crate::compiler::native::designator_class::is_function_name;
23
use crate::compiler::native::function_operand::unbound;
24

            
25
67118876
pub(crate) fn call(symbols: &mut SymbolTable, elems: &[Expr]) -> Result<Expr> {
26
67118876
    let (head, args) = elems
27
67118876
        .split_first()
28
        .ok_or_else(|| Error::Compile("empty function call".to_string()))?;
29
67118876
    match head {
30
66049160
        Expr::Symbol(name) => dispatch_symbol(symbols, name, args),
31
44291
        Expr::Datum(inner) => match inner.as_ref() {
32
44291
            Expr::Symbol(name) => dispatch_symbol(symbols, name, args),
33
            _ => Err(not_callable(head)),
34
        },
35
738440
        Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
36
736343
            call_lambda(symbols, params, body, args, None)
37
736343
        }),
38
        Expr::List(inner) => {
39
226105
            let resolved = call(symbols, inner)?;
40
225441
            match resolved {
41
212305
                Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
42
212293
                    call_lambda(symbols, &params, &body, args, None)
43
212293
                }),
44
13136
                value => call_value(symbols, head, &value, args),
45
            }
46
        }
47
60880
        value => call_value(symbols, head, value, args),
48
    }
49
67118876
}
50

            
51
/// The call of the function value `value`, which `head` evaluated to.
52
74016
fn call_value(symbols: &mut SymbolTable, head: &Expr, value: &Expr, args: &[Expr]) -> Result<Expr> {
53
74016
    match value {
54
53345
        Expr::WasmLocal(..) | Expr::WasmGlobal(..) => match call_target(value) {
55
            Some(CallTarget::Closure(place, sig)) => {
56
49992
                eval_closure_call(symbols, place, sig, args)?.ok_or_else(|| not_callable(head))
57
            }
58
2729
            Some(CallTarget::Any(_)) => Ok(Expr::WasmRuntime(WasmType::AnyRef)),
59
624
            None => Err(not_callable(head)),
60
        },
61
1464
        Expr::WasmRuntime(WasmType::Closure(sig)) => symbols
62
1464
            .closure_result(*sig)
63
1464
            .map(Expr::WasmRuntime)
64
209
            .ok_or_else(|| not_callable(head)),
65
9999
        Expr::WasmRuntime(WasmType::AnyRef) => Ok(Expr::WasmRuntime(WasmType::AnyRef)),
66
9208
        _ => Err(not_callable(head)),
67
    }
68
74016
}
69

            
70
745301170
pub(crate) fn eval_value(symbols: &mut SymbolTable, expr: &Expr) -> Result<Expr> {
71
745301170
    with_sufficient_stack(|| {
72
        // Charged on every call, including on the disposable clones classification
73
        // probes evaluate against, so a form whose test re-evaluates its own
74
        // nested test (e.g. COND's constant-test probe) is bounded by the shared
75
        // budget rather than by however many times the recursion happens to fan
76
        // out (plan 0011 Phase 0; row E / C_30).
77
745301170
        symbols.charge_work(1)?;
78
745300744
        symbols.measurements().note_walk();
79
745300744
        let value = match expr {
80
65473477
            Expr::List(elems) if !elems.is_empty() => {
81
65473477
                let value = call(symbols, elems)?;
82
59013669
                if !value.is_wasm_runtime() {
83
42401452
                    symbols.measurements().note_fold();
84
16612217
                }
85
59013669
                value
86
            }
87
633838
            Expr::Quasiquote(inner) if !symbols.is_macro_expansion() => {
88
142
                eval_quasiquote(symbols, inner)?
89
            }
90
679827125
            _ => resolve_arg(symbols, expr)?,
91
        };
92
738787039
        if value.is_wasm_runtime() {
93
28904395
            symbols.note_runtime_value();
94
709882644
        }
95
738787039
        Ok(value)
96
745301170
    })
97
745301170
}
98

            
99
/// Kept out of line so the hot `eval_value` recursion keeps its small frame.
100
#[inline(never)]
101
142
fn eval_quasiquote(symbols: &mut SymbolTable, template: &Expr) -> Result<Expr> {
102
142
    eval_value(symbols, &quasiquote_form(template)?)
103
142
}
104

            
105
/// A variable read as a value: inside a macro body list data is in value form.
106
/// Kept out of line so the hot `resolve_arg` keeps its small frame.
107
#[inline(never)]
108
56208361
fn read_value(expanding: bool, value: Expr) -> Expr {
109
56208361
    if expanding {
110
28823444
        member_value(value)
111
    } else {
112
27384917
        value
113
    }
114
56208361
}
115

            
116
66093451
fn dispatch_symbol(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
117
66093451
    match symbols.resolve_head(name) {
118
        Head::Macro(params, body) => {
119
165548
            let (params, body) = (params.clone(), body.clone());
120
165548
            expand_macro_then(symbols, &params, &body, args, |symbols, code| {
121
161263
                eval_value(symbols, &code)
122
161263
            })
123
        }
124
        Head::Function(params, body) => {
125
1957818
            let (params, body) = (params.clone(), body.clone());
126
1957818
            call_user_function(symbols, name, &params, &body, args)
127
        }
128
54768655
        Head::Native => call_native(symbols, name, args),
129
9192977
        Head::SpecialForm => crate::compiler::special::call(symbols, name, args),
130
8453
        Head::Unknown if symbols.contains(name) => Err(symbols.not_callable(name, "")),
131
6979
        Head::Unknown => Err(Error::undefined_symbol(name)),
132
    }
133
66093451
}
134

            
135
/// The eval surface of a closure call: the source's value when an argument does
136
/// not fit the emitted signature, else the signature's recorded result.
137
49992
fn eval_closure_call(
138
49992
    symbols: &mut SymbolTable,
139
49992
    place: Place,
140
49992
    sig: ClosureSigId,
141
49992
    args: &[Expr],
142
49992
) -> Result<Option<Expr>> {
143
49992
    let params = symbols.closure_params(sig).map(<[WasmType]>::to_vec);
144
49992
    if let Some(params) = params
145
49941
        && let Some((params, body)) = respecialised(symbols, place, &params, args)?
146
    {
147
1334
        return symbols
148
1334
            .within_shared_recursion(|symbols| call_lambda(symbols, &params, &body, args, None))
149
1334
            .map(Some);
150
48658
    }
151
48658
    Ok(symbols.closure_result(sig).map(Expr::WasmRuntime))
152
49992
}
153

            
154
1957818
fn call_user_function(
155
1957818
    symbols: &mut SymbolTable,
156
1957818
    name: &str,
157
1957818
    params: &LambdaParams,
158
1957818
    body: &Expr,
159
1957818
    args: &[Expr],
160
1957818
) -> Result<Expr> {
161
    // A (mutually) recursive defun re-entered with a runtime arg never
162
    // folds to a base case — inlining it again would recurse the
163
    // compiler's stack forever. Hand it to the codegen monomorph path by
164
    // surfacing a runtime placeholder of the call's inferred result type;
165
    // the inline depth guard below is the backstop for any recursion the
166
    // re-entry check misses (e.g. const recursion with no base case).
167
1957818
    if symbols.is_inlining(name)
168
71960
        && let Some(ret_ty) = recursive_runtime_call_type(symbols, name, params, body, args)?
169
    {
170
50332
        return Ok(Expr::WasmRuntime(ret_ty));
171
1907483
    }
172
1907483
    symbols.enter_inline(name)?;
173
1814741
    let result = call_lambda(symbols, params, body, args, Some(name));
174
1814741
    symbols.exit_inline()?;
175
1814741
    result
176
1957818
}
177

            
178
54768655
fn call_native(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Expr> {
179
54768655
    let stand_in = symbols
180
54768655
        .lookup(name)
181
54768655
        .and_then(Symbol::value)
182
4842189
        .filter(|value| matches!(value, Expr::WasmRuntime(_)))
183
        .cloned();
184
54768655
    let Some(stand_in) = stand_in else {
185
49926466
        return crate::compiler::native::call(symbols, name, args);
186
    };
187
    // Host-fn shim: the symbol carries the result type as a WasmRuntime
188
    // stand-in. Eval each arg so nested constant folding still runs, then
189
    // surface the stand-in as the call's value; no host-side dispatch
190
    // happens until codegen.
191
4842189
    for arg in args {
192
176592
        eval_value(symbols, arg)?;
193
    }
194
4842189
    Ok(stand_in)
195
54768655
}
196

            
197
/// The runtime result type to surface for a re-entrant recursive defun call,
198
/// or `None` when no argument resolves to a runtime value (so the call is
199
/// still const-foldable and should keep inlining). Must agree with what the
200
/// codegen monomorph path emits the helper at: both start from
201
/// `recursive_ret_guess`. Each arg is resolved on a CLONE so this probe
202
/// applies no side effects to the live table; an argument's dimension
203
/// error is the call's own.
204
71960
fn recursive_runtime_call_type(
205
71960
    symbols: &mut SymbolTable,
206
71960
    name: &str,
207
71960
    params: &LambdaParams,
208
71960
    body: &Expr,
209
71960
    args: &[Expr],
210
71960
) -> Result<Option<crate::ast::WasmType>> {
211
71960
    let mut resolved = Vec::with_capacity(args.len());
212
71960
    for arg in args {
213
97379
        match eval_value(&mut symbols.clone(), arg) {
214
97376
            Ok(value) => resolved.push(value),
215
3
            Err(err @ Error::Dimension(_)) => return Err(err),
216
            Err(_) => resolved.push(Expr::Nil),
217
        }
218
    }
219
71957
    if !resolved.iter().any(Expr::is_wasm_runtime) {
220
21625
        return Ok(None);
221
50332
    }
222
50332
    Ok(Some(super::ret_guess::recursive_ret_guess(
223
50332
        name,
224
50332
        &params.required,
225
50332
        body,
226
50332
        resolved.iter().map(super::stack::classify_stack_type),
227
50332
    )))
228
71960
}
229

            
230
/// Expand a macro call and run `process` on the resulting code, with a
231
/// depth guard spanning the whole expand-then-reprocess step. Every
232
/// expansion site (eval / effect / stack / call compile paths) routes
233
/// through here so a self-referential macro — whose re-expansion happens
234
/// inside `process` — is bounded uniformly and turned into a structured
235
/// compile error instead of a native stack overflow. The depth is carried
236
/// on the persistent `symbols` (threaded through the recursion) and
237
/// restored afterwards so sibling expansions don't accumulate.
238
551329
pub(crate) fn expand_macro_then<T>(
239
551329
    symbols: &mut SymbolTable,
240
551329
    params: &LambdaParams,
241
551329
    body: &Expr,
242
551329
    args: &[Expr],
243
551329
    process: impl FnOnce(&mut SymbolTable, Expr) -> Result<T>,
244
551329
) -> Result<T> {
245
551329
    symbols.enter_macro_expansion()?;
246
551304
    let result = expand_macro(symbols, params, body, args).and_then(|expansion| {
247
        // Charged against the shared budget per expansion instance, sized by
248
        // the expansion's own output — a macro that keeps regenerating a
249
        // large datum (or is re-expanded at many distinct call sites) is
250
        // bounded by total work produced, not merely by nesting depth.
251
542226
        symbols.charge_work(crate::compiler::datum::cost(&expansion)?)?;
252
542226
        process(symbols, expansion)
253
542226
    });
254
551304
    symbols.exit_macro_expansion()?;
255
551304
    result
256
551329
}
257

            
258
1137511
pub(crate) fn expand_macro(
259
1137511
    symbols: &mut SymbolTable,
260
1137511
    params: &LambdaParams,
261
1137511
    body: &Expr,
262
1137511
    args: &[Expr],
263
1137511
) -> Result<Expr> {
264
1137511
    if !params.aux.is_empty() {
265
        return Err(Error::Compile(
266
            "&aux not yet supported in macros".to_string(),
267
        ));
268
1137511
    }
269

            
270
1137511
    let min_args = params.required.len();
271
1137511
    let max_args = if params.rest.is_some() || !params.key.is_empty() {
272
538253
        None
273
    } else {
274
599258
        Some(min_args + params.optional.len())
275
    };
276
1137511
    if args.len() < min_args || max_args.is_some_and(|max| args.len() > max) {
277
417
        return Err(Error::Arity {
278
417
            name: "macro".to_string(),
279
417
            expected: min_args,
280
417
            actual: args.len(),
281
417
        });
282
1137094
    }
283

            
284
1137094
    if body_reads_unbound_variable(symbols, params, body) {
285
19481
        symbols.measurements().note_macro_global_read();
286
1117613
    }
287
1137094
    let mut local_symbols = symbols.clone();
288
    // The macro body evaluates in its own PRIVATE expansion environment —
289
    // a definition it registers there is discarded along with
290
    // `local_symbols` once the expansion's generated code is produced, so
291
    // it must not be rejected just because the CALL SITE happens to sit
292
    // under a runtime AND/OR/COND guard; that guard governs the GENERATED
293
    // code once it's recompiled against the caller's own table, not the
294
    // expansion machinery that produced it.
295
1137094
    local_symbols.suspend_runtime_guards();
296
    // Also marks this clone as evaluating a macro's private body: the
297
    // eval-side LET/LET* "promote a setf-mutated constant binding to
298
    // runtime, matching codegen" step (see `let_eval.rs`) must skip that
299
    // promotion here — this body is never itself codegen'd, only its
300
    // OUTPUT is, so promoting would block legitimate pure compile-time
301
    // arithmetic the macro uses to build its expansion.
302
1137094
    local_symbols.mark_macro_expansion();
303
1137094
    let mut arg_idx = 0;
304

            
305
1137094
    for param in &params.required {
306
818416
        local_symbols
307
818416
            .define(Symbol::new(param, SymbolKind::Variable).with_value(args[arg_idx].clone()));
308
818416
        arg_idx += 1;
309
    }
310

            
311
1137094
    for (param, default) in &params.optional {
312
74
        let value = if arg_idx < args.len() {
313
12
            let arg = args[arg_idx].clone();
314
12
            arg_idx += 1;
315
12
            arg
316
62
        } else if let Some(default_expr) = default {
317
62
            eval_value(&mut local_symbols, default_expr)?
318
        } else {
319
            Expr::Nil
320
        };
321
74
        local_symbols.define(Symbol::new(param, SymbolKind::Variable).with_value(value));
322
    }
323

            
324
1137094
    if let Some(rest_param) = &params.rest {
325
534232
        let rest = Expr::quoted_list(args[arg_idx..].to_vec());
326
534232
        local_symbols.define(Symbol::new(rest_param, SymbolKind::Variable).with_value(rest));
327
602862
    }
328

            
329
    // Bind key parameters in macros
330
1137094
    if !params.key.is_empty() {
331
4021
        let remaining_args = &args[arg_idx..];
332
4021
        check_keyword_args(params, remaining_args)?;
333
        for KeyParam {
334
            name: param,
335
            keyword,
336
            default,
337
3592
        } in &params.key
338
        {
339
3592
            let keyword = Expr::Keyword(keyword.clone());
340
3592
            let found_value = find_keyword_value(remaining_args, &keyword)?.cloned();
341

            
342
3592
            let value = if let Some(val) = found_value {
343
1885
                val
344
1707
            } else if let Some(default_expr) = default {
345
1278
                eval_value(&mut local_symbols, default_expr)?
346
            } else {
347
429
                Expr::Nil
348
            };
349

            
350
3592
            local_symbols.define(Symbol::new(param, SymbolKind::Variable).with_value(value));
351
        }
352
1133073
    }
353

            
354
1136665
    let code = match eval_value(&mut local_symbols, body) {
355
423
        Err(Error::Transfer { .. }) => Err(Error::Compile(
356
423
            "a macro body's RETURN-FROM escapes the expansion".to_string(),
357
423
        )),
358
1119341
        Ok(_) if local_symbols.saw_runtime_value() => Err(Error::Compile(
359
10050
            "a macro body cannot use a runtime value or effect at expansion time".to_string(),
360
10050
        )),
361
1126192
        other => other.map(Expr::into_code),
362
27374
    }?;
363
1109291
    symbols.compose_expansion(&code, args)?;
364
1101179
    Ok(code)
365
1137511
}
366

            
367
/// Whether a free symbol of the macro body — one it does not bind as a
368
/// parameter — resolves to a variable of the use-site table. Quoted data is
369
/// skipped; a symbol in head position is a call, not a read.
370
1137096
fn body_reads_unbound_variable(symbols: &SymbolTable, params: &LambdaParams, body: &Expr) -> bool {
371
1849743
    let bound = |name: &str| {
372
1979946
        params.required.iter().any(|p| p == name)
373
881269
            || params.optional.iter().any(|(p, _)| p == name)
374
881208
            || params.key.iter().any(|p| p.name == name)
375
876978
            || params.rest.as_deref() == Some(name)
376
1849743
    };
377
    let reads_variable =
378
1849743
        |name: &str| !bound(name) && symbols.lookup(name).is_some_and(Symbol::is_variable);
379
1137096
    let mut stack = vec![body];
380
427392220
    while let Some(expr) = stack.pop() {
381
426274606
        match expr {
382
1849743
            Expr::Symbol(name) if reads_variable(name) => return true,
383
1538619
            Expr::List(items) => stack.extend(items.iter().skip(1)),
384
            Expr::Cons(car, cdr) => stack.extend([car.as_ref(), cdr.as_ref()]),
385
607076
            Expr::Quasiquote(template) => stack.extend(template.unquoted_forms()),
386
            Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) | Expr::Lambda(_, inner) => {
387
                stack.push(inner);
388
            }
389
424109429
            _ => {}
390
        }
391
    }
392
1117614
    false
393
1137096
}
394

            
395
683321283
pub(crate) fn resolve_arg(symbols: &mut SymbolTable, expr: &Expr) -> Result<Expr> {
396
683321283
    match expr {
397
        Expr::Nil
398
        | Expr::T
399
        | Expr::Number(_)
400
        | Expr::String(_)
401
        | Expr::Bytes(_)
402
        | Expr::Datum(_)
403
        | Expr::Keyword(_)
404
616208351
        | Expr::RuntimeValue(_) => Ok(expr.clone()),
405
8973097
        Expr::Quote(inner) => Ok(Expr::quoted(inner.as_ref().clone())),
406
28781
        Expr::Lambda(_, _) => Ok(expr.clone()),
407
        Expr::Cons(_, _) | Expr::List(_) => Ok(expr.clone()),
408
633696
        Expr::Quasiquote(inner) if symbols.is_macro_expansion() => quasiquote_datum(symbols, inner),
409
        Expr::Quasiquote(inner) => quasiquote_form(inner),
410
        Expr::Unquote(_) | Expr::UnquoteSplicing(_) => {
411
            Err(Error::Compile("unquote outside of quasiquote".to_string()))
412
        }
413
        Expr::Symbol(name) => {
414
56274554
            let expanding = symbols.is_macro_expansion();
415
            let (value, kind, has_fn) = {
416
56274554
                let sym = symbols
417
56274554
                    .lookup(name)
418
55327
                    .ok_or_else(|| Error::undefined_symbol(name))?;
419
56219227
                let datum = sym.expansion_value().filter(|_| expanding);
420
56219227
                (
421
56219227
                    datum.or(sym.value()).cloned(),
422
56219227
                    sym.kind(),
423
56219227
                    sym.function().is_some(),
424
56219227
                )
425
            };
426
56219227
            if let Some(value) = value {
427
56208361
                return Ok(read_value(expanding, value));
428
10866
            }
429
10866
            match kind {
430
633
                SymbolKind::Native | SymbolKind::Operator => Err(unbound(symbols, name)),
431
3124
                SymbolKind::SpecialForm | SymbolKind::Macro if is_function_name(name) => {
432
3328
                    Err(unbound(symbols, name))
433
                }
434
1044
                SymbolKind::SpecialForm => Err(Error::Compile(format!(
435
1044
                    "'{name}' is a special form and cannot be used as a value"
436
1044
                ))),
437
1040
                SymbolKind::Macro => Err(Error::Compile(format!(
438
1040
                    "'{name}' is a macro and cannot be used as a value"
439
1040
                ))),
440
4821
                _ if has_fn => Err(unbound(symbols, name)),
441
4372
                _ => Err(Error::Compile(format!("symbol '{name}' has no value"))),
442
            }
443
        }
444
        Expr::WasmRuntime(_)
445
        | Expr::WasmLocal(_, _)
446
        | Expr::WasmGlobal(_, _)
447
1202804
        | Expr::Instance(_, _) => Ok(expr.clone()),
448
    }
449
683321283
}
450

            
451
#[cfg(test)]
452
#[path = "eval_tests.rs"]
453
mod tests;