neovm-core 0.0.1

Core runtime structures for NeoVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Obarray and symbol interning.
//!
//! In Emacs, symbols are unique objects stored in an "obarray" (hash table).
//! Each symbol has:
//! - A name (string)
//! - A value cell (variable binding)
//! - A function cell (function binding)
//! - A property list (plist)
//! - A `special` flag (for dynamic binding in lexical scope)

use super::intern::{SymId, intern, is_canonical_id, lookup_interned, resolve_sym};
use super::value::{Value, ValueKind};
use crate::gc_trace::GcTrace;
use rustc_hash::FxHashMap;

/// Describes how a symbol's value cell is stored, matching GNU Emacs's
/// `symbol_redirect` enum (`SYMBOL_PLAINVAL`, `SYMBOL_VARALIAS`,
/// `SYMBOL_LOCALIZED`, `SYMBOL_FORWARDED`).
#[derive(Clone, Debug)]
pub enum SymbolValue {
    /// Direct value (GNU: SYMBOL_PLAINVAL).
    Plain(Option<Value>),
    /// Alias to another symbol (GNU: SYMBOL_VARALIAS).
    Alias(SymId),
    /// Buffer-local variable (GNU: SYMBOL_LOCALIZED).
    BufferLocal {
        default: Option<Value>,
        local_if_set: bool,
    },
    /// Forwarded to Rust variable (GNU: SYMBOL_FORWARDED) — placeholder.
    Forwarded,
}

impl Default for SymbolValue {
    fn default() -> Self {
        SymbolValue::Plain(None)
    }
}

/// Per-symbol metadata stored in the obarray.
#[derive(Clone, Debug)]
pub struct SymbolData {
    /// The symbol's name.
    pub name: SymId,
    /// Value cell — see [`SymbolValue`] for the indirection variants.
    pub value: SymbolValue,
    /// Function cell (None = void-function).
    pub function: Option<Value>,
    /// Property list (flat alternating key-value pairs stored as HashMap).
    pub plist: FxHashMap<SymId, Value>,
    /// Whether this symbol is declared `special` (always dynamically bound).
    pub special: bool,
    /// Whether this symbol is a constant (defconst).
    pub constant: bool,
    /// Whether this symbol is interned in the global obarray.
    interned_global: bool,
    /// Whether `fmakunbound` explicitly masked the symbol's fallback function.
    function_unbound: bool,
}

impl SymbolData {
    pub fn new(name: SymId) -> Self {
        Self {
            name,
            value: SymbolValue::Plain(None),
            function: None,
            plist: FxHashMap::default(),
            special: false,
            constant: false,
            interned_global: false,
            function_unbound: false,
        }
    }
}

/// The obarray — a table of interned symbols.
///
/// This is the central symbol registry. `intern` looks up or creates symbols,
/// ensuring that `(eq 'foo 'foo)` is always true.
#[derive(Clone, Debug)]
pub struct Obarray {
    symbols: Vec<Option<SymbolData>>,
    global_member_count: usize,
    function_epoch: u64,
}

impl Default for Obarray {
    fn default() -> Self {
        Self::new()
    }
}

impl Obarray {
    fn is_canonical_symbol_id(id: SymId) -> bool {
        is_canonical_id(id)
    }

    fn slot_index(id: SymId) -> usize {
        id.0 as usize
    }

    fn slot(&self, id: SymId) -> Option<&SymbolData> {
        self.symbols
            .get(Self::slot_index(id))
            .and_then(Option::as_ref)
    }

    fn slot_mut(&mut self, id: SymId) -> Option<&mut SymbolData> {
        self.symbols
            .get_mut(Self::slot_index(id))
            .and_then(Option::as_mut)
    }

    fn ensure_slot(&mut self, id: SymId) -> &mut SymbolData {
        let idx = Self::slot_index(id);
        if self.symbols.len() <= idx {
            self.symbols.resize_with(idx + 1, || None);
        }
        self.symbols[idx].get_or_insert_with(|| SymbolData::new(id))
    }

    fn mark_global_member(&mut self, id: SymId) {
        let added = {
            let sym = self.ensure_slot(id);
            if sym.interned_global {
                return;
            }
            sym.interned_global = true;
            let name = resolve_sym(id);
            if name.starts_with(':') {
                // Match GNU lread.c intern_sym: keywords interned in the
                // initial obarray are self-evaluating constants and are marked
                // declared-special.
                sym.special = true;
                sym.constant = true;
                if matches!(sym.value, SymbolValue::Plain(None)) {
                    sym.value = SymbolValue::Plain(Some(Value::keyword_id(id)));
                }
            }
            true
        };
        if added {
            self.global_member_count += 1;
        }
    }

    fn clear_global_member(&mut self, id: SymId) -> bool {
        let Some(sym) = self.slot_mut(id) else {
            return false;
        };
        if !sym.interned_global {
            return false;
        }
        sym.interned_global = false;
        self.global_member_count = self.global_member_count.saturating_sub(1);
        true
    }

    fn ensure_global_member_if_canonical(&mut self, id: SymId) {
        if Self::is_canonical_symbol_id(id) {
            self.mark_global_member(id);
        }
    }

    fn is_global_member(&self, id: SymId) -> bool {
        self.slot(id).is_some_and(|sym| sym.interned_global)
    }

    fn value_from_symbol_id(&self, id: SymId) -> Value {
        let name = resolve_sym(id);
        if self.is_global_member(id) {
            if name == "nil" {
                return Value::NIL;
            }
            if name == "t" {
                return Value::T;
            }
            if name.starts_with(':') {
                return Value::keyword_id(id);
            }
        }
        Value::symbol(id)
    }

    pub fn new() -> Self {
        let mut ob = Self {
            symbols: Vec::new(),
            global_member_count: 0,
            function_epoch: 0,
        };

        // Pre-intern fundamental symbols
        let t_id = intern("t");
        {
            let t_sym = ob.ensure_slot(t_id);
            t_sym.value = SymbolValue::Plain(Some(Value::T));
            t_sym.constant = true;
            t_sym.special = true;
        }
        ob.mark_global_member(t_id);

        let nil_id = intern("nil");
        {
            let nil_sym = ob.ensure_slot(nil_id);
            nil_sym.value = SymbolValue::Plain(Some(Value::NIL));
            nil_sym.constant = true;
            nil_sym.special = true;
        }
        ob.mark_global_member(nil_id);

        ob
    }

    /// Intern a symbol: look up by name, creating if absent.
    /// Returns the symbol name (which is the key for identity).
    pub fn intern(&mut self, name: &str) -> String {
        let id = intern(name);
        self.ensure_symbol_id(id);
        self.mark_global_member(id);
        name.to_string()
    }

    /// Materialize a canonical symbol in the global obarray.
    ///
    /// GNU does this as part of interning into the initial obarray. Neomacs
    /// keeps string interning separate from obarray storage, so runtime paths
    /// that operate on canonical symbols can explicitly request the same
    /// initial-obarray semantics here.
    pub fn ensure_interned_global_id(&mut self, id: SymId) {
        self.ensure_global_member_if_canonical(id);
    }

    /// Look up a symbol without creating it. Returns None if not interned.
    pub fn intern_soft(&self, name: &str) -> Option<&SymbolData> {
        let id = lookup_interned(name)?;
        self.slot(id).filter(|sym| sym.interned_global)
    }

    /// Get symbol data (mutable). Interns the symbol if needed.
    pub fn get_or_intern(&mut self, name: &str) -> &mut SymbolData {
        let id = intern(name);
        self.mark_global_member(id);
        self.ensure_symbol_id(id)
    }

    /// Get symbol data (immutable).
    pub fn get(&self, name: &str) -> Option<&SymbolData> {
        let id = lookup_interned(name)?;
        self.slot(id).filter(|sym| sym.interned_global)
    }

    /// Get symbol data (mutable).
    pub fn get_mut(&mut self, name: &str) -> Option<&mut SymbolData> {
        let id = lookup_interned(name)?;
        self.slot_mut(id).filter(|sym| sym.interned_global)
    }

    /// Ensure symbol storage exists for an arbitrary symbol id.
    pub fn ensure_symbol_id(&mut self, id: SymId) -> &mut SymbolData {
        self.ensure_slot(id)
    }

    /// Get symbol data by identity.
    pub fn get_by_id(&self, id: SymId) -> Option<&SymbolData> {
        self.slot(id)
    }

    /// Get mutable symbol data by identity.
    pub fn get_mut_by_id(&mut self, id: SymId) -> Option<&mut SymbolData> {
        self.slot_mut(id)
    }

    /// Get the value cell of a symbol.
    pub fn symbol_value(&self, name: &str) -> Option<&Value> {
        self.symbol_value_id(intern(name))
    }

    /// Get the value cell of a symbol by identity.
    /// Follows `Alias` chains (with cycle detection, max 50 hops).
    pub fn symbol_value_id(&self, id: SymId) -> Option<&Value> {
        let mut current = id;
        for _ in 0..50 {
            match self.slot(current)?.value {
                SymbolValue::Plain(ref v) => return v.as_ref(),
                SymbolValue::Alias(target) => current = target,
                SymbolValue::BufferLocal { ref default, .. } => return default.as_ref(),
                SymbolValue::Forwarded => return None,
            }
        }
        None // alias cycle — give up
    }

    /// Set the value cell of a symbol. Interns if needed.
    pub fn set_symbol_value(&mut self, name: &str, value: Value) {
        let id = intern(name);
        self.mark_global_member(id);
        self.set_symbol_value_id_inner(id, value);
    }

    /// Set the value cell of a symbol by identity.
    pub fn set_symbol_value_id(&mut self, id: SymId, value: Value) {
        self.ensure_global_member_if_canonical(id);
        self.set_symbol_value_id_inner(id, value);
    }

    /// Inner helper: follow aliases and write the value at the resolved target.
    fn set_symbol_value_id_inner(&mut self, id: SymId, value: Value) {
        let target = self.resolve_alias_for_write(id);
        let sym = self.ensure_symbol_id(target);
        match sym.value {
            SymbolValue::Plain(_) => sym.value = SymbolValue::Plain(Some(value)),
            SymbolValue::BufferLocal {
                ref mut default, ..
            } => *default = Some(value),
            SymbolValue::Forwarded => { /* no-op placeholder */ }
            SymbolValue::Alias(_) => {
                // resolve_alias_for_write should have resolved this, but
                // as a safety fallback write as Plain.
                sym.value = SymbolValue::Plain(Some(value));
            }
        }
    }

    /// Visit each stored symbol value cell that currently holds a `Value`.
    pub fn for_each_value_cell_mut(&mut self, mut f: impl FnMut(&mut Value)) {
        for sym in self.symbols.iter_mut().flatten() {
            match &mut sym.value {
                SymbolValue::Plain(Some(value)) => f(value),
                SymbolValue::BufferLocal {
                    default: Some(value),
                    ..
                } => f(value),
                SymbolValue::Plain(None)
                | SymbolValue::BufferLocal { default: None, .. }
                | SymbolValue::Alias(_)
                | SymbolValue::Forwarded => {}
            }
        }
    }

    /// Follow alias chain for a mutable write, returning the resolved SymId.
    /// Max 50 hops to prevent infinite loops.
    fn resolve_alias_for_write(&mut self, id: SymId) -> SymId {
        let mut current = id;
        for _ in 0..50 {
            match self.slot(current) {
                Some(s) => match s.value {
                    SymbolValue::Alias(target) => current = target,
                    _ => return current,
                },
                None => return current,
            }
        }
        current // cycle — write to the last hop
    }

    /// Get the function cell of a symbol.
    pub fn symbol_function(&self, name: &str) -> Option<&Value> {
        self.symbol_function_id(intern(name))
    }

    /// Get the function cell of a symbol by identity.
    pub fn symbol_function_id(&self, id: SymId) -> Option<&Value> {
        let sym = self.slot(id)?;
        if sym.function_unbound {
            return None;
        }
        sym.function.as_ref()
    }

    /// Get the function cell of a symbol from its Value representation.
    /// Uses the SymId directly, which works correctly for both interned
    /// and uninterned symbols (unlike `symbol_function(name)` which
    /// re-interns the name and would miss uninterned symbol function cells).
    pub fn symbol_function_of_value(&self, value: &Value) -> Option<&Value> {
        match value.kind() {
            ValueKind::Symbol(id) => self.symbol_function_id(id),
            ValueKind::Nil => self.symbol_function("nil"),
            ValueKind::T => self.symbol_function("t"),
            _ => None,
        }
    }

    /// Set the function cell of a symbol (fset). Interns if needed.
    pub fn set_symbol_function(&mut self, name: &str, function: Value) {
        let id = intern(name);
        self.mark_global_member(id);
        let sym = self.ensure_symbol_id(id);
        sym.function = Some(function);
        sym.function_unbound = false;
        self.function_epoch = self.function_epoch.wrapping_add(1);
    }

    /// Set the function cell of a symbol by identity.
    pub fn set_symbol_function_id(&mut self, id: SymId, function: Value) {
        self.ensure_global_member_if_canonical(id);
        let sym = self.ensure_symbol_id(id);
        sym.function = Some(function);
        sym.function_unbound = false;
        self.function_epoch = self.function_epoch.wrapping_add(1);
    }

    /// Remove the function cell (fmakunbound).
    pub fn fmakunbound(&mut self, name: &str) {
        self.fmakunbound_id(intern(name));
    }

    /// Remove the function cell by identity.
    pub fn fmakunbound_id(&mut self, id: SymId) {
        self.ensure_global_member_if_canonical(id);
        let sym = self.ensure_symbol_id(id);
        let mut changed = !sym.function_unbound;
        sym.function_unbound = true;
        changed |= sym.function.take().is_some();
        if changed {
            self.function_epoch = self.function_epoch.wrapping_add(1);
        }
    }

    /// Remove function cell without marking as explicitly unbound.
    /// Used for init-time masking of lazily-materialized builtins.
    pub fn clear_function_silent(&mut self, name: &str) {
        self.clear_function_silent_id(intern(name));
    }

    /// Remove function cell without marking as explicitly unbound, by identity.
    pub fn clear_function_silent_id(&mut self, id: SymId) {
        if let Some(sym) = self.slot_mut(id) {
            if sym.function.take().is_some() {
                self.function_epoch = self.function_epoch.wrapping_add(1);
            }
        }
    }

    /// Remove the value cell (makunbound).
    pub fn makunbound(&mut self, name: &str) {
        self.makunbound_id(intern(name));
    }

    /// Remove the value cell by identity.
    /// Follows alias chains (max 50 hops).
    pub fn makunbound_id(&mut self, id: SymId) {
        self.ensure_global_member_if_canonical(id);
        let target = self.resolve_alias_for_write(id);
        if let Some(sym) = self.slot_mut(target) {
            if !sym.constant {
                match sym.value {
                    SymbolValue::Plain(_) => sym.value = SymbolValue::Plain(None),
                    SymbolValue::BufferLocal {
                        ref mut default, ..
                    } => *default = None,
                    SymbolValue::Forwarded => { /* no-op */ }
                    SymbolValue::Alias(_) => sym.value = SymbolValue::Plain(None),
                }
            }
        }
    }

    /// Check if a symbol is bound (has a value cell).
    pub fn boundp(&self, name: &str) -> bool {
        self.boundp_id(intern(name))
    }

    /// Check if a symbol is bound by identity.
    /// Follows alias chains (max 50 hops).
    pub fn boundp_id(&self, id: SymId) -> bool {
        let mut current = id;
        for _ in 0..50 {
            match self.slot(current) {
                Some(s) => match &s.value {
                    SymbolValue::Plain(v) => return v.is_some(),
                    SymbolValue::Alias(target) => current = *target,
                    SymbolValue::BufferLocal { default, .. } => return default.is_some(),
                    SymbolValue::Forwarded => return false,
                },
                None => return false,
            }
        }
        false // cycle
    }

    /// Check if a symbol has a function cell.
    pub fn fboundp(&self, name: &str) -> bool {
        self.fboundp_id(intern(name))
    }

    /// Check if a symbol has a function cell by identity.
    pub fn fboundp_id(&self, id: SymId) -> bool {
        self.slot(id)
            .filter(|sym| !sym.function_unbound)
            .and_then(|s| s.function.as_ref())
            .is_some_and(|f| !f.is_nil())
    }

    /// Get a property from the symbol's plist.
    pub fn get_property(&self, name: &str, prop: &str) -> Option<&Value> {
        self.get_property_id(intern(name), intern(prop))
    }

    /// Get a property from the symbol's plist by identity.
    pub fn get_property_id(&self, symbol: SymId, prop: SymId) -> Option<&Value> {
        self.slot(symbol).and_then(|s| s.plist.get(&prop))
    }

    /// Set a property on the symbol's plist.
    pub fn put_property(&mut self, name: &str, prop: &str, value: Value) {
        let symbol = intern(name);
        self.mark_global_member(symbol);
        let sym = self.ensure_symbol_id(symbol);
        sym.plist.insert(intern(prop), value);
    }

    /// Set a property on the symbol's plist by identity.
    pub fn put_property_id(&mut self, symbol: SymId, prop: SymId, value: Value) {
        self.ensure_global_member_if_canonical(symbol);
        let sym = self.ensure_symbol_id(symbol);
        sym.plist.insert(prop, value);
    }

    /// Replace the complete plist for a symbol by identity.
    pub fn replace_symbol_plist_id<I>(&mut self, symbol: SymId, entries: I)
    where
        I: IntoIterator<Item = (SymId, Value)>,
    {
        self.ensure_global_member_if_canonical(symbol);
        let sym = self.ensure_symbol_id(symbol);
        sym.plist.clear();
        sym.plist.extend(entries);
    }

    /// Get the symbol's full plist as a flat list.
    pub fn symbol_plist(&self, name: &str) -> Value {
        self.symbol_plist_id(intern(name))
    }

    /// Get the symbol's full plist as a flat list by identity.
    pub fn symbol_plist_id(&self, id: SymId) -> Value {
        match self.slot(id) {
            Some(sym) if !sym.plist.is_empty() => {
                let mut items = Vec::new();
                for (k, v) in &sym.plist {
                    items.push(self.value_from_symbol_id(*k));
                    items.push(*v);
                }
                Value::list(items)
            }
            _ => Value::NIL,
        }
    }

    /// Mark a symbol as special (dynamically bound).
    pub fn make_special(&mut self, name: &str) {
        let id = intern(name);
        self.mark_global_member(id);
        self.ensure_symbol_id(id).special = true;
    }

    /// Mark a symbol as special by identity.
    pub fn make_special_id(&mut self, id: SymId) {
        self.ensure_global_member_if_canonical(id);
        self.ensure_symbol_id(id).special = true;
    }

    /// Clear the special flag on a symbol.
    pub fn make_non_special(&mut self, name: &str) {
        let id = intern(name);
        self.mark_global_member(id);
        self.ensure_symbol_id(id).special = false;
    }

    /// Clear the special flag on a symbol by identity.
    pub fn make_non_special_id(&mut self, id: SymId) {
        self.ensure_global_member_if_canonical(id);
        self.ensure_symbol_id(id).special = false;
    }

    /// Check if a symbol is special.
    pub fn is_special(&self, name: &str) -> bool {
        self.is_special_id(intern(name))
    }

    /// Check if a symbol is special by identity.
    pub fn is_special_id(&self, id: SymId) -> bool {
        self.slot(id).is_some_and(|s| s.special)
    }

    /// Check if a symbol is a constant.
    pub fn is_constant(&self, name: &str) -> bool {
        self.is_constant_id(intern(name))
    }

    /// Check if a symbol is a constant by identity.
    pub fn is_constant_id(&self, id: SymId) -> bool {
        (Self::is_canonical_symbol_id(id) && resolve_sym(id).starts_with(':'))
            || self.slot(id).is_some_and(|s| s.constant)
    }

    /// Mark a symbol as a hard constant (like SYMBOL_NOWRITE in GNU Emacs).
    pub fn set_constant(&mut self, name: &str) {
        let id = intern(name);
        self.set_constant_id(id);
    }

    /// Mark a symbol as a hard constant (like SYMBOL_NOWRITE in GNU Emacs) by identity.
    pub fn set_constant_id(&mut self, id: SymId) {
        self.ensure_global_member_if_canonical(id);
        self.ensure_symbol_id(id).constant = true;
    }

    // ------------------------------------------------------------------
    // SymbolValue-aware helpers (buffer-local / alias introspection)
    // ------------------------------------------------------------------

    /// Mark a symbol as a buffer-local variable in the obarray.
    /// Preserves any existing default value from `Plain` or `BufferLocal`.
    pub fn make_buffer_local(&mut self, name: &str, local_if_set: bool) {
        let id = intern(name);
        self.mark_global_member(id);
        let sym = self.ensure_symbol_id(id);
        let old_default = match &sym.value {
            SymbolValue::Plain(v) => v.clone(),
            SymbolValue::BufferLocal { default, .. } => default.clone(),
            _ => None,
        };
        sym.value = SymbolValue::BufferLocal {
            default: old_default,
            local_if_set,
        };
    }

    /// Install a variable-alias edge: reading/writing `id` will redirect to `target`.
    pub fn make_alias(&mut self, id: SymId, target: SymId) {
        let sym = self.ensure_symbol_id(id);
        sym.value = SymbolValue::Alias(target);
    }

    /// Check whether a symbol is a buffer-local variable in the obarray.
    pub fn is_buffer_local(&self, name: &str) -> bool {
        self.is_buffer_local_id(intern(name))
    }

    /// Check whether a symbol is a buffer-local variable by identity.
    pub fn is_buffer_local_id(&self, id: SymId) -> bool {
        self.slot(id)
            .is_some_and(|s| matches!(s.value, SymbolValue::BufferLocal { .. }))
    }

    /// Check whether a symbol is an alias by identity.
    pub fn is_alias_id(&self, id: SymId) -> bool {
        self.slot(id)
            .is_some_and(|s| matches!(s.value, SymbolValue::Alias(_)))
    }

    /// Get the default value of a symbol, following aliases.
    /// For `Plain` and `BufferLocal` this is the direct/default value;
    /// for `Alias` it follows the chain; for `Forwarded` it returns `None`.
    pub fn default_value_id(&self, id: SymId) -> Option<&Value> {
        let mut current = id;
        for _ in 0..50 {
            match self.slot(current)?.value {
                SymbolValue::Plain(ref v) => return v.as_ref(),
                SymbolValue::BufferLocal { ref default, .. } => return default.as_ref(),
                SymbolValue::Alias(target) => current = target,
                SymbolValue::Forwarded => return None,
            }
        }
        None
    }

    /// Follow function indirection (defalias chains).
    /// Returns the final function value, following symbol aliases.
    pub fn indirect_function(&self, name: &str) -> Option<Value> {
        self.indirect_function_id(intern(name))
    }

    /// Follow function indirection (defalias chains) by canonical symbol id.
    /// Returns the final function value, following symbol aliases.
    pub fn indirect_function_id(&self, id: SymId) -> Option<Value> {
        let mut current_id = id;
        let mut depth = 0;
        loop {
            if depth > 100 {
                return None; // Circular alias chain
            }
            let func = self.slot(current_id)?.function.as_ref()?;
            match func.kind() {
                ValueKind::Symbol(id) => {
                    current_id = id;
                    depth += 1;
                }
                _ => return Some(*func),
            }
        }
    }

    /// Number of interned symbols.
    pub fn len(&self) -> usize {
        self.global_member_count
    }

    pub fn is_empty(&self) -> bool {
        self.global_member_count == 0
    }

    /// All interned symbol names.
    pub fn all_symbols(&self) -> Vec<&str> {
        self.symbols
            .iter()
            .flatten()
            .filter(|sym| sym.interned_global)
            .map(|sym| resolve_sym(sym.name))
            .collect()
    }

    /// Remove a symbol from the obarray.  Returns `true` if it was present.
    pub fn unintern(&mut self, name: &str) -> bool {
        let id = intern(name);
        let removed_symbol = self.clear_global_member(id);
        if removed_symbol {
            self.function_epoch = self.function_epoch.wrapping_add(1);
        }
        removed_symbol
    }

    /// Monotonic epoch for function-cell mutations.
    pub fn function_epoch(&self) -> u64 {
        self.function_epoch
    }

    /// True when `fmakunbound` explicitly masked this symbol's fallback function definition.
    pub fn is_function_unbound(&self, name: &str) -> bool {
        self.is_function_unbound_id(intern(name))
    }

    /// True when `fmakunbound` explicitly masked this symbol's fallback function definition.
    pub fn is_function_unbound_id(&self, id: SymId) -> bool {
        self.slot(id).is_some_and(|sym| sym.function_unbound)
    }

    // -----------------------------------------------------------------------
    // pdump accessors
    // -----------------------------------------------------------------------

    /// Iterate over all (SymId, &SymbolData) pairs (for pdump serialization).
    pub(crate) fn iter_symbols(&self) -> impl Iterator<Item = (SymId, &SymbolData)> {
        self.symbols.iter().enumerate().filter_map(|(idx, slot)| {
            debug_assert!(idx <= u32::MAX as usize, "symbol index overflow");
            slot.as_ref().map(|sym| (SymId(idx as u32), sym))
        })
    }

    /// Iterate over ids interned in the global obarray.
    pub(crate) fn global_member_ids(&self) -> impl Iterator<Item = SymId> + '_ {
        self.iter_symbols()
            .filter(|(_, sym)| sym.interned_global)
            .map(|(id, _)| id)
    }

    /// Iterate over fmakunbound'd symbol ids (for pdump serialization).
    pub(crate) fn function_unbound_ids(&self) -> impl Iterator<Item = SymId> + '_ {
        self.iter_symbols()
            .filter(|(_, sym)| sym.function_unbound)
            .map(|(id, _)| id)
    }

    /// Reconstruct an Obarray from pdump data.
    pub(crate) fn from_dump(
        symbols: Vec<(SymId, SymbolData)>,
        global_members: Vec<SymId>,
        function_unbound: Vec<SymId>,
        function_epoch: u64,
    ) -> Self {
        let mut ob = Self {
            symbols: Vec::new(),
            global_member_count: 0,
            function_epoch,
        };
        for (id, mut sym) in symbols {
            sym.interned_global = false;
            sym.function_unbound = false;
            *ob.ensure_slot(id) = sym;
        }
        for id in global_members {
            ob.mark_global_member(id);
        }
        for id in function_unbound {
            ob.ensure_slot(id).function_unbound = true;
        }
        ob
    }
}

impl GcTrace for Obarray {
    fn trace_roots(&self, roots: &mut Vec<Value>) {
        for sym in self.symbols.iter().flatten() {
            match &sym.value {
                SymbolValue::Plain(Some(v)) => roots.push(*v),
                SymbolValue::BufferLocal {
                    default: Some(v), ..
                } => roots.push(*v),
                SymbolValue::Plain(None)
                | SymbolValue::BufferLocal { default: None, .. }
                | SymbolValue::Alias(_)
                | SymbolValue::Forwarded => {}
            }
            if let Some(ref f) = sym.function {
                roots.push(*f);
            }
            for pval in sym.plist.values() {
                roots.push(*pval);
            }
        }
    }
}
#[cfg(test)]
#[path = "symbol_test.rs"]
mod tests;