1
use super::entry::{Symbol, SymbolKind};
2
use super::table::SymbolTable;
3
use crate::ast::Expr;
4

            
5
31
pub(super) fn variable(name: &str) -> Symbol {
6
31
    Symbol::new(name, SymbolKind::Variable).with_value(Expr::T)
7
31
}
8

            
9
20
pub(super) fn function_symbol(name: &str) -> Symbol {
10
20
    Symbol::new(name, SymbolKind::Function).with_function(Expr::T)
11
20
}
12

            
13
22
pub(super) fn reader_of(name: &str, read: &str) -> Symbol {
14
22
    reader_of_kind(name, read, SymbolKind::Function)
15
22
}
16

            
17
4
pub(super) fn macro_reader_of(name: &str, read: &str) -> Symbol {
18
4
    reader_of_kind(name, read, SymbolKind::Macro)
19
4
}
20

            
21
26
fn reader_of_kind(name: &str, read: &str, kind: SymbolKind) -> Symbol {
22
26
    let body = Expr::Symbol(read.to_string());
23
26
    Symbol::new(name, kind).with_function(Expr::Lambda(
24
26
        crate::ast::LambdaParams::simple(Vec::new()),
25
26
        Box::new(body),
26
26
    ))
27
26
}
28

            
29
8
pub(super) fn definition_of(table: &SymbolTable, name: &str) -> Option<u32> {
30
8
    table.lookup(name).map(Symbol::function_definition)
31
8
}
32

            
33
10
pub(super) fn value_definition_of(table: &SymbolTable, name: &str) -> Option<u32> {
34
10
    table.lookup(name).map(Symbol::value_definition)
35
10
}
36

            
37
#[test]
38
1
fn define_gives_each_function_a_distinct_definition_id() {
39
1
    let mut table = SymbolTable::new();
40
1
    table.define(function_symbol("walk"));
41
1
    let first = definition_of(&table, "walk");
42
1
    let mut shadowed = table.clone();
43
1
    shadowed.define(function_symbol("walk"));
44
1
    assert_ne!(first, Some(0));
45
1
    assert_ne!(definition_of(&shadowed, "walk"), first);
46
1
}
47

            
48
#[test]
49
1
fn define_keeps_the_id_of_a_restored_symbol() {
50
1
    let mut table = SymbolTable::new();
51
1
    table.define(function_symbol("walk"));
52
1
    let saved = table.lookup("walk").cloned();
53
1
    let before = definition_of(&table, "walk");
54
1
    table.define(function_symbol("other"));
55
1
    table.define(saved.expect("walk was defined"));
56
1
    assert_eq!(definition_of(&table, "walk"), before);
57
1
}
58

            
59
#[test]
60
1
fn redefining_a_function_assigns_a_fresh_id() {
61
1
    let mut table = SymbolTable::new();
62
1
    table.define(function_symbol("f"));
63
1
    let before = definition_of(&table, "f");
64
1
    table.define(function_symbol("f"));
65
1
    assert_ne!(definition_of(&table, "f"), before);
66
1
}
67

            
68
#[test]
69
1
fn redefining_a_macro_makes_it_a_function() {
70
1
    let mut table = SymbolTable::new();
71
1
    table.define(macro_reader_of("m", "x"));
72
1
    assert!(matches!(table.resolve_head("m"), super::Head::Macro(..)));
73
1
    table.define(reader_of("m", "y"));
74
1
    assert!(matches!(table.resolve_head("m"), super::Head::Function(..)));
75
1
}
76

            
77
#[test]
78
1
fn clones_share_one_id_allocator() {
79
1
    let mut table = SymbolTable::new();
80
1
    let mut other = table.clone();
81
1
    table.define(function_symbol("a"));
82
1
    other.define(function_symbol("b"));
83
1
    assert_ne!(definition_of(&table, "a"), definition_of(&other, "b"));
84
1
}
85

            
86
#[test]
87
1
fn test_symbol_creation() {
88
1
    let sym = Symbol::new("foo", SymbolKind::Variable);
89
1
    assert_eq!(sym.name(), "foo");
90
1
    assert_eq!(sym.kind(), SymbolKind::Variable);
91
1
    assert!(sym.value().is_none());
92
1
}
93

            
94
#[test]
95
1
fn test_symbol_with_value() {
96
1
    let sym = Symbol::new("x", SymbolKind::Variable).with_value(Expr::T);
97
1
    assert!(sym.value().is_some());
98
1
    assert_eq!(sym.value(), Some(&Expr::T));
99
1
}
100

            
101
#[test]
102
1
fn test_symbol_properties() {
103
1
    let mut sym = Symbol::new("test", SymbolKind::Function);
104
1
    sym.set_property("doc", Expr::String("A test function".into()));
105
1
    sym.set_property("pure", Expr::T);
106

            
107
1
    assert_eq!(
108
1
        sym.get_property("doc"),
109
1
        Some(&Expr::String("A test function".into()))
110
    );
111
1
    assert_eq!(sym.get_property("pure"), Some(&Expr::T));
112
1
    assert!(sym.get_property("nonexistent").is_none());
113
1
}
114

            
115
#[test]
116
1
fn test_symbol_table_builtins() {
117
1
    let table = SymbolTable::with_builtins();
118

            
119
1
    assert!(table.contains("+"));
120
1
    assert_eq!(table.lookup("+").unwrap().kind(), SymbolKind::Operator);
121

            
122
1
    assert!(table.contains("IF"));
123
1
    assert_eq!(table.lookup("IF").unwrap().kind(), SymbolKind::SpecialForm);
124

            
125
1
    assert!(table.contains("CAR"));
126
1
    assert_eq!(table.lookup("CAR").unwrap().kind(), SymbolKind::Native);
127

            
128
1
    assert!(table.contains("EVAL"));
129
1
    assert_eq!(
130
1
        table.lookup("EVAL").unwrap().kind(),
131
1
        SymbolKind::SpecialForm
132
    );
133

            
134
1
    assert!(table.contains("DEBUG"));
135
1
    assert_eq!(table.lookup("DEBUG").unwrap().kind(), SymbolKind::Native);
136
1
}
137

            
138
#[test]
139
1
fn test_symbol_table_define_lookup() {
140
1
    let mut table = SymbolTable::new();
141
1
    table.define(Symbol::new("my-func", SymbolKind::Function));
142

            
143
1
    assert!(table.contains("my-func"));
144
1
    assert!(!table.contains("undefined"));
145

            
146
1
    let sym = table.lookup("my-func").unwrap();
147
1
    assert_eq!(sym.kind(), SymbolKind::Function);
148
1
}
149

            
150
// ADR-0029 strict resolution: a namespaced symbol keys by its canonical
151
// `NS:NAME` string and does NOT alias the bare `NAME`. There is no ambient
152
// current namespace and no cross-namespace fallback.
153

            
154
#[test]
155
1
fn qualified_symbol_keys_separately_from_bare() {
156
1
    let mut table = SymbolTable::new();
157
1
    table.define(Symbol::new("FOO:BAR", SymbolKind::Function));
158

            
159
1
    assert!(table.contains("FOO:BAR"));
160
    // Strict: the qualified key does not create a bare alias.
161
1
    assert!(!table.contains("BAR"));
162
1
    assert!(table.lookup("FOO:BAR").is_some());
163
1
    assert!(table.lookup("BAR").is_none());
164
1
}
165

            
166
#[test]
167
1
fn lookup_qualified_builds_canonical_key() {
168
1
    let mut table = SymbolTable::new();
169
1
    table.define(Symbol::new("FINANCE:ADD-MONEY", SymbolKind::Function));
170

            
171
1
    assert!(
172
1
        table
173
1
            .lookup_qualified(Some("FINANCE"), "ADD-MONEY")
174
1
            .is_some()
175
    );
176
    // An unqualified lookup of the same base name does not reach the namespaced entry.
177
1
    assert!(table.lookup_qualified(None, "ADD-MONEY").is_none());
178
1
}
179

            
180
#[test]
181
1
fn builtins_remain_global_unqualified() {
182
1
    let table = SymbolTable::with_builtins();
183
    // Global builtins keep bare keys; a namespaced lookup of the same base misses.
184
1
    assert!(table.contains("+"));
185
1
    assert!(!table.contains("MATH:+"));
186
1
    assert!(table.lookup_qualified(Some("MATH"), "+").is_none());
187
1
}
188

            
189
#[test]
190
1
fn universal_prelude_loaded_but_not_host_layer() {
191
    // ADR-0029 two-layer prelude: the universal math:* / list:* helpers are
192
    // present in every table; the host-fn-dependent split:* helpers are NOT
193
    // (they load only on the rpc Session path, after host fns are registered).
194
1
    let table = SymbolTable::with_builtins();
195
1
    assert!(table.contains("MATH:SQUARE"));
196
1
    assert!(table.contains("LIST:SECOND"));
197
1
    assert!(!table.contains("SPLIT:LIST-FOR-TRANSACTION"));
198

            
199
    // The pure-wasm table loads the same universal layer.
200
1
    let wasm_table = SymbolTable::with_builtins_for_wasm();
201
1
    assert!(wasm_table.contains("MATH:SQUARE"));
202
1
    assert!(!wasm_table.contains("SPLIT:LIST-FOR-TRANSACTION"));
203
1
}
204

            
205
/// Fable review (Phase 3): `exit_macro_expansion` used to hide a mismatched
206
/// enter/exit pair with `saturating_sub`. It is now a checked subtraction
207
/// returning a structured `Error::Compile` — the `Result` IS the contract,
208
/// so no `#[spec(requires: ...)]` shadows it with a panic under
209
/// `--cfg anodized_panic`.
210
#[test]
211
1
fn exit_macro_expansion_at_depth_zero_is_a_compile_error_not_a_panic() {
212
1
    let mut symbols = SymbolTable::with_builtins();
213
1
    let err = symbols
214
1
        .exit_macro_expansion()
215
1
        .expect_err("exit_macro_expansion() with shared_recursion_depth 0 must error");
216
1
    assert!(
217
1
        err.to_string()
218
1
            .contains("exit_shared_recursion() called with shared_recursion_depth already 0")
219
    );
220
1
}
221

            
222
/// A balanced enter/exit pair still succeeds.
223
#[test]
224
1
fn exit_macro_expansion_after_enter_succeeds() {
225
1
    let mut symbols = SymbolTable::with_builtins();
226
1
    symbols.enter_macro_expansion().expect("enter succeeds");
227
1
    symbols
228
1
        .exit_macro_expansion()
229
1
        .expect("balanced exit must succeed");
230
1
}
231

            
232
#[test]
233
1
fn exit_runtime_guard_releases_the_shared_level_even_on_a_branch_underflow() {
234
1
    let mut symbols = SymbolTable::new();
235
1
    symbols.enter_shared_recursion().expect("enter succeeds");
236
1
    let err = symbols
237
1
        .exit_runtime_guard()
238
1
        .expect_err("a branch underflow must error");
239
1
    assert!(err.to_string().contains("exit_runtime_branch()"));
240
1
    assert!(symbols.exit_shared_recursion().is_err());
241
1
}
242

            
243
#[test]
244
1
fn a_runtime_branch_marks_the_table_until_it_exits() {
245
1
    let mut symbols = SymbolTable::new();
246
1
    symbols.enter_runtime_branch().expect("enter succeeds");
247
1
    assert!(symbols.is_under_any_runtime_guard());
248
1
    symbols.exit_runtime_branch().expect("exit succeeds");
249
1
    assert!(!symbols.is_under_any_runtime_guard());
250
1
    assert!(symbols.exit_runtime_branch().is_err());
251
1
}
252

            
253
/// A scope frame shadows without copying: the shadowed binding returns when
254
/// the frame closes, a name the frame introduced leaves, and a plain
255
/// definition made inside the frame outlives it (0014 Stage 2, ISS-039).
256
#[test]
257
1
fn a_scope_frame_restores_what_it_shadowed_and_keeps_definitions() {
258
1
    let mut table = SymbolTable::new();
259
1
    table.define(Symbol::new("X", SymbolKind::Variable).with_value(Expr::Nil));
260
1
    table.push_scope();
261
1
    table.define_scoped(Symbol::new("X", SymbolKind::Variable).with_value(Expr::T));
262
1
    table.define_scoped(Symbol::new("Y", SymbolKind::Variable).with_value(Expr::T));
263
1
    table.define(Symbol::new("F", SymbolKind::Function).with_value(Expr::T));
264
1
    assert_eq!(table.lookup("X").and_then(Symbol::value), Some(&Expr::T));
265
1
    table.pop_scope().expect("a frame is open");
266
1
    assert_eq!(table.lookup("X").and_then(Symbol::value), Some(&Expr::Nil));
267
1
    assert!(table.lookup("Y").is_none());
268
1
    assert!(table.lookup("F").is_some());
269
1
    assert!(table.pop_scope().is_err());
270
1
}
271

            
272
#[test]
273
1
fn a_runtime_value_is_recorded_only_on_a_macro_expansion_table() {
274
1
    let mut symbols = SymbolTable::with_builtins();
275
1
    symbols.note_runtime_value();
276
1
    assert!(!symbols.saw_runtime_value());
277
1
    symbols.mark_macro_expansion();
278
1
    assert!(!symbols.saw_runtime_value());
279
1
    symbols.note_runtime_value();
280
1
    assert!(symbols.saw_runtime_value());
281
1
}
282

            
283
#[test]
284
1
fn a_clones_runtime_note_is_seen_by_the_original() {
285
1
    let mut symbols = SymbolTable::with_builtins();
286
1
    symbols.mark_macro_expansion();
287
1
    let mut clone = symbols.clone();
288
1
    clone.note_runtime_value();
289
1
    assert!(symbols.saw_runtime_value());
290
1
}
291

            
292
#[test]
293
1
fn a_fresh_expansion_does_not_inherit_a_previous_note() {
294
1
    let mut first = SymbolTable::with_builtins();
295
1
    first.mark_macro_expansion();
296
1
    first.note_runtime_value();
297
1
    let mut second = first.clone();
298
1
    second.mark_macro_expansion();
299
1
    assert!(!second.saw_runtime_value());
300
1
    assert!(first.saw_runtime_value());
301
1
}
302

            
303
#[test]
304
1
fn a_nested_expansions_note_does_not_reach_the_outer_one() {
305
1
    let mut outer = SymbolTable::with_builtins();
306
1
    outer.mark_macro_expansion();
307
1
    let mut inner = outer.clone();
308
1
    inner.mark_macro_expansion();
309
1
    inner.note_runtime_value();
310
1
    assert!(!outer.saw_runtime_value());
311
1
}
312

            
313
#[test]
314
1
fn a_speculative_clones_note_is_not_seen_by_the_original() {
315
1
    let mut symbols = SymbolTable::with_builtins();
316
1
    symbols.mark_macro_expansion();
317
1
    let mut probe = symbols.speculative_clone();
318
1
    probe.note_runtime_value();
319
1
    assert!(probe.saw_runtime_value());
320
1
    assert!(!symbols.saw_runtime_value());
321
1
}
322

            
323
#[test]
324
1
fn a_speculative_clone_of_an_expansion_still_records_notes() {
325
1
    let mut symbols = SymbolTable::with_builtins();
326
1
    symbols.mark_macro_expansion();
327
1
    let probe = symbols.speculative_clone();
328
1
    assert!(probe.is_macro_expansion());
329
1
}
330

            
331
#[test]
332
1
fn defining_does_not_bump_the_epoch_but_noting_a_redefinition_does() {
333
1
    let mut table = SymbolTable::new();
334
1
    let start = table.redefinition_epoch();
335
1
    table.define(function_symbol("f"));
336
1
    table.define(function_symbol("f"));
337
1
    assert_eq!(table.redefinition_epoch(), start);
338
1
    table.note_redefinition();
339
1
    assert_eq!(table.redefinition_epoch(), start + 1);
340
1
}
341

            
342
#[test]
343
1
fn note_redefinition_is_visible_through_clones() {
344
1
    let table = SymbolTable::new();
345
1
    let clone = table.clone();
346
1
    let start = table.redefinition_epoch();
347
1
    clone.note_redefinition();
348
1
    assert_eq!(table.redefinition_epoch(), start + 1);
349
1
}
350

            
351
#[test]
352
1
fn a_function_body_table_and_its_clones_know_they_are_in_a_body() {
353
1
    let mut table = SymbolTable::new();
354
1
    assert!(table.function_owner().is_none());
355
1
    table.enter_function_body(0);
356
1
    assert!(table.function_owner().is_some());
357
1
    assert!(table.clone().function_owner().is_some());
358
1
}
359

            
360
#[test]
361
1
fn hidden_names_are_unique_across_clones() {
362
1
    let table = SymbolTable::new();
363
1
    let clone = table.clone();
364
1
    let names = [
365
1
        table.hidden_name("mk", "a"),
366
1
        clone.hidden_name("mk", "a"),
367
1
        table.hidden_name("mk", "a"),
368
1
    ];
369
1
    assert_ne!(names[0], names[1]);
370
1
    assert_ne!(names[1], names[2]);
371
1
    assert_ne!(names[0], names[2]);
372
1
}
373

            
374
#[test]
375
1
fn a_hidden_name_tells_its_factory_and_parameter() {
376
1
    let name = SymbolTable::new().hidden_name("MK", "A");
377
1
    assert_eq!(SymbolTable::hidden_origin(&name), Some(("MK", "A")));
378
1
    assert!(SymbolTable::is_hidden_name(&name));
379
1
    assert_eq!(SymbolTable::hidden_origin("A"), None);
380
1
}
381

            
382
#[test]
383
1
fn within_shared_recursion_charges_one_level_and_releases_it() {
384
1
    let mut symbols = SymbolTable::new();
385
1
    let seen = symbols
386
1
        .within_shared_recursion(|inner| Ok(inner.shared_recursion_depth))
387
1
        .expect("below the ceiling");
388
1
    assert_eq!(seen, 1);
389
1
    assert_eq!(symbols.shared_recursion_depth, 0);
390
1
}
391

            
392
#[test]
393
1
fn within_shared_recursion_releases_the_level_when_the_run_fails() {
394
1
    let mut symbols = SymbolTable::new();
395
1
    let err = symbols
396
1
        .within_shared_recursion(|_| Err::<(), _>(crate::error::Error::Compile("boom".to_string())))
397
1
        .expect_err("the run fails");
398
1
    assert!(matches!(err, crate::error::Error::Compile(_)), "{err}");
399
1
    assert_eq!(symbols.shared_recursion_depth, 0);
400
1
}
401

            
402
#[test]
403
1
fn within_shared_recursion_is_refused_at_the_ceiling() {
404
1
    let mut symbols = SymbolTable::new();
405
1
    for _ in 0..crate::runtime::MAX_SHARED_RECURSION_DEPTH {
406
24
        symbols.enter_shared_recursion().expect("below the ceiling");
407
    }
408
1
    let err = symbols
409
        .within_shared_recursion(|_| Ok(()))
410
1
        .expect_err("ceiling reached");
411
1
    assert!(matches!(err, crate::error::Error::Resource(_)), "{err}");
412
1
}
413

            
414
#[test]
415
1
fn a_designator_of_a_global_function_is_not_special() {
416
1
    let mut table = SymbolTable::new();
417
1
    table.define(reader_of("f", "x"));
418
1
    assert_eq!(table.designated_function("f").expect("designated"), None);
419
1
}
420

            
421
#[test]
422
1
fn a_designator_names_the_alias_of_the_global_a_labels_function_hides() {
423
1
    let mut table = SymbolTable::new();
424
1
    let global = reader_of("f", "x");
425
1
    let expected = global.function().cloned();
426
1
    table.define(global);
427
1
    table.define(reader_of("f", "y").local_function());
428
1
    let alias = table
429
1
        .designated_function("f")
430
1
        .expect("designated")
431
1
        .expect("alias");
432
1
    assert_eq!(
433
1
        table.lookup(&alias).and_then(|s| s.function().cloned()),
434
1
        expected
435
    );
436
1
    assert_eq!(
437
1
        table.clone().designated_function("f").expect("designated"),
438
1
        Some(alias)
439
    );
440
1
}
441

            
442
#[test]
443
1
fn a_global_survives_a_variable_between_it_and_the_labels_function() {
444
1
    let mut table = SymbolTable::new();
445
1
    table.define(reader_of("f", "x"));
446
1
    table.define(Symbol::new("f", SymbolKind::Variable));
447
1
    table.define(reader_of("f", "y").local_function());
448
1
    assert!(
449
1
        table
450
1
            .designated_function("f")
451
1
            .expect("designated")
452
1
            .is_some()
453
    );
454
1
}
455

            
456
#[test]
457
1
fn a_designator_naming_only_a_labels_function_is_undefined() {
458
1
    let mut table = SymbolTable::new();
459
1
    table.define(reader_of("f", "y").local_function());
460
1
    let err = table.designated_function("f").unwrap_err();
461
1
    assert_eq!(err.to_string(), "Undefined symbol: f");
462
1
}
463

            
464
#[test]
465
1
fn a_global_macro_is_not_the_function_a_labels_function_hides() {
466
1
    let mut table = SymbolTable::new();
467
1
    table.define(macro_reader_of("f", "x"));
468
1
    table.define(reader_of("f", "y").local_function());
469
1
    let err = table.designated_function("f").unwrap_err();
470
1
    assert_eq!(err.to_string(), "Undefined symbol: f");
471
1
}
472

            
473
#[test]
474
1
fn a_variable_does_not_hide_a_macro_in_operator_position() {
475
1
    let mut table = SymbolTable::new();
476
1
    table.define(macro_reader_of("m", "y"));
477
1
    table.define(variable("m"));
478
1
    assert!(matches!(table.resolve_head("m"), super::Head::Macro(..)));
479
1
    assert!(table.lookup("m").is_some_and(Symbol::is_variable));
480
1
}
481

            
482
#[test]
483
1
fn a_labels_function_over_a_macro_gives_it_back_when_its_scope_closes() {
484
1
    let mut table = SymbolTable::new();
485
1
    table.define(macro_reader_of("m", "y"));
486
1
    table.push_scope();
487
1
    table.define_scoped(reader_of("m", "y").local_function());
488
1
    table.define_scoped(variable("m"));
489
1
    assert!(matches!(table.resolve_head("m"), super::Head::Function(..)));
490
1
    table.pop_scope().expect("a frame is open");
491
1
    assert!(matches!(table.resolve_head("m"), super::Head::Macro(..)));
492
1
}
493

            
494
6
fn chain_of(depth: usize) -> Expr {
495
574
    (0..depth).fold(Expr::Nil, |tail, _| Expr::cons(Expr::Nil, tail))
496
6
}
497

            
498
#[test]
499
1
fn open_expansions_compose_up_to_the_ceiling() {
500
1
    let ceiling = crate::compiler::datum::MAX_ELAB_DEPTH;
501
1
    let mut symbols = SymbolTable::new();
502
1
    symbols.enter_macro_expansion().expect("outer");
503
1
    symbols
504
1
        .compose_expansion(&chain_of(10), &[])
505
1
        .expect("first expansion");
506
1
    symbols.enter_macro_expansion().expect("inner");
507
1
    symbols
508
1
        .compose_expansion(&chain_of(ceiling - 10), &[])
509
1
        .expect("exactly at the ceiling");
510
1
    let err = symbols
511
1
        .compose_expansion(&chain_of(ceiling - 9), &[])
512
1
        .expect_err("one level past the ceiling");
513
1
    assert!(
514
1
        matches!(&err, crate::error::Error::Resource(m) if m.contains("nests deeper")),
515
        "{err}"
516
    );
517
1
}
518

            
519
#[test]
520
1
fn an_expansion_is_charged_only_for_the_depth_it_adds_to_its_arguments() {
521
1
    let ceiling = crate::compiler::datum::MAX_ELAB_DEPTH;
522
1
    let mut symbols = SymbolTable::new();
523
1
    symbols.enter_macro_expansion().expect("expansion");
524
1
    let arg = chain_of(ceiling - 1);
525
1
    symbols
526
1
        .compose_expansion(
527
1
            &Expr::cons(arg.clone(), Expr::Nil),
528
1
            std::slice::from_ref(&arg),
529
1
        )
530
1
        .expect("a wrapper around a deep argument adds one level");
531
1
}
532

            
533
#[test]
534
1
fn leaving_an_expansion_releases_its_depth() {
535
1
    let mut symbols = SymbolTable::new();
536
1
    symbols.enter_macro_expansion().expect("enter");
537
1
    symbols
538
1
        .compose_expansion(&chain_of(100), &[])
539
1
        .expect("compose");
540
1
    symbols.exit_macro_expansion().expect("exit");
541
1
    symbols.enter_macro_expansion().expect("sibling");
542
1
    symbols
543
1
        .compose_expansion(&chain_of(100), &[])
544
1
        .expect("a sibling starts from the outer depth");
545
1
}