1
//! `DEFUN`, `DEFVAR`, `DEFPARAMETER` — name-binding forms that mutate
2
//! the symbol table in place.
3
//!
4
//! A FRESH (or redefining) binding registers UNCONDITIONALLY — the symbol
5
//! table has no way to represent "only bound when this runtime branch is
6
//! taken" — so every DEFVAR/DEFPARAMETER that would actually write a
7
//! binding is refused under a runtime AND/OR guard, regardless of whether
8
//! its initializer classifies as constant or runtime. DEFVAR's "don't
9
//! overwrite" no-op (name already bound) is the one exception: it writes
10
//! nothing, so it stays safe under a guard.
11
//!
12
//! The codegen path (`compile_defvar`/`compile_defparam`) classifies the
13
//! initializer on a disposable clone of the CURRENT table, compiles it for
14
//! real against that SAME (still unmodified) table, and only THEN
15
//! registers the binding — never registering first and compiling second,
16
//! which would let a self-referential redefinition
17
//! (`(defparameter x (progn (setf x (+ x 1)) x))`) see its own new value
18
//! instead of the old one it should read.
19

            
20
use crate::ast::{Expr, WasmType};
21
use crate::compiler::context::CompileContext;
22
use crate::compiler::emit::FunctionEmitter;
23
use crate::compiler::expr::format_form;
24
use crate::compiler::join::{Arm, reconcile_arms};
25
use crate::compiler::native::{chain_pair_element, compile_constant_list};
26
use crate::compiler::recompile::compiled_in_trial;
27
use crate::compiler::special::{closure_for_stack, has_v1_param_shape, is_capture_free};
28

            
29
use super::let_compile::record_closure_result;
30
use crate::compiler::expr::{compile_expr, compile_for_effect, compile_for_stack, probe_value};
31
use crate::error::{Error, Result};
32
use crate::reserved::reject_reserved;
33
use crate::runtime::{Asked, ClosureShape, HomeKey, Symbol, SymbolKind, SymbolTable};
34

            
35
use super::super::cell_store::{compile_into_home, store_arm};
36
use super::define_cell::{CellDefinition, define_cell};
37
use super::define_checks::reject_misplaced_definition;
38
use super::define_function::defun;
39

            
40
338232
pub(super) fn compile_defun(
41
338232
    ctx: &mut CompileContext,
42
338232
    emit: &mut FunctionEmitter,
43
338232
    symbols: &mut SymbolTable,
44
338232
    args: &[Expr],
45
338232
) -> Result<()> {
46
338232
    let result = defun(symbols, args)?;
47
335934
    record_definition_site(ctx, symbols, args);
48
335934
    compile_expr(ctx, emit, symbols, &result)
49
338232
}
50

            
51
220089
pub(super) fn compile_defun_for_effect(
52
220089
    ctx: &mut CompileContext,
53
220089
    _emit: &mut FunctionEmitter,
54
220089
    symbols: &mut SymbolTable,
55
220089
    args: &[Expr],
56
220089
) -> Result<()> {
57
220089
    defun(symbols, args)?;
58
188397
    record_definition_site(ctx, symbols, args);
59
188397
    Ok(())
60
220089
}
61

            
62
/// Records on a just-registered DEFUN the BLOCK labels open at its
63
/// definition, which its inlined body may return to (ISS-179).
64
524331
pub(super) fn record_definition_site(
65
524331
    ctx: &CompileContext,
66
524331
    symbols: &mut SymbolTable,
67
524331
    args: &[Expr],
68
524331
) {
69
524331
    if let Some(symbol) = args
70
524331
        .first()
71
524331
        .and_then(Expr::as_symbol)
72
524331
        .and_then(|name| symbols.lookup_mut(name))
73
    {
74
524331
        symbol.set_block_depth(ctx.block_label_count());
75
    }
76
524331
}
77

            
78
266021
pub(super) fn compile_defvar(
79
266021
    ctx: &mut CompileContext,
80
266021
    emit: &mut FunctionEmitter,
81
266021
    symbols: &mut SymbolTable,
82
266021
    args: &[Expr],
83
266021
) -> Result<()> {
84
266021
    if args.is_empty() {
85
        return Err(Error::Compile(
86
            "DEFVAR requires at least a name".to_string(),
87
        ));
88
266021
    }
89
266021
    let name = def_name(symbols, "DEFVAR", &args[0])?;
90
266018
    reject_misplaced_definition(symbols, "DEFVAR", &name)?;
91
266002
    let doc = def_doc(args.get(2));
92
266002
    let already_bound = !symbols.is_cell(&name)
93
148361
        && (symbols.lost_type(&name).is_some()
94
148361
            || symbols
95
148361
                .lookup(&name)
96
3767
                .is_some_and(|sym| sym.value().is_some()));
97
266002
    if already_bound {
98
1876
        register_def_value(symbols, &name, None, doc);
99
1876
        return Ok(());
100
264126
    }
101
264126
    let Some(init) = args.get(1) else {
102
10655
        reject_unless_cell_store(symbols, "DEFVAR", &name, args)?;
103
10655
        register_def_value(symbols, &name, None, doc);
104
10655
        return Ok(());
105
    };
106
253471
    let def = ValueDefinition {
107
253471
        form: "DEFVAR",
108
253471
        name: &name,
109
253471
        doc,
110
253471
        init,
111
253471
        args,
112
253471
    };
113
253471
    define_value(ctx, emit, symbols, def)
114
266021
}
115

            
116
117989
pub(super) fn compile_defparam(
117
117989
    ctx: &mut CompileContext,
118
117989
    emit: &mut FunctionEmitter,
119
117989
    symbols: &mut SymbolTable,
120
117989
    args: &[Expr],
121
117989
) -> Result<()> {
122
117989
    if args.len() < 2 {
123
208
        return Err(Error::Compile(
124
208
            "DEFPARAMETER requires a name and initial value".to_string(),
125
208
        ));
126
117781
    }
127
117781
    let name = def_name(symbols, "DEFPARAMETER", &args[0])?;
128
117778
    reject_misplaced_definition(symbols, "DEFPARAMETER", &name)?;
129
117753
    let def = ValueDefinition {
130
117753
        form: "DEFPARAMETER",
131
117753
        name: &name,
132
117753
        doc: def_doc(args.get(2)),
133
117753
        init: &args[1],
134
117753
        args,
135
117753
    };
136
117753
    define_value(ctx, emit, symbols, def)
137
117989
}
138

            
139
struct ValueDefinition<'a> {
140
    form: &'static str,
141
    name: &'a str,
142
    doc: Option<String>,
143
    init: &'a Expr,
144
    args: &'a [Expr],
145
}
146

            
147
/// A DEFVAR / DEFPARAMETER with an init: a store into the unit's cell, or a
148
/// constant registered at the form. An init that does not fold makes the
149
/// global a cell, so the unit compiles again with one.
150
371224
fn define_value(
151
371224
    ctx: &mut CompileContext,
152
371224
    emit: &mut FunctionEmitter,
153
371224
    symbols: &mut SymbolTable,
154
371224
    def: ValueDefinition,
155
371224
) -> Result<()> {
156
371224
    let cell = symbols.is_cell(def.name);
157
371224
    if !cell {
158
242327
        super::super::reject_definition_under_runtime_guard(symbols, def.form)?;
159
128897
    }
160
369552
    let probed = probe_value(&mut symbols.clone(), def.init)?;
161
369344
    if !cell && probed.is_wasm_runtime() {
162
53197
        return ask_for_cell(ctx, emit, symbols, def.name, def.init);
163
316147
    }
164
316147
    reject_unless_cell_store(symbols, def.form, def.name, def.args)?;
165
312391
    match cell {
166
        true => {
167
125777
            let cell_def = CellDefinition {
168
125777
                name: def.name,
169
125777
                doc: def.doc,
170
125777
                init: def.init,
171
125777
                probed: &probed,
172
125777
                only_unbound: def.form == "DEFVAR",
173
125777
                args: def.args,
174
125777
            };
175
125777
            define_cell(ctx, emit, symbols, cell_def)
176
        }
177
186614
        false => finish_def_binding(ctx, emit, symbols, def.name, def.doc, def.init, probed),
178
    }
179
371224
}
180

            
181
/// Asks the next attempt for a cell of `name`, whose init runs at run time.
182
/// This attempt goes on with a stand-in global bound to it, so that the
183
/// definitions after it ask too and the unit compiles again once; the attempt
184
/// is thrown away.
185
53197
fn ask_for_cell(
186
53197
    ctx: &mut CompileContext,
187
53197
    emit: &FunctionEmitter,
188
53197
    symbols: &mut SymbolTable,
189
53197
    name: &str,
190
53197
    init: &Expr,
191
53197
) -> Result<()> {
192
53197
    let ask = compiled_in_trial(ctx, symbols, emit, init, asked)?.unwrap_or(Asked::Untyped);
193
53197
    let ty = match &ask {
194
47757
        Asked::Typed(ty) => *ty,
195
5440
        Asked::Closure(_) | Asked::Untyped => WasmType::AnyRef,
196
    };
197
53197
    symbols.ask_cell(name, ask);
198
53197
    let home = Expr::WasmGlobal(ctx.alloc_mutable_global(ty)?, ty);
199
53197
    register_def_value(symbols, name, Some(home), None);
200
53197
    Ok(())
201
53197
}
202

            
203
/// What a run-time init compiles to, for the cell the next attempt makes; an
204
/// init that is no more than `AnyRef` leaves the cell to its stores.
205
52568
fn asked(ctx: &CompileContext, compiled: Option<WasmType>) -> Result<Asked> {
206
52568
    Ok(match compiled {
207
        Some(WasmType::Closure(sig)) => {
208
3771
            let sig = ctx.closure_sig(sig)?;
209
3771
            ClosureShape::of(&sig.params, sig.result).map_or(Asked::Untyped, Asked::Closure)
210
        }
211
1040
        Some(WasmType::AnyRef) | None => Asked::Untyped,
212
47757
        Some(ty) => Asked::Typed(ty),
213
    })
214
52568
}
215

            
216
/// A definition of a cell is a run-time store a caught exit may skip. A DEFVAR
217
/// of a special cell is one anywhere; any other definition is refused under a
218
/// runtime guard or in a loop, whose scratch table would lose what it
219
/// registers, and a constant one after a caught exit, which a macro may read.
220
326802
fn reject_unless_cell_store(
221
326802
    symbols: &SymbolTable,
222
326802
    form_name: &str,
223
326802
    name: &str,
224
326802
    args: &[Expr],
225
326802
) -> Result<()> {
226
326802
    let cell = symbols.is_cell(name);
227
326802
    let special = symbols.is_special(name) && !symbols.is_created_global(name);
228
326802
    if cell && form_name == "DEFVAR" && special {
229
6458
        return Ok(());
230
320344
    }
231
320344
    super::super::reject_definition_under_runtime_guard(symbols, form_name)?;
232
317224
    match cell || symbols.skipping_region(args).is_none() {
233
316588
        true => Ok(()),
234
636
        false => Err(super::super::definition_not_static(form_name)),
235
    }
236
326802
}
237

            
238
/// Compiles `init`'s real effects/value against `symbols` — `name` must not
239
/// yet be (re)bound to `probed`'s value, so a self-referential redefinition
240
/// sees its OLD value, matching the environment `probed` was itself
241
/// classified against. Registers `name` afterwards: `probed`'s constant
242
/// value, or the closure home of a lambda.
243
186614
pub(super) fn finish_def_binding(
244
186614
    ctx: &mut CompileContext,
245
186614
    emit: &mut FunctionEmitter,
246
186614
    symbols: &mut SymbolTable,
247
186614
    name: &str,
248
186614
    doc: Option<String>,
249
186614
    init: &Expr,
250
186614
    probed: Expr,
251
186614
) -> Result<()> {
252
186614
    let expansion = expansion_datum(symbols, name, &probed);
253
186614
    let value = if lifts_closure(&probed) {
254
37779
        closure_home(ctx, emit, symbols, name, init, &probed)?
255
    } else {
256
        // A compile-time-constant value may still carry a runtime side
257
        // effect (e.g. a nested `setf` on a wasm-backed place) that only
258
        // real codegen — not `eval_value` — can emit; compile once, for
259
        // effect, then register the already-classified constant.
260
148835
        compile_for_effect(ctx, emit, symbols, init)?;
261
148831
        probed
262
    };
263
186188
    register_def_value(symbols, name, Some(value), doc);
264
186188
    register_expansion_value(symbols, name, expansion);
265
186188
    Ok(())
266
186614
}
267

            
268
/// The init a macro body reads for `name`: a constant of a global no store
269
/// can change.
270
638971
pub(super) fn expansion_datum(symbols: &SymbolTable, name: &str, probed: &Expr) -> Option<Expr> {
271
638971
    let constant = !probed.is_wasm_runtime() && !lifts_closure(probed);
272
638971
    (constant && !symbols.is_stored_global(name)).then(|| probed.clone())
273
638971
}
274

            
275
524216
pub(super) fn register_expansion_value(symbols: &mut SymbolTable, name: &str, datum: Option<Expr>) {
276
524216
    if let (Some(datum), Some(sym)) = (datum, symbols.lookup_mut(name)) {
277
166530
        sym.set_expansion_value(datum);
278
357686
    }
279
524216
}
280

            
281
/// A lambda value a wasm closure can carry: its global is a closure home, so
282
/// a call through the name is a `call_ref`.
283
891352
pub(super) fn lifts_closure(probed: &Expr) -> bool {
284
891352
    matches!(probed, Expr::Lambda(params, _) if has_v1_param_shape(params))
285
891352
}
286

            
287
/// The home of a lambda a global is defined to: a mutable wasm global every
288
/// function reaches, typed by the closure codegen pushes.
289
58995
pub(super) fn closure_home(
290
58995
    ctx: &mut CompileContext,
291
58995
    emit: &mut FunctionEmitter,
292
58995
    symbols: &mut SymbolTable,
293
58995
    name: &str,
294
58995
    init: &Expr,
295
58995
    probed: &Expr,
296
58995
) -> Result<Expr> {
297
58995
    let ty = compile_closure_init(ctx, emit, symbols, init)?;
298
58365
    let home = global_home(ctx, emit, ty)?;
299
58365
    record_closure_home(ctx, symbols, name, probed, &home)?;
300
58365
    Ok(home)
301
58995
}
302

            
303
/// Pushes the closure `init` makes; a lambda an earlier unit carried is the
304
/// closure's source and compiles as the lambda form would.
305
61907
fn compile_closure_init(
306
61907
    ctx: &mut CompileContext,
307
61907
    emit: &mut FunctionEmitter,
308
61907
    symbols: &mut SymbolTable,
309
61907
    init: &Expr,
310
61907
) -> Result<WasmType> {
311
61907
    match init {
312
24128
        Expr::Lambda(..) => closure_for_stack(ctx, emit, symbols, init),
313
37779
        _ => compile_for_stack(ctx, emit, symbols, init),
314
    }
315
61907
}
316

            
317
/// The home of the list of closures an earlier unit carried as `source`.
318
10401
pub(super) fn list_source_home(
319
10401
    ctx: &mut CompileContext,
320
10401
    emit: &mut FunctionEmitter,
321
10401
    symbols: &mut SymbolTable,
322
10401
    source: &Expr,
323
10401
) -> Result<Expr> {
324
10401
    let ty = compile_for_stack(ctx, emit, symbols, source)?;
325
10401
    global_home(ctx, emit, ty)
326
10401
}
327

            
328
/// The home of a cell an earlier unit's constant seeds: typed by the
329
/// constant joined with what the stores of the previous attempt wrote, so an
330
/// integer seed with a fractional store is a Scalar.
331
328644
pub(super) fn seeded_home(
332
328644
    ctx: &mut CompileContext,
333
328644
    emit: &mut FunctionEmitter,
334
328644
    symbols: &mut SymbolTable,
335
328644
    name: &str,
336
328644
    constant: &Expr,
337
328644
) -> Result<Expr> {
338
328644
    if matches!(constant, Expr::Lambda(..)) {
339
2912
        let ty = compile_closure_init(ctx, emit, symbols, constant)?;
340
2912
        let home = global_home(ctx, emit, ty)?;
341
2912
        record_closure_result(symbols, ctx, &home)?;
342
2912
        return Ok(home);
343
325732
    }
344
325732
    let base = home_base(name, constant)?;
345
325732
    let ty = joined_with_hint(symbols, name, &base);
346
325732
    compile_home_init(ctx, emit, symbols, constant, constant, ty)?;
347
325732
    symbols.note_home(name, base, Some(constant.clone()), ty);
348
325732
    global_home(ctx, emit, ty)
349
328644
}
350

            
351
/// Stores the value on the stack into a new mutable global of type `ty`.
352
397410
fn global_home(ctx: &mut CompileContext, emit: &mut FunctionEmitter, ty: WasmType) -> Result<Expr> {
353
397410
    let idx = ctx.alloc_mutable_global(ty)?;
354
397410
    emit.global_set(idx);
355
397410
    Ok(Expr::WasmGlobal(idx, ty))
356
397410
}
357

            
358
/// Lets the eval surface type a call through a closure global, and lets a
359
/// higher-order native inline a capture-free closure no store can replace.
360
58365
fn record_closure_home(
361
58365
    ctx: &mut CompileContext,
362
58365
    symbols: &mut SymbolTable,
363
58365
    name: &str,
364
58365
    probed: &Expr,
365
58365
    home: &Expr,
366
58365
) -> Result<()> {
367
58365
    record_closure_result(symbols, ctx, home)?;
368
58365
    if let (Expr::Lambda(params, body), Some((place, _))) = (probed, home.place())
369
58365
        && lifts_closure(probed)
370
58365
        && !symbols.is_cell(name)
371
58365
        && is_capture_free(symbols, params, body)
372
    {
373
48772
        symbols.record_closure_body(place, params.clone(), (**body).clone());
374
9593
    }
375
58365
    Ok(())
376
58365
}
377

            
378
/// The arms that type the home of a constant-init global before any store is
379
/// compiled: its init.
380
389395
pub(super) fn home_base(name: &str, probed: &Expr) -> Result<Vec<Arm>> {
381
389395
    match constant_list_arm(probed).or_else(|| store_arm(probed)) {
382
389395
        Some(arm) => Ok(vec![arm]),
383
        None => Err(Error::Compile(format!(
384
            "{name}: a global the program stores to or binds must hold a runtime value, but its \
385
             initial value has no runtime representation"
386
        ))),
387
    }
388
389395
}
389

            
390
/// A constant list init as the arm that materialises at the home's element.
391
778790
fn constant_list_arm(probed: &Expr) -> Option<Arm> {
392
778790
    match probed {
393
8340
        Expr::Datum(inner) => match inner.as_ref() {
394
4988
            Expr::List(members) => chain_pair_element(members).ok().map(Arm::ConstantList),
395
3352
            _ => None,
396
        },
397
770450
        _ => None,
398
    }
399
778790
}
400

            
401
/// Compiles a constant init into its home. A constant list whose home has
402
/// another element than its own is built at the home's element.
403
389395
pub(super) fn compile_home_init(
404
389395
    ctx: &mut CompileContext,
405
389395
    emit: &mut FunctionEmitter,
406
389395
    symbols: &mut SymbolTable,
407
389395
    init: &Expr,
408
389395
    probed: &Expr,
409
389395
    ty: WasmType,
410
389395
) -> Result<()> {
411
389395
    match (probed, constant_list_arm(probed), ty) {
412
        (Expr::Datum(inner), Some(Arm::ConstantList(own)), WasmType::PairRef(elem))
413
1559
            if elem != own =>
414
        {
415
429
            let Expr::List(members) = inner.as_ref() else {
416
                return compile_into_home(ctx, emit, symbols, init, ty, false);
417
            };
418
429
            compile_constant_list(ctx, emit, symbols, members.clone(), elem).map(drop)
419
        }
420
388966
        _ => compile_into_home(ctx, emit, symbols, init, ty, matches!(probed, Expr::Nil)),
421
    }
422
389395
}
423

            
424
/// `base` joined with what the stores of the previous attempt wrote.
425
325732
fn joined_with_hint(symbols: &SymbolTable, name: &str, base: &[Arm]) -> WasmType {
426
325732
    let hint = symbols.hint(&HomeKey::global(name)).map(Arm::Value);
427
325732
    let arms: Vec<Arm> = base.iter().copied().chain(hint).collect();
428
325732
    reconcile_arms(&arms)
429
325732
}
430

            
431
5678930
pub(super) fn def_name(symbols: &SymbolTable, form_name: &str, expr: &Expr) -> Result<String> {
432
5678930
    match expr {
433
5678927
        Expr::Symbol(s) => reject_reserved(symbols, s).map(|()| s.clone()),
434
3
        other => Err(Error::Compile(format!(
435
3
            "{form_name}: expected symbol name, got {}",
436
3
            format_form(other)
437
3
        ))),
438
    }
439
5678930
}
440

            
441
393347
pub(super) fn def_doc(expr: Option<&Expr>) -> Option<String> {
442
393347
    match expr {
443
416
        Some(Expr::String(s)) => Some(s.clone()),
444
392931
        _ => None,
445
    }
446
393347
}
447

            
448
385821
pub(super) fn register_def_value(
449
385821
    symbols: &mut SymbolTable,
450
385821
    name: &str,
451
385821
    value: Option<Expr>,
452
385821
    doc: Option<String>,
453
385821
) {
454
385821
    symbols.mark_special(name);
455
385821
    if let Some(sym) = symbols.lookup_mut(name) {
456
231432
        if let Some(v) = value {
457
93136
            sym.set_value(v);
458
138296
        }
459
231432
        if let Some(d) = doc {
460
            sym.set_doc(d);
461
231432
        }
462
231432
        return;
463
154389
    }
464
154389
    let mut sym = Symbol::new(name, SymbolKind::Variable);
465
154389
    if let Some(v) = value {
466
153553
        sym = sym.with_value(v);
467
836
    }
468
154389
    if let Some(d) = doc {
469
416
        sym = sym.with_doc(d);
470
153973
    }
471
154389
    symbols.define(sym);
472
385821
}