1
//! Effect-position codegen.
2
//!
3
//! `compile_for_effect` is the entry point — it inspects the leading
4
//! form and either dispatches into the specialised SETF / IF / PROGN
5
//! handlers below, hands off to a special form's effect path, or
6
//! falls back to value-position emit when the form has a runtime
7
//! result that must be consumed.
8

            
9
use crate::ast::{Expr, WasmType};
10
use crate::compiler::context::CompileContext;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::error::{Error, Result};
13
use crate::runtime::{Head, SymbolTable, with_sufficient_stack};
14

            
15
use super::call::applying_lambda;
16
use super::call_runtime::try_compile_runtime_call;
17
use super::eval::{call, eval_value, expand_macro_then};
18
use super::fold::probe_value;
19
use super::lambda_params::compile_and_bind_lambda_params;
20
use super::local_cell::{store_begin_place, store_end_place};
21
use super::quasiquote::quasiquote_form;
22
use super::stack::compile_for_stack;
23
use crate::compiler::special::{compound_setf_call, promoted_place};
24

            
25
#[inline(never)]
26
3
fn compile_quasiquote_for_effect(
27
3
    ctx: &mut CompileContext,
28
3
    emit: &mut FunctionEmitter,
29
3
    symbols: &mut SymbolTable,
30
3
    template: &Expr,
31
3
) -> Result<()> {
32
3
    compile_for_effect(ctx, emit, symbols, &quasiquote_form(template)?)
33
3
}
34

            
35
4616956
pub(in crate::compiler) fn compile_for_effect(
36
4616956
    ctx: &mut CompileContext,
37
4616956
    emit: &mut FunctionEmitter,
38
4616956
    symbols: &mut SymbolTable,
39
4616956
    expr: &Expr,
40
4616956
) -> Result<()> {
41
4616956
    with_sufficient_stack(|| {
42
4616956
        symbols.charge_work(1)?;
43
4616956
        if let Expr::Quasiquote(template) = expr {
44
3
            return compile_quasiquote_for_effect(ctx, emit, symbols, template);
45
4616953
        }
46
4616953
        if try_compile_inline_lambda_call_for_effect(ctx, emit, symbols, expr)? {
47
18
            return Ok(());
48
4616935
        }
49
4616935
        if let Expr::List(elems) = expr
50
2669917
            && let Some(Expr::Symbol(name)) = elems.first()
51
        {
52
2669914
            let args = &elems[1..];
53
2669914
            let head = symbols.resolve_head(name);
54
2669914
            let builtin = head.is_builtin();
55
            // Expand macros (e.g. WHEN → IF) and recurse
56
2669914
            if let Head::Macro(params, body) = head {
57
340297
                let (params, body) = (params.clone(), body.clone());
58
340297
                return expand_macro_then(symbols, &params, &body, args, |symbols, code| {
59
340074
                    compile_for_effect(ctx, emit, symbols, &code)
60
340074
                });
61
2329617
            }
62
2329617
            if builtin {
63
2273437
                if try_compile_builtin_for_effect(ctx, emit, symbols, name, args)? {
64
1969655
                    return Ok(());
65
221291
                }
66
56180
            } else if try_compile_defun_call_for_effect(ctx, emit, symbols, expr, name, args)? {
67
24466
                return Ok(());
68
29781
            }
69
            // A value-producing native / host-fn call (LIST, CONS, +, an accessor,
70
            // …) whose result is discarded in effect position: COMPILE it and drop
71
            // the value, so effects in its ARGUMENTS (a nested `setf`, a promoted
72
            // accumulator update, …) actually emit. `eval_value` alone const-folds
73
            // without emitting — that silently dropped those arg effects. Non-value
74
            // special forms (LAMBDA, FUNCTION) are NOT compilable for stack and
75
            // stay on the eval path below.
76
251072
            if !(builtin && crate::compiler::special::is_special_form(name)) {
77
251072
                return compile_value_producing_call_for_effect(
78
251072
                    ctx, emit, symbols, expr, name, args,
79
251072
                );
80
            }
81
1947021
        }
82
        // A bare atom, or a non-value special form, in effect position: const-fold
83
        // it (no stack value to emit).
84
1947021
        eval_value(symbols, expr)?;
85
1947018
        Ok(())
86
4616956
    })
87
4616956
}
88

            
89
/// The effect path of a name that still resolves to the compiler's own
90
/// builtin; `Ok(false)` leaves the form to the caller's tail.
91
2273437
fn try_compile_builtin_for_effect(
92
2273437
    ctx: &mut CompileContext,
93
2273437
    emit: &mut FunctionEmitter,
94
2273437
    symbols: &mut SymbolTable,
95
2273437
    name: &str,
96
2273437
    args: &[Expr],
97
2273437
) -> Result<bool> {
98
2273437
    match name {
99
8528
        "DEBUG" => crate::compiler::native::compile_debug_effect(ctx, emit, symbols, args)?,
100
37348
        "PRINT" => crate::compiler::native::compile_print_effect(ctx, emit, symbols, args)?,
101
210
        "DISPLAY" => crate::compiler::native::compile_display_effect(ctx, emit, symbols, args)?,
102
        "NEWLINE" => crate::compiler::native::compile_newline_effect(ctx, emit, symbols, args)?,
103
552721
        "SETF" => compile_setf_for_effect(ctx, emit, symbols, args)?,
104
        "CREATE-TAG" | "DELETE-ENTITY" => {
105
20817
            crate::compiler::native::compile(ctx, emit, symbols, name, args)?;
106
        }
107
143394
        "IF" => compile_if_for_effect(ctx, emit, symbols, args)?,
108
118941
        "PROGN" => compile_progn_for_effect(ctx, emit, symbols, args)?,
109
        // `eval_value` does not model side effects (`create-tag`, `debug`,
110
        // host fns, a `(return-from …)`'s `br`), so a special form routed
111
        // there would drop its wasm; derived from the registry, not a list.
112
1391478
        _ if crate::compiler::special::is_special_form(name)
113
1170187
            && !crate::compiler::special::is_eval_only_special_form(name) =>
114
        {
115
1170187
            crate::compiler::special::compile_for_effect(ctx, emit, symbols, name, args)?;
116
        }
117
221291
        _ => return Ok(false),
118
    }
119
1969655
    Ok(true)
120
2273437
}
121

            
122
/// The generic `(name args...)` call once no special-cased name / macro /
123
/// special form matched, and `name` resolves to a user-defined `DEFUN`
124
/// whose call classifies as genuinely RUNTIME: `Ok(true)` means fully
125
/// emitted (inlined or routed to the monomorph helper); `Ok(false)` means
126
/// `name` isn't such a call (not a lambda at all, or one that folds to a
127
/// compile-time constant) and the caller's own tail handles it.
128
56180
fn try_compile_defun_call_for_effect(
129
56180
    ctx: &mut CompileContext,
130
56180
    emit: &mut FunctionEmitter,
131
56180
    symbols: &mut SymbolTable,
132
56180
    expr: &Expr,
133
56180
    name: &str,
134
56180
    args: &[Expr],
135
56180
) -> Result<bool> {
136
56180
    let (params, body) = match symbols.resolve_head(name) {
137
56180
        Head::Function(params, body) => (params.clone(), body.clone()),
138
        _ => return Ok(false),
139
    };
140
    // Classify on a DISPOSABLE clone — this decides which codegen path to
141
    // take, so it must not itself apply the call's compile-time effects (a
142
    // nested `setf`, a host-fn call in an argument, …) to the live table.
143
    // The runtime branch below applies them exactly once, in codegen; the
144
    // non-runtime fallthrough (the caller's tail, once this returns
145
    // `Ok(false)`) applies them exactly once via `compile_for_stack`.
146
56180
    let val = probe_value(&mut symbols.clone(), expr)?;
147
56177
    if !val.is_wasm_runtime() {
148
29781
        return Ok(false);
149
26396
    }
150
    // A recursive runtime-arg call routes to the monomorph helper (its
151
    // result is computed then dropped here); otherwise inline the body,
152
    // depth-guarded so a non-terminating recursion is a structured error,
153
    // not a native compiler-stack overflow — same contract as the
154
    // value/stack call paths.
155
26396
    if try_compile_runtime_call(ctx, emit, symbols, name, &params, &body, args)?.is_some() {
156
848
        emit.drop_value();
157
848
        return Ok(true);
158
25545
    }
159
    let Some(mut local) =
160
25545
        compile_and_bind_lambda_params(ctx, emit, symbols, &params, &body, args, Some(name))?
161
    else {
162
1875
        return Ok(true);
163
    };
164
23670
    ctx.push_inlining_frame(symbols, name)?;
165
23670
    let defined_at = super::call::definition_depth(symbols, name);
166
23670
    let result = ctx.with_hidden_labels(defined_at, |ctx| {
167
23670
        compile_for_effect(ctx, emit, &mut local, &body)
168
23670
    });
169
23670
    ctx.pop_inlining_frame(symbols, name)?;
170
23670
    result?;
171
21743
    Ok(true)
172
56180
}
173

            
174
/// A value-producing native / host-fn call (LIST, CONS, +, an accessor, …)
175
/// whose result is discarded in effect position: COMPILE it and drop the
176
/// value, so effects in its ARGUMENTS (a nested `setf`, a promoted
177
/// accumulator update, …) actually emit. `eval_value` alone const-folds
178
/// without emitting — that would silently drop those arg effects.
179
251072
fn compile_value_producing_call_for_effect(
180
251072
    ctx: &mut CompileContext,
181
251072
    emit: &mut FunctionEmitter,
182
251072
    symbols: &mut SymbolTable,
183
251072
    expr: &Expr,
184
251072
    name: &str,
185
251072
    args: &[Expr],
186
251072
) -> Result<()> {
187
    // A host fn — including a VOID one (`result: None`, e.g. `rpc-log`) —
188
    // routes through its effect compiler, which emits the import call and
189
    // drops any result. `compile_for_stack` would reject a void host fn
190
    // ("no return type"). A non-host value-producing native is compiled and
191
    // dropped.
192
251072
    if symbols.resolve_head(name).is_builtin() && ctx.lookup_host_fn(name).is_some() {
193
23934
        return crate::compiler::native::compile_host_fn_for_effect(ctx, emit, symbols, name, args);
194
227138
    }
195
227138
    compile_for_stack(ctx, emit, symbols, expr)?;
196
225628
    emit.drop_value();
197
225628
    Ok(())
198
251072
}
199

            
200
118941
fn compile_progn_for_effect(
201
118941
    ctx: &mut CompileContext,
202
118941
    emit: &mut FunctionEmitter,
203
118941
    symbols: &mut SymbolTable,
204
118941
    args: &[Expr],
205
118941
) -> Result<()> {
206
118941
    for arg in args {
207
155084
        compile_for_effect(ctx, emit, symbols, arg)?;
208
    }
209
113102
    Ok(())
210
118941
}
211

            
212
/// Compiles an inline lambda call `((lambda (params) body) args...)` — a
213
/// non-symbol head, since the reader parses `(lambda …)` as an `Expr::List`
214
/// that resolves to `Expr::Lambda` only once evaluated, mirroring
215
/// `compile_call_for_stack`'s own two arms — for effect, inlining its body
216
/// into the SAME emitter (mirroring `compile_lambda_call_for_stack`).
217
/// Returns `false` (nothing compiled) for anything else, incl. a `List`
218
/// callee that resolves to something other than a lambda: without this,
219
/// the generic symbol-headed dispatch in `compile_for_effect` falls
220
/// through to the eval-only interpreter fallback at the bottom of this
221
/// module, which never emits wasm at all, silently dropping the body's
222
/// effects (including any `(return-from …)` the body contains, which
223
/// needs a real `br` to an enclosing `BLOCK`, not a symbolic eval
224
/// placeholder).
225
4616953
fn try_compile_inline_lambda_call_for_effect(
226
4616953
    ctx: &mut CompileContext,
227
4616953
    emit: &mut FunctionEmitter,
228
4616953
    symbols: &mut SymbolTable,
229
4616953
    expr: &Expr,
230
4616953
) -> Result<bool> {
231
4616953
    let Expr::List(elems) = expr else {
232
1947018
        return Ok(false);
233
    };
234
2669935
    let Some(head) = elems.first() else {
235
        return Ok(false);
236
    };
237
2669935
    if matches!(head, Expr::Symbol(_)) {
238
2669914
        return Ok(false);
239
21
    }
240
21
    let resolved = match head {
241
        Expr::Lambda(_, _) => Some(head.clone()),
242
18
        Expr::List(inner) => match call(symbols, inner)? {
243
18
            lambda @ Expr::Lambda(_, _) => Some(lambda),
244
            _ => None,
245
        },
246
3
        _ => None,
247
    };
248
21
    let Some(Expr::Lambda(params, body)) = resolved else {
249
3
        return Ok(false);
250
    };
251
18
    applying_lambda(symbols, head, |symbols| {
252
        let Some(mut local) =
253
18
            compile_and_bind_lambda_params(ctx, emit, symbols, &params, &body, &elems[1..], None)?
254
        else {
255
            return Ok(());
256
        };
257
18
        compile_for_effect(ctx, emit, &mut local, &body)
258
18
    })?;
259
18
    Ok(true)
260
4616953
}
261

            
262
143394
fn compile_if_for_effect(
263
143394
    ctx: &mut CompileContext,
264
143394
    emit: &mut FunctionEmitter,
265
143394
    symbols: &mut SymbolTable,
266
143394
    args: &[Expr],
267
143394
) -> Result<()> {
268
143394
    if args.len() < 2 || args.len() > 3 {
269
        return Err(Error::Compile(
270
            "IF requires a test, a then-form, and an optional else-form".to_string(),
271
        ));
272
143394
    }
273
    // Classify on a CLONE — the test's compile-time effects reach the live
274
    // table only via the single emit below.
275
143394
    let test = probe_value(&mut symbols.clone(), &args[0])?;
276
143394
    let test_diverges = crate::compiler::special::form_diverges_scratch(symbols, &args[0])?;
277
143394
    if test_diverges {
278
        // The test transfers control before producing a condition; compile it
279
        // for effect so the exit fires. Both branches are dead.
280
208
        return compile_for_effect(ctx, emit, symbols, &args[0]);
281
143186
    }
282
143186
    if crate::compiler::special::is_runtime_test(&test) {
283
86770
        crate::compiler::special::compile_test_condition(ctx, emit, symbols, &args[0])?;
284
86557
        emit.if_block(wasm_encoder::BlockType::Empty);
285
86557
        crate::compiler::special::in_runtime_branch(symbols, |symbols| {
286
86557
            compile_for_effect(ctx, emit, symbols, &args[1])?;
287
85924
            if let Some(else_form) = args.get(2) {
288
82301
                emit.else_block();
289
82301
                compile_for_effect(ctx, emit, symbols, else_form)?;
290
3623
            }
291
85924
            Ok(())
292
86557
        })?;
293
85924
        emit.block_end()?;
294
85924
        return Ok(());
295
56416
    }
296
56416
    let test = crate::compiler::special::apply_const_test(ctx, emit, symbols, &args[0], &test)?;
297
56416
    if !test.is_nil() {
298
14979
        compile_for_effect(ctx, emit, symbols, &args[1])
299
41437
    } else if args.len() == 3 {
300
36886
        compile_for_effect(ctx, emit, symbols, &args[2])
301
    } else {
302
4551
        Ok(())
303
    }
304
143394
}
305

            
306
552721
fn compile_setf_for_effect(
307
552721
    ctx: &mut CompileContext,
308
552721
    emit: &mut FunctionEmitter,
309
552721
    symbols: &mut SymbolTable,
310
552721
    args: &[Expr],
311
552721
) -> Result<()> {
312
552721
    if !args.len().is_multiple_of(2) {
313
        return Err(Error::Compile(
314
            "SETF requires an even number of arguments".to_string(),
315
        ));
316
552721
    }
317
552721
    let args = &crate::compiler::special::expand_macro_places(symbols, args)?;
318
552721
    for pair in args.chunks(2) {
319
552929
        let place = &pair[0];
320
552929
        let value_expr = &pair[1];
321
552929
        if let Some(call) = compound_setf_call(symbols, place, value_expr)? {
322
11648
            compile_for_effect(ctx, emit, symbols, &call)?;
323
11648
            continue;
324
541281
        }
325
541281
        if let Some((target, ty)) = promoted_place(symbols, place) {
326
            // A diverging rhs (`(return-from …)`, `(error …)`) never
327
            // produces a value the local actually receives — control
328
            // transfers away first, so its nominal type (always `AnyRef`
329
            // for a `return-from`, boxed for its own enclosing BLOCK)
330
            // must not be coerced against the local's declared type.
331
            // Compile it for effect so the exit fires; the store below
332
            // is dead code, same treatment IF/COND give a diverging test.
333
540231
            if crate::compiler::special::form_diverges_scratch(symbols, value_expr)? {
334
630
                compile_for_effect(ctx, emit, symbols, value_expr)?;
335
630
                continue;
336
539601
            }
337
            // Coerce the rhs to the local's declared type (literal Index↔Scalar
338
            // crossing, nil → typed default); a real clash is a clean compile
339
            // error, not an invalid `local.set`.
340
539601
            store_begin_place(ctx, emit, target);
341
539601
            crate::compiler::special::compile_store_value(
342
539601
                ctx, emit, symbols, place, value_expr, ty,
343
539601
            )?;
344
            // Reassigning a closure local invalidates the body recorded for it
345
            // at bind time — the local now holds a different closure, so a later
346
            // FOLD inlining the stale body would call the wrong fn. Forget AFTER
347
            // compiling the rhs (which may legitimately FOLD the OLD closure)
348
            // and before the store.
349
524268
            if matches!(ty, WasmType::Closure(_)) {
350
3033
                symbols.forget_closure_body(target);
351
521235
            }
352
524268
            store_end_place(ctx, emit, target, false);
353
524268
            crate::compiler::special::mark_cell_store(emit, symbols, place, target);
354
524268
            continue;
355
1050
        }
356
        // const place, no PRE-EXISTING runtime storage of its
357
        // own — unsafe under a runtime guard (see
358
        // `reject_compile_time_setf_under_runtime_guard`).
359
1050
        crate::compiler::special::reject_compile_time_setf_under_runtime_guard(symbols)?;
360
1050
        crate::compiler::special::reject_uncarried_global_store(symbols, place)?;
361
836
        let value = crate::compiler::special::compile_const_place_setf_rhs(
362
836
            ctx, emit, symbols, place, value_expr,
363
836
        )?;
364
836
        crate::compiler::special::setf_set_place(symbols, place, value)?;
365
    }
366
536962
    Ok(())
367
552721
}