1
use crate::ast::{Expr, Place, WasmType};
2
use crate::compiler::expr::format_form;
3
use crate::error::{Error, Result};
4
use crate::reserved::reject_reserved;
5
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
6

            
7
use super::super::context::CompileContext;
8
use super::super::emit::FunctionEmitter;
9
use super::super::expr::{
10
    compile_for_effect, compile_for_stack, compile_for_stack_as, eval_value, fold_value,
11
    format_expr, probe_value, serialize_stack_to_output, store_begin_place, store_end_place,
12
};
13
use super::defstruct::{compile_defstruct, compile_defstruct_for_effect, defstruct};
14
use super::{SpecialFormSpec, compound_setf_call, expand_macro_places};
15

            
16
pub(super) const FORMS: &[SpecialFormSpec] = &[
17
    SpecialFormSpec {
18
        name: "DEFSTRUCT",
19
        eval: defstruct,
20
        compile: compile_defstruct,
21
        stack: None,
22
        effect: Some(compile_defstruct_for_effect),
23
    },
24
    SpecialFormSpec {
25
        name: "SETF",
26
        eval: setf,
27
        compile: compile_setf,
28
        stack: Some(compile_setf_for_stack),
29
        effect: None,
30
    },
31
];
32

            
33
30995
pub(super) fn compile_setf(
34
30995
    ctx: &mut CompileContext,
35
30995
    emit: &mut FunctionEmitter,
36
30995
    symbols: &mut SymbolTable,
37
30995
    args: &[Expr],
38
30995
) -> Result<()> {
39
    // Value/effect position (`compile_expr` dispatch — e.g. a body/program tail
40
    // `(setf x v)`): SETF's value (it returns the assigned value) must be
41
    // SERIALIZED to the output buffer, leaving the wasm stack empty — the
42
    // `compile_expr` contract. The `stack` handler keeps the value on the stack
43
    // for genuine stack consumers (`(list … (setf n …))`); leaving it here would
44
    // strand a value at the end of the enclosing block (invalid wasm).
45
30995
    let ty = compile_setf_for_stack(ctx, emit, symbols, args)?;
46
28083
    serialize_stack_to_output(ctx, emit, ty)
47
30995
}
48

            
49
/// SETF in stack/value position: assign and LEAVE the assigned value on the
50
/// stack (so `(list … (setf n …))` / `(+ (setf n …) …)` work). A runtime-local
51
/// symbol place emits the value then `local.tee` (last pair) / `local.set`
52
/// (earlier pairs); const places fall back to the eval-rebind
53
/// path, then materialize the resulting value.
54
63307
pub(super) fn compile_setf_for_stack(
55
63307
    ctx: &mut CompileContext,
56
63307
    emit: &mut FunctionEmitter,
57
63307
    symbols: &mut SymbolTable,
58
63307
    args: &[Expr],
59
63307
) -> Result<WasmType> {
60
63307
    if !args.len().is_multiple_of(2) {
61
        return Err(Error::Compile(
62
            "SETF requires an even number of arguments (place value pairs)".to_string(),
63
        ));
64
63307
    }
65
63307
    let args = &expand_macro_places(symbols, args)?;
66
63307
    let pairs: Vec<&[Expr]> = args.chunks(2).collect();
67
63307
    let Some(last) = pairs.len().checked_sub(1) else {
68
        // `(setf)` with no pairs ≡ nil — push the falsy i31 (typed Bool so it
69
        // serializes as Nil), matching `setf`'s empty-arg result.
70
        emit.i32_const(0);
71
        return Ok(WasmType::Bool);
72
    };
73
    // Process each place/value pair INDIVIDUALLY (mirroring the effect path): a
74
    // runtime-local place emits a typed store; a const place takes
75
    // the eval-rebind path (no wasm store). A whole-form fallback to `setf` would
76
    // silently DROP a runtime-local store in a MIXED form — `set_place` is a
77
    // no-op for a `WasmLocal` symbol, so its `local.set` would never be emitted.
78
63307
    let mut result_ty = WasmType::Bool;
79
63307
    for (i, pair) in pairs.iter().enumerate() {
80
63723
        let place = &pair[0];
81
63723
        let value_expr = &pair[1];
82
63723
        let is_last = i == last;
83
63723
        if let Some(call) = compound_setf_call(symbols, place, value_expr)? {
84
9776
            let ty = compile_for_stack(ctx, emit, symbols, &call)?;
85
8944
            match is_last {
86
8944
                true => result_ty = ty,
87
                false => emit.drop_value(),
88
            }
89
8944
            continue;
90
53531
        }
91
53531
        match promoted_place(symbols, place) {
92
            Some((target, ty)) => {
93
                // Coerce the rhs to the LOCAL's declared type — a dimension-flexible
94
                // literal (`(setf ratio-local 1)`) crosses the Index↔Scalar
95
                // boundary and `nil` lands on the typed default; a genuine clash is
96
                // a clean compile error, not an invalid `local.set`.
97
53531
                store_begin_place(ctx, emit, target);
98
53531
                super::compile_store_value(ctx, emit, symbols, place, value_expr, ty)?;
99
                // Reassigning a closure local invalidates any source body recorded
100
                // for it at bind time: the local now holds a DIFFERENT closure (or
101
                // nil), so inlining the old body in a later FOLD would apply the
102
                // wrong function. Forget AFTER compiling the rhs (it may FOLD the
103
                // OLD closure) and before the store — FOLD then `call_ref`s.
104
50583
                if matches!(ty, WasmType::Closure(_)) {
105
1664
                    symbols.forget_closure_body(target);
106
48919
                }
107
50583
                store_end_place(ctx, emit, target, is_last);
108
50583
                super::mark_cell_store(emit, symbols, place, target);
109
50583
                if is_last {
110
50167
                    result_ty = ty;
111
416
                }
112
            }
113
            None => {
114
                // const place, no PRE-EXISTING runtime
115
                // storage of its own — unsafe under a runtime guard, same
116
                // as the effect handler (see
117
                // `reject_compile_time_setf_under_runtime_guard`).
118
                super::reject_compile_time_setf_under_runtime_guard(symbols)?;
119
                super::reject_uncarried_global_store(symbols, place)?;
120
                let value = compile_const_place_setf_rhs(ctx, emit, symbols, place, value_expr)?;
121
                let assigned = set_place(symbols, place, value)?;
122
                if is_last {
123
                    result_ty = compile_for_stack(ctx, emit, symbols, &assigned)?;
124
                }
125
            }
126
        }
127
    }
128
59111
    Ok(result_ty)
129
63307
}
130

            
131
/// Compiles a const SETF place's RHS for its real effects and
132
/// returns the value to register for `place`. Mirrors DEFVAR/DEFPARAMETER's
133
/// own promotion (`binding::define::finish_def_binding`): a genuinely
134
/// RUNTIME RHS (a host-fn call, an `(error …)` raise, a nested SETF onto an
135
/// existing `WasmLocal`, …) needs real bytecode, and — since a compile-time
136
/// symbol has no storage of its own — a `Expr::Symbol` place is promoted
137
/// into a backing `WasmLocal` so later reads see the real value instead of a
138
/// dangling placeholder. A compile-time-constant RHS may
139
/// still carry a real side effect of its own, so it is unconditionally
140
/// compiled for effect too — never modelled via `eval_value` alone.
141
///
142
/// Compiling `value_expr` can ITSELF promote `place` to a real `WasmLocal`
143
/// — e.g. `(setf p (progn (setf p (host-fn)) 2))`, where the INNER `setf`
144
/// promotes `p` before the OUTER one's own value is ready. `place` is
145
/// RE-CHECKED after `value_expr` compiles, and if it now has real storage,
146
/// the outer value is stored into THAT storage for real — `set_place`
147
/// deliberately no-ops on an already-runtime-backed place (see its own doc
148
/// comment), so skipping this re-check would silently drop the outer
149
/// store. `value_expr` is never compiled a second time: the post-promotion
150
/// store consumes either the ALREADY-probed constant (a fresh,
151
/// side-effect-free compile of the literal via `compile_for_stack_as`) or
152
/// the value already sitting on the wasm stack from the runtime branch's
153
/// own `compile_for_stack`. Shared by both `compile_setf_for_effect` and
154
/// `compile_setf_for_stack`'s const-place branch.
155
836
pub(in crate::compiler) fn compile_const_place_setf_rhs(
156
836
    ctx: &mut CompileContext,
157
836
    emit: &mut FunctionEmitter,
158
836
    symbols: &mut SymbolTable,
159
836
    place: &Expr,
160
836
    value_expr: &Expr,
161
836
) -> Result<Expr> {
162
836
    if let Some(datum) = fold_value(symbols, value_expr)? {
163
836
        return store_into_promoted_place(ctx, emit, symbols, place, &datum);
164
    }
165
    let probed = probe_value(&mut symbols.clone(), value_expr)?;
166
    if probed.is_wasm_runtime() {
167
        return compile_const_place_setf_runtime(ctx, emit, symbols, place, value_expr);
168
    }
169
    compile_for_effect(ctx, emit, symbols, value_expr)?;
170
    store_into_promoted_place(ctx, emit, symbols, place, &probed)
171
836
}
172

            
173
/// `place`'s existing runtime storage, if it has any (from its definition,
174
/// or promoted before this SETF ran at all, or by one of `value_expr`'s own
175
/// nested effects).
176
595648
pub(in crate::compiler) fn promoted_place(
177
595648
    symbols: &SymbolTable,
178
595648
    place: &Expr,
179
595648
) -> Option<(Place, WasmType)> {
180
595648
    match place {
181
536842
        Expr::Symbol(name) => symbols.lookup(name)?.value()?.place(),
182
58806
        other => other.place(),
183
    }
184
595648
}
185

            
186
/// The RHS resolved to a genuinely runtime value: compile it for real, then
187
/// store into `place`'s promoted local if `value_expr` itself just created
188
/// one (a nested SETF on the SAME symbol), otherwise allocate a fresh one —
189
/// mirrors DEFVAR/DEFPARAMETER's own promotion
190
/// (`binding::define::finish_def_binding`).
191
fn compile_const_place_setf_runtime(
192
    ctx: &mut CompileContext,
193
    emit: &mut FunctionEmitter,
194
    symbols: &mut SymbolTable,
195
    place: &Expr,
196
    value_expr: &Expr,
197
) -> Result<Expr> {
198
    let actual_ty = compile_for_stack(ctx, emit, symbols, value_expr)?;
199
    if let Some((target, ty)) = promoted_place(symbols, place) {
200
        if ty != actual_ty {
201
            return Err(Error::Compile(format!(
202
                "SETF: {} was promoted to {ty} by a nested assignment inside its own \
203
                 value expression, but this assignment's value is {actual_ty}",
204
                format_form(place)
205
            )));
206
        }
207
        set_promoted(emit, target);
208
        return Ok(promoted_value(target, ty));
209
    }
210
    let idx = ctx.alloc_local(actual_ty)?;
211
    emit.local_set(idx);
212
    Ok(Expr::WasmLocal(idx, actual_ty))
213
}
214

            
215
/// The RHS resolved to a compile-time constant `probed`: if `place` was
216
/// promoted to a real local by one of `value_expr`'s own nested effects,
217
/// the constant must still be stored into it for real (a fresh,
218
/// side-effect-free compile of the literal `probed`, never `value_expr`
219
/// again); otherwise there is no storage to write and `probed` is simply
220
/// the value to register via `set_place`.
221
836
fn store_into_promoted_place(
222
836
    ctx: &mut CompileContext,
223
836
    emit: &mut FunctionEmitter,
224
836
    symbols: &mut SymbolTable,
225
836
    place: &Expr,
226
836
    probed: &Expr,
227
836
) -> Result<Expr> {
228
836
    let Some((target, ty)) = promoted_place(symbols, place) else {
229
836
        return Ok(probed.clone());
230
    };
231
    compile_for_stack_as(ctx, emit, symbols, probed, ty)?;
232
    set_promoted(emit, target);
233
    Ok(promoted_value(target, ty))
234
836
}
235

            
236
fn set_promoted(emit: &mut FunctionEmitter, target: Place) {
237
    match target {
238
        Place::Local(idx) => emit.local_set(idx),
239
        Place::Global(idx) => emit.global_set(idx),
240
    }
241
}
242

            
243
fn promoted_value(target: Place, ty: WasmType) -> Expr {
244
    match target {
245
        Place::Local(idx) => Expr::WasmLocal(idx, ty),
246
        Place::Global(idx) => Expr::WasmGlobal(idx, ty),
247
    }
248
}
249

            
250
/// A store to a global cell of the unit is a runtime effect: the evaluator
251
/// answers the value, and notes the store so a fold over it is refused.
252
593228
fn stores_to_cell(symbols: &SymbolTable, place: &Expr) -> bool {
253
593228
    matches!(place, Expr::Symbol(name) if symbols.cell_global(name).is_some())
254
593228
}
255

            
256
602307
pub(super) fn setf(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
257
602307
    if !args.len().is_multiple_of(2) {
258
        return Err(Error::Compile(
259
            "SETF requires an even number of arguments (place value pairs)".to_string(),
260
        ));
261
602307
    }
262

            
263
602307
    if args.is_empty() {
264
        return Ok(Expr::Nil);
265
602307
    }
266

            
267
602307
    let args = &expand_macro_places(symbols, args)?;
268
602307
    let mut last_value = Expr::Nil;
269
602307
    for pair in args.chunks(2) {
270
603971
        let place = &pair[0];
271
603971
        if let Some(call) = compound_setf_call(symbols, place, &pair[1])? {
272
6656
            last_value = eval_value(symbols, &call)?;
273
6448
            continue;
274
597315
        }
275
597315
        if let Expr::Symbol(name) = place
276
597315
            && symbols.is_macro_expansion()
277
203034
            && !symbols.is_macro_local(name)
278
        {
279
425
            return Err(Error::Compile(format!(
280
425
                "{name}: a macro body may not mutate a global; an expansion makes no commits"
281
425
            )));
282
596890
        }
283
        // A place already backed by a runtime value is a no-op here (see
284
        // `set_place` below) — either a real `WasmLocal` (codegen already
285
        // promoted it), or a `WasmRuntime` placeholder (the EVAL-ONLY
286
        // surface's classification for a runtime-backed `LET`/`LET*`
287
        // binding, which never allocates a real local: `let_eval.rs` binds
288
        // a runtime initializer straight to `Expr::WasmRuntime`, never
289
        // `WasmLocal`, so checking `WasmLocal` alone here wrongly treated
290
        // it as compile-time-only). Codegen's own `let_compile.rs` ALWAYS
291
        // promotes a `WasmRuntime` binding to a real `WasmLocal` before
292
        // its body compiles, so codegen never reaches this function with
293
        // a bare `WasmRuntime` place — this broadening only affects the
294
        // eval-only surface. Anything else is a PURE compile-time-model
295
        // update with no real bytecode, unsafe under a runtime guard, same
296
        // as the codegen paths (`compile_setf_for_effect`/
297
        // `compile_setf_for_stack`) — checked here too so eval-only
298
        // classification and codegen agree on what's rejected.
299
596890
        let is_runtime_backed = matches!(
300
596890
            place,
301
596890
            Expr::Symbol(name) if symbols
302
596890
                .lookup(name)
303
596890
                .and_then(|s| s.value())
304
596890
                .is_some_and(Expr::is_wasm_runtime)
305
        );
306
596890
        if !is_runtime_backed {
307
203943
            super::reject_compile_time_setf_under_runtime_guard(symbols)?;
308
392947
        }
309
596890
        let value = eval_value(symbols, &pair[1])?;
310
593228
        if stores_to_cell(symbols, place) {
311
126082
            symbols.measurements().note_cell_store();
312
467146
        }
313
593228
        last_value = set_place(symbols, place, value)?;
314
    }
315

            
316
598012
    Ok(last_value)
317
602307
}
318

            
319
594067
pub(in crate::compiler) fn set_place(
320
594067
    symbols: &mut SymbolTable,
321
594067
    place: &Expr,
322
594067
    value: Expr,
323
594067
) -> Result<Expr> {
324
594067
    match place {
325
        Expr::Symbol(name) => {
326
594067
            reject_reserved(symbols, name)?;
327
594066
            if symbols.lookup(name).is_some_and(Symbol::is_loop_constant) {
328
212
                return Err(Error::Compile(format!(
329
212
                    "{name}: a statically unrolled loop's variable may not be assigned"
330
212
                )));
331
593854
            }
332
593854
            super::reject_captured_assignment(symbols, name)?;
333
593854
            match symbols.lookup_mut(name) {
334
                // A var already backed by a runtime value keeps that
335
                // binding, whether a real `WasmLocal` (the local IS its
336
                // storage, and codegen emits the runtime store —
337
                // overwriting it here would drop the local index, so a
338
                // later read or assign would compile a producerless
339
                // `WasmRuntime` → invalid wasm) or the eval-only surface's
340
                // `WasmRuntime` placeholder (compile-time UNKNOWABLE, so
341
                // overwriting it with the assigned value's constant would
342
                // make a later eval-only read see a value the guard
343
                // governing this SETF might never actually have produced
344
                // at runtime). `setf` still returns the assigned value.
345
                //
346
                // The return here is deliberately the RAW `value` — not
347
                // coerced to the place's declared type — even when the
348
                // place is runtime-backed: this function is shared by the
349
                // pure eval-only `setf` entry point AND codegen's own
350
                // internal plumbing (`compile_setf_for_stack`'s
351
                // const-place branch calls this, then feeds the result
352
                // straight into `compile_for_stack`, which requires a
353
                // genuinely compile-for-stack-able value, never a bare
354
                // `WasmRuntime` placeholder with no backing local). See
355
                // `setf` below for where the coercion-aware value belongs.
356
593853
                Some(sym) if sym.value().is_some_and(Expr::is_wasm_runtime) => {}
357
202488
                Some(sym) => sym.set_value(value.clone()),
358
                None => {
359
1
                    symbols.define_special(
360
1
                        Symbol::new(name, SymbolKind::Variable).with_value(value.clone()),
361
1
                    );
362
                }
363
            }
364
593854
            Ok(value)
365
        }
366

            
367
        _ => Err(Error::Compile(format!(
368
            "Invalid place in SETF: {}",
369
            format_expr(place)
370
        ))),
371
    }
372
594067
}