1
//! `AND` / `OR` short-circuit forms (ADR-0033: they return VALUES, as in
2
//! Common Lisp, not booleans). Both walk their operands in a plain loop
3
//! (never recursing to fold a constant-only prefix — a naive recursive
4
//! rewrite would exhaust the native stack on a long flat chain, e.g. `(and
5
//! nil t t t ...)` with thousands of operands) and delegate to `if_form` /
6
//! `compile_expr` for the one genuinely-runtime `IF` a non-constant operand
7
//! needs, so test lowering (`nil_repr`), arm reconciliation and boxing have
8
//! exactly one implementation, shared with `IF` itself.
9
//!
10
//! `AND` needs no temporary: once an operand is known non-nil its own value
11
//! is never needed again (the result comes from the rest of the chain), so
12
//! a runtime operand parks in a throwaway local purely to give `if_form` a
13
//! side-effect-free test to re-read. `OR` needs a live operand's value in
14
//! both the test and the result position (`(or a b)` is "if a is non-nil,
15
//! a; else b"), so its runtime chain stores the operand in a wasm local and
16
//! embeds `Expr::WasmLocal` (the compiled case) or `Expr::WasmRuntime` (the
17
//! eval-mirror's type-only placeholder) directly into a synthetic IF —
18
//! referencing the already-computed value instead of re-evaluating it.
19
//!
20
//! A chain's constant prefix (however long) costs no native-stack
21
//! recursion at all — it's a plain `for` loop. Only a genuinely-runtime
22
//! operand recurses (once per such operand, through `if_form`'s own
23
//! "then"/"else"-branch re-entry into `and_form`/`or_form`), and that
24
//! recursion is depth-guarded (`SymbolTable::enter_runtime_guard`, charged
25
//! against `MAX_SHARED_RECURSION_DEPTH`) into a structured `Error::Resource`
26
//! rather than a native stack overflow.
27

            
28
use crate::ast::{Expr, WasmType};
29
use crate::compiler::context::CompileContext;
30
use crate::compiler::emit::FunctionEmitter;
31
use crate::compiler::expr::{
32
    classify_stack_type, compile_for_effect, compile_for_stack, eval_value, probe_value,
33
    serialize_stack_to_output,
34
};
35
use crate::error::Result;
36
use crate::runtime::SymbolTable;
37

            
38
use super::if_form;
39

            
40
/// `(AND rest...)` / `(OR rest...)` as a plain call AST node — built fresh
41
/// (not pre-evaluated) so recursing into `and_form`/`or_form` or their
42
/// stack compilers evaluates each of `rest` exactly once, lazily, exactly
43
/// like any other nested call.
44
317010
fn chain_expr(head: &str, rest: &[Expr]) -> Expr {
45
317010
    let mut items = Vec::with_capacity(rest.len() + 1);
46
317010
    items.push(Expr::Symbol(head.to_string()));
47
317010
    items.extend_from_slice(rest);
48
317010
    Expr::List(items)
49
317010
}
50

            
51
3143
pub(super) fn compile_and(
52
3143
    ctx: &mut CompileContext,
53
3143
    emit: &mut FunctionEmitter,
54
3143
    symbols: &mut SymbolTable,
55
3143
    args: &[Expr],
56
3143
) -> Result<()> {
57
3143
    let ty = compile_and_for_stack(ctx, emit, symbols, args)?;
58
2727
    serialize_stack_to_output(ctx, emit, ty)
59
3143
}
60

            
61
/// Walks `args` left to right in a plain loop: a compile-time-constant nil
62
/// operand ends the chain immediately (CL semantics — nothing after it,
63
/// including its own further operands, ever runs); a non-nil constant just
64
/// applies its effects and moves on; the first genuinely-runtime operand
65
/// parks in a throwaway local and hands the rest of the chain to `if_form`
66
/// as `(if <local> (and rest...) nil)`. The constant walk never recurses;
67
/// only the one runtime hand-off does, depth-guarded.
68
112697
pub(super) fn compile_and_for_stack(
69
112697
    ctx: &mut CompileContext,
70
112697
    emit: &mut FunctionEmitter,
71
112697
    symbols: &mut SymbolTable,
72
112697
    args: &[Expr],
73
112697
) -> Result<WasmType> {
74
112697
    let Some((last, init)) = args.split_last() else {
75
212
        return compile_for_stack(ctx, emit, symbols, &Expr::T);
76
    };
77
112485
    for (idx, operand) in init.iter().enumerate() {
78
65207
        let probe = probe_value(&mut symbols.clone(), operand)?;
79
65207
        if probe.is_wasm_runtime() {
80
63722
            if !super::is_runtime_test(&probe) {
81
                // A `Never`-repr runtime value (index / money / closure) can
82
                // never be nil — it folds true unconditionally, so it is
83
                // NOT a genuine guard: `runtime_guard_depth` must not rise
84
                // for it (a definition later in the chain would be reached
85
                // unconditionally, not under any runtime branch).
86
418
                compile_for_effect(ctx, emit, symbols, operand)?;
87
418
                continue;
88
63304
            }
89
63304
            let ty = compile_for_stack(ctx, emit, symbols, operand)?;
90
63092
            let local = ctx.alloc_local(ty)?;
91
63092
            emit.local_set(local);
92
63092
            let test = Expr::WasmLocal(local, ty);
93
63092
            let rest = chain_expr("AND", &args[idx + 1..]);
94
63092
            symbols.enter_runtime_guard()?;
95
            let result =
96
62676
                if_form::compile_if_for_stack(ctx, emit, symbols, &[test, rest, Expr::Nil]);
97
62676
            symbols.exit_runtime_guard()?;
98
62676
            return result;
99
1485
        }
100
1485
        if probe.is_nil() {
101
19
            if !matches!(operand, Expr::Nil) {
102
15
                compile_for_effect(ctx, emit, symbols, operand)?;
103
4
            }
104
19
            emit.i32_const(0);
105
19
            return Ok(WasmType::Bool);
106
1466
        }
107
1466
        compile_for_effect(ctx, emit, symbols, operand)?;
108
    }
109
49162
    compile_for_stack(ctx, emit, symbols, last)
110
112697
}
111

            
112
/// Effect-position `AND`: unlike [`compile_and_for_stack`], a definition
113
/// form (`DEFVAR`/`DEFPARAMETER`/`DEFUN`, …) has no stack lowering at all,
114
/// so this does NOT route every operand through `compile_for_stack` — only
115
/// a genuinely-runtime operand whose TRUTHINESS controls whether later
116
/// operands run needs a stack value (parked in a local, tested, and the
117
/// rest of the chain nested inside the `if`'s true arm); every other
118
/// operand, including the last, compiles for effect only. Same left-to-right
119
/// walk and constant short-circuit as the stack path, same depth guard for
120
/// the one recursive runtime hand-off.
121
16075
pub(super) fn compile_and_for_effect(
122
16075
    ctx: &mut CompileContext,
123
16075
    emit: &mut FunctionEmitter,
124
16075
    symbols: &mut SymbolTable,
125
16075
    args: &[Expr],
126
16075
) -> Result<()> {
127
16075
    let Some((last, init)) = args.split_last() else {
128
        return Ok(());
129
    };
130
16075
    for (idx, operand) in init.iter().enumerate() {
131
10228
        let probe = probe_value(&mut symbols.clone(), operand)?;
132
10228
        if probe.is_wasm_runtime() {
133
7727
            if !super::is_runtime_test(&probe) {
134
                // A `Never`-repr runtime value (index / money / closure) can
135
                // never be nil — it folds true unconditionally, so it never
136
                // gates the rest of the chain; compile it for effect only.
137
630
                compile_for_effect(ctx, emit, symbols, operand)?;
138
630
                continue;
139
7097
            }
140
            // `compile_test_condition` already compiles `operand` for its
141
            // value exactly once and converts the emitted type to a
142
            // condition — no need to separately park it in a local, wrap
143
            // that in a `WasmLocal`, and reload it through a SECOND
144
            // `compile_test_condition` call. Still runs BEFORE
145
            // `enter_runtime_guard` below, so the test's own unconditional
146
            // effects are never wrongly treated as guarded.
147
7097
            super::compile_test_condition(ctx, emit, symbols, operand)?;
148
7095
            emit.if_block(wasm_encoder::BlockType::Empty);
149
            // `enter_runtime_guard` also marks (via `runtime_guard_depth`) that
150
            // anything compiled here — however deeply nested through
151
            // IF/COND/LET/PROGN/macro expansion — is under a GENUINELY
152
            // RUNTIME guard: a definition form reached from here refuses
153
            // itself at its own registration site (see
154
            // `SymbolTable::is_under_any_runtime_guard`), rather than a
155
            // syntactic pre-scan of this suffix (which can't see through
156
            // macros/nesting and can't tell a reachable definition from one
157
            // a constant operand earlier in THIS SAME suffix would already
158
            // short-circuit past).
159
7095
            symbols.enter_runtime_guard()?;
160
7095
            let result = compile_and_for_effect(ctx, emit, symbols, &args[idx + 1..]);
161
7095
            symbols.exit_runtime_guard()?;
162
7095
            result?;
163
3767
            emit.block_end()?;
164
3767
            return Ok(());
165
2501
        }
166
2501
        if probe.is_nil() {
167
627
            if !matches!(operand, Expr::Nil) {
168
                compile_for_effect(ctx, emit, symbols, operand)?;
169
627
            }
170
627
            return Ok(());
171
1874
        }
172
1874
        compile_for_effect(ctx, emit, symbols, operand)?;
173
    }
174
8351
    compile_for_effect(ctx, emit, symbols, last)
175
16075
}
176

            
177
/// Eval-mirror of [`compile_and_for_stack`]: same left-to-right loop, same
178
/// early exit on a constant nil, same depth-guarded single recursion for
179
/// the first genuinely-runtime operand.
180
372281
pub(super) fn and_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
181
372281
    let Some((last, init)) = args.split_last() else {
182
        return Ok(Expr::T);
183
    };
184
372281
    for (idx, operand) in init.iter().enumerate() {
185
31430542
        let value = eval_value(symbols, operand)?;
186
31429710
        if value.is_wasm_runtime() && super::is_runtime_test(&value) {
187
            let placeholder =
188
228422
                Expr::WasmRuntime(classify_stack_type(&value).unwrap_or(WasmType::I32));
189
228422
            let rest = chain_expr("AND", &args[idx + 1..]);
190
228422
            symbols.enter_runtime_guard()?;
191
218438
            let result = if_form::if_form(symbols, &[placeholder, rest, Expr::Nil]);
192
218438
            symbols.exit_runtime_guard()?;
193
218438
            return result;
194
31201288
        }
195
31201288
        if value.is_nil() {
196
631
            return Ok(Expr::Nil);
197
31200657
        }
198
        // Never-nil runtime value (or an ordinary non-nil constant): its
199
        // own effects already applied above via `eval_value`; not a
200
        // genuine guard, so `runtime_guard_depth` must not rise for it — move on.
201
    }
202
142396
    eval_value(symbols, last)
203
372281
}
204

            
205
2306
pub(super) fn compile_or(
206
2306
    ctx: &mut CompileContext,
207
2306
    emit: &mut FunctionEmitter,
208
2306
    symbols: &mut SymbolTable,
209
2306
    args: &[Expr],
210
2306
) -> Result<()> {
211
2306
    let ty = compile_or_for_stack(ctx, emit, symbols, args)?;
212
2306
    serialize_stack_to_output(ctx, emit, ty)
213
2306
}
214

            
215
/// Same left-to-right, non-recursive walk as [`compile_and_for_stack`]: a
216
/// non-nil constant IS the result (no runtime park, no widening through a
217
/// synthetic IF); a constant `nil` contributes only its own compile-time
218
/// effects (if it isn't the literal `nil` itself) before OR moves on. Only
219
/// the first genuinely-runtime operand parks in a (reusable) local and
220
/// hands the rest of the chain to `if_form` as `(if <local> <local> (or
221
/// rest...))`.
222
28782
pub(super) fn compile_or_for_stack(
223
28782
    ctx: &mut CompileContext,
224
28782
    emit: &mut FunctionEmitter,
225
28782
    symbols: &mut SymbolTable,
226
28782
    args: &[Expr],
227
28782
) -> Result<WasmType> {
228
28782
    let Some((last, init)) = args.split_last() else {
229
        // `(or)` is nil — falsy i31, typed `Bool` to match the eval mirror.
230
212
        emit.i32_const(0);
231
212
        return Ok(WasmType::Bool);
232
    };
233
28570
    for (idx, operand) in init.iter().enumerate() {
234
16794
        let probe = probe_value(&mut symbols.clone(), operand)?;
235
16794
        if probe.is_wasm_runtime() {
236
14068
            if !super::is_runtime_test(&probe) {
237
                // Never-nil: this operand IS the OR's result (matching the
238
                // truthy-constant arm below) — not a genuine guard, so
239
                // `runtime_guard_depth` must not rise for it.
240
624
                return compile_for_stack(ctx, emit, symbols, operand);
241
13444
            }
242
13444
            let ty = compile_for_stack(ctx, emit, symbols, operand)?;
243
13440
            let local = ctx.alloc_local(ty)?;
244
13440
            emit.local_set(local);
245
            // The already-computed value stands in for both the test and the
246
            // true-branch result of `(if operand operand (or rest...))` — a
247
            // `local.get` re-read, never a re-evaluation of `operand`.
248
13440
            let held = Expr::WasmLocal(local, ty);
249
13440
            let rest = chain_expr("OR", &args[idx + 1..]);
250
13440
            let synthetic = [held.clone(), held, rest];
251
13440
            symbols.enter_runtime_guard()?;
252
13440
            let result = if_form::compile_if_for_stack(ctx, emit, symbols, &synthetic);
253
13440
            symbols.exit_runtime_guard()?;
254
13440
            return result;
255
2726
        }
256
2726
        if !probe.is_nil() {
257
1456
            return compile_for_stack(ctx, emit, symbols, operand);
258
1270
        }
259
1270
        if !matches!(operand, Expr::Nil) {
260
431
            compile_for_effect(ctx, emit, symbols, operand)?;
261
839
        }
262
    }
263
13046
    compile_for_stack(ctx, emit, symbols, last)
264
28782
}
265

            
266
/// Effect-position `OR`: mirrors [`compile_and_for_effect`] — only a
267
/// genuinely-runtime operand whose TRUTHINESS decides whether the rest of
268
/// the chain runs needs a stack value; every other operand, including the
269
/// last, compiles for effect only. A truthy runtime operand IS the OR's
270
/// (discarded) result, so the rest of the chain lives in the `if`'s ELSE
271
/// arm rather than its THEN arm (the reverse of AND's placement).
272
4221
pub(super) fn compile_or_for_effect(
273
4221
    ctx: &mut CompileContext,
274
4221
    emit: &mut FunctionEmitter,
275
4221
    symbols: &mut SymbolTable,
276
4221
    args: &[Expr],
277
4221
) -> Result<()> {
278
4221
    let Some((last, init)) = args.split_last() else {
279
        return Ok(());
280
    };
281
4221
    for (idx, operand) in init.iter().enumerate() {
282
3575
        let probe = probe_value(&mut symbols.clone(), operand)?;
283
3575
        if probe.is_wasm_runtime() {
284
1475
            if !super::is_runtime_test(&probe) {
285
                // Never-nil: this operand IS the OR's result — nothing after
286
                // it ever runs.
287
208
                compile_for_effect(ctx, emit, symbols, operand)?;
288
208
                return Ok(());
289
1267
            }
290
            // See the matching comment in `compile_and_for_effect`: a
291
            // single `compile_test_condition` call replaces the
292
            // park-in-a-local-then-reload sequence, compiling `operand`
293
            // exactly once, still before `enter_runtime_guard` below.
294
1267
            super::compile_test_condition(ctx, emit, symbols, operand)?;
295
1267
            emit.if_block(wasm_encoder::BlockType::Empty);
296
1267
            emit.else_block();
297
1267
            symbols.enter_runtime_guard()?;
298
1267
            let result = compile_or_for_effect(ctx, emit, symbols, &args[idx + 1..]);
299
1267
            symbols.exit_runtime_guard()?;
300
1267
            result?;
301
1059
            emit.block_end()?;
302
1059
            return Ok(());
303
2100
        }
304
2100
        if !probe.is_nil() {
305
            // Constant non-nil: this operand IS the OR's result — its
306
            // effects run, and nothing after it does.
307
419
            compile_for_effect(ctx, emit, symbols, operand)?;
308
419
            return Ok(());
309
1681
        }
310
1681
        if !matches!(operand, Expr::Nil) {
311
17
            compile_for_effect(ctx, emit, symbols, operand)?;
312
1664
        }
313
    }
314
2327
    compile_for_effect(ctx, emit, symbols, last)
315
4221
}
316

            
317
/// Eval-mirror of [`compile_or_for_stack`]: same left-to-right loop, same
318
/// constant-value short-circuit, same depth-guarded single recursion for
319
/// the first genuinely-runtime operand.
320
43088
pub(super) fn or_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
321
43088
    let Some((last, init)) = args.split_last() else {
322
        return Ok(Expr::Nil);
323
    };
324
43088
    for (idx, operand) in init.iter().enumerate() {
325
62414885
        let value = eval_value(symbols, operand)?;
326
62414469
        if value.is_wasm_runtime() && super::is_runtime_test(&value) {
327
            // Mirror `compile_or_for_stack`'s synthetic IF with a type-only
328
            // placeholder (the eval mirror has no real wasm local to reuse) —
329
            // `if_form` reconciles it against the rest exactly as codegen will.
330
            let placeholder =
331
12056
                Expr::WasmRuntime(classify_stack_type(&value).unwrap_or(WasmType::I32));
332
12056
            let rest = chain_expr("OR", &args[idx + 1..]);
333
12056
            symbols.enter_runtime_guard()?;
334
12056
            let result = if_form::if_form(symbols, &[placeholder.clone(), placeholder, rest]);
335
12056
            symbols.exit_runtime_guard()?;
336
12056
            return result;
337
62402413
        }
338
62402413
        if !value.is_nil() {
339
            // Never-nil runtime value, or an ordinary non-nil constant: IS
340
            // the OR's result — not a genuine guard.
341
1065
            return Ok(value);
342
62401348
        }
343
    }
344
29551
    eval_value(symbols, last)
345
43088
}