ryo-symbol 0.1.0

Symbol system for Rust codebase - unique identifiers and file path management
Documentation
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! SymbolRegistry - Central registry for symbol management
//!
//! # Persistent Identity (UUID)
//!
//! Every symbol is automatically assigned a UUID at registration time.
//! This UUID serves as the **persistent identity** that survives:
//! - Server restarts (SymbolId is session-volatile)
//! - Symbol renames (SymbolPath changes, UUID stays)
//! - Code refactoring (same entity, different location)
//!
//! ## Why UUID, not SymbolPath?
//!
//! SymbolPath is like Active Directory's Distinguished Name (DN) - it describes
//! **where** something is, not **what** it is. When you rename `foo::Bar` to
//! `foo::Baz`, the SymbolPath changes but the entity remains the same.
//!
//! ## External Output Requirements
//!
//! **All external APIs that expose symbol references MUST use UUID.**
//!
//! ### TODO: Migrate to UUID-based output
//!
//! The following locations currently use SymbolPath or SymbolId strings
//! and should be migrated to include UUID:
//!
//! - `ryo-app/src/api/types.rs`:
//!   - `Suggestion.symbol_path` → add `uuid: Uuid`
//!   - `TypeAnalysisResponse.symbol_id` → add `uuid: Uuid`
//!   - `TypeAnalysisResponse.supertraits` → `Vec<SymbolRef>` with uuid
//!   - `TypeAnalysisResponse.implementors` → `Vec<SymbolRef>` with uuid
//!   - `TypeImpactInfo.containing_types` → `Vec<SymbolRef>` with uuid
//!   - `VarInfo.symbol_path` → add `uuid: Uuid`
//!   - `ChainNodeInfo.id` → add `uuid: Uuid`
//!   - `CascadeResponse.callers/users` → `Vec<SymbolRef>` with uuid
//!
//! - `ryo-storage/src/txlog/entry.rs`:
//!   - `TxAction::MutationApplied.affected_symbols` → `Vec<Uuid>`
//!   - `MutationRecord.affected_symbols` → `Vec<Uuid>`
//!
//! ## Performance Note
//!
//! Current implementation assigns UUID to ALL symbols at registration.
//! If memory becomes an issue (~80 bytes per symbol), consider lazy allocation
//! only when symbols are exposed via external APIs.

use std::collections::HashMap;

use slotmap::{SecondaryMap, SlotMap};
use uuid::Uuid;

use crate::error::{InvalidSymbolId, RegistrationError, RenameError, UnregisterReexportError};
use crate::file_path::WorkspaceFilePath;
use crate::id::SymbolId;
use crate::kind::SymbolKind;
use crate::path::SymbolPath;
use crate::span::{FileSpan, Visibility};
use crate::var_scope::VarScope;

/// Re-export information
#[derive(Debug, Clone)]
pub struct ReExportInfo {
    /// Re-export path (alias)
    pub alias_path: SymbolPath,
    /// File where the re-export is defined
    pub origin_file: WorkspaceFilePath,
}

/// Central registry for symbol management
///
/// # Single Point of Access
///
/// **All symbol operations must go through SymbolRegistry.**
///
/// - Get SymbolId: `register()` or `lookup()`
/// - Get/update metadata: `kind()`, `span()`, `set_span()`, etc.
/// - Graph operations also use SymbolId
///
/// # Responsibilities
/// - Bidirectional SymbolPath ↔ SymbolId conversion
/// - Metadata management (Kind, Span, Visibility, etc.)
/// - Symbol lifecycle management
///
/// # Thread Safety
/// - Read operations are thread-safe
/// - Write operations require exclusive access
///   (Executor controls this at Tick boundaries)
#[derive(Clone)]
pub struct SymbolRegistry {
    // === Core Mappings ===
    /// SymbolId → SymbolPath (reverse lookup)
    id_to_path: SlotMap<SymbolId, SymbolPath>,
    /// SymbolPath → SymbolId (forward lookup)
    path_to_id: HashMap<SymbolPath, SymbolId>,

    // === Metadata (SecondaryMap) ===
    /// Symbol kind
    kinds: SecondaryMap<SymbolId, SymbolKind>,
    /// File location
    spans: SecondaryMap<SymbolId, FileSpan>,
    /// Visibility
    visibility: SecondaryMap<SymbolId, Visibility>,
    /// Parent symbol (for InSymbol)
    parents: SecondaryMap<SymbolId, SymbolId>,

    // === Re-export Management ===
    /// Re-export info (canonical → aliases)
    re_exports: SecondaryMap<SymbolId, Vec<ReExportInfo>>,
    /// Re-export reverse lookup (alias path → canonical SymbolId)
    alias_to_canonical: HashMap<SymbolPath, SymbolId>,

    // === Persistent Identity (UUID) ===
    /// SymbolId → Uuid (O(1) lookup for serialization)
    id_to_uuid: SecondaryMap<SymbolId, Uuid>,
    /// Uuid → SymbolId (reverse lookup for deserialization)
    uuid_to_id: HashMap<Uuid, SymbolId>,
    /// Preloaded UUID mappings from previous session (SymbolPath → Uuid)
    /// Used during register() to restore persistent identity
    preloaded_uuids: HashMap<SymbolPath, Uuid>,
}

impl SymbolRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            id_to_path: SlotMap::with_key(),
            path_to_id: HashMap::new(),
            kinds: SecondaryMap::new(),
            spans: SecondaryMap::new(),
            visibility: SecondaryMap::new(),
            parents: SecondaryMap::new(),
            re_exports: SecondaryMap::new(),
            alias_to_canonical: HashMap::new(),
            id_to_uuid: SecondaryMap::new(),
            uuid_to_id: HashMap::new(),
            preloaded_uuids: HashMap::new(),
        }
    }

    /// Create with pre-allocated capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            id_to_path: SlotMap::with_capacity_and_key(capacity),
            path_to_id: HashMap::with_capacity(capacity),
            kinds: SecondaryMap::new(),
            spans: SecondaryMap::new(),
            visibility: SecondaryMap::new(),
            parents: SecondaryMap::new(),
            re_exports: SecondaryMap::new(),
            alias_to_canonical: HashMap::new(),
            id_to_uuid: SecondaryMap::new(),
            uuid_to_id: HashMap::with_capacity(capacity),
            preloaded_uuids: HashMap::new(),
        }
    }

    // ========== Registration ==========

    /// Register a symbol (returns existing ID if already registered)
    ///
    /// # Returns
    /// - `Ok(SymbolId)`: Registration successful (new or existing)
    /// - `Err(RegistrationError)`: Registration failed
    pub fn register(
        &mut self,
        path: SymbolPath,
        kind: SymbolKind,
    ) -> Result<SymbolId, RegistrationError> {
        // Check if already registered
        if let Some(&existing_id) = self.path_to_id.get(&path) {
            // Verify kind matches
            if let Some(&existing_kind) = self.kinds.get(existing_id) {
                if existing_kind != kind {
                    return Err(RegistrationError::ConflictingKind {
                        path: Box::new(path),
                        existing: existing_kind,
                        new: kind,
                    });
                }
            }
            return Ok(existing_id);
        }

        // Register new symbol
        let id = self.id_to_path.insert(path.clone());
        self.path_to_id.insert(path.clone(), id);
        self.kinds.insert(id, kind);

        // Use preloaded UUID if available (from previous session), otherwise generate new
        let uuid = self
            .preloaded_uuids
            .remove(&path)
            .unwrap_or_else(Uuid::new_v4);
        self.id_to_uuid.insert(id, uuid);
        self.uuid_to_id.insert(uuid, id);

        Ok(id)
    }

    /// Register with full metadata
    pub fn register_with_metadata(
        &mut self,
        path: SymbolPath,
        kind: SymbolKind,
        span: Option<FileSpan>,
        vis: Option<Visibility>,
    ) -> Result<SymbolId, RegistrationError> {
        let id = self.register(path, kind)?;

        if let Some(span) = span {
            self.spans.insert(id, span);
        }
        if let Some(vis) = vis {
            self.visibility.insert(id, vis);
        }

        Ok(id)
    }

    /// Register a variable (InSymbol)
    ///
    /// Creates a path like `parent::$scope::name` and registers it.
    ///
    /// # Arguments
    /// - `containing_symbol`: Parent symbol (function/method/struct)
    /// - `scope`: Variable scope type
    /// - `name`: Variable name
    /// - `kind`: Symbol kind (Variable, Parameter, or Field)
    pub fn register_var(
        &mut self,
        containing_symbol: SymbolId,
        scope: VarScope,
        name: &str,
        kind: SymbolKind,
    ) -> Result<SymbolId, RegistrationError> {
        // Get parent path
        let parent_path = self
            .path(containing_symbol)
            .ok_or(RegistrationError::InvalidParent)?
            .clone();

        // Create variable path
        let var_path = parent_path
            .with_var_scope(scope, name)
            .map_err(RegistrationError::InvalidPath)?;

        // Register
        let id = self.register(var_path, kind)?;

        // Record parent relationship
        self.parents.insert(id, containing_symbol);

        Ok(id)
    }

    // ========== Lookup ==========

    /// SymbolPath → SymbolId (O(1) hash lookup)
    ///
    /// Also resolves re-export aliases to their canonical ID.
    #[inline]
    pub fn lookup(&self, path: &SymbolPath) -> Option<SymbolId> {
        // Try canonical path first
        if let Some(&id) = self.path_to_id.get(path) {
            return Some(id);
        }
        // Try as alias
        self.alias_to_canonical.get(path).copied()
    }

    /// SymbolId → SymbolPath (O(1) array access)
    #[inline]
    pub fn resolve(&self, id: SymbolId) -> Option<&SymbolPath> {
        self.id_to_path.get(id)
    }

    /// Alias for resolve() - get path from ID
    #[inline]
    pub fn path(&self, id: SymbolId) -> Option<&SymbolPath> {
        self.resolve(id)
    }

    /// Get SymbolRef (ID + Path) for unified display
    ///
    /// # Format
    /// Returns `SymbolRef` which displays as: `SymbolId(2v1)@path::to::symbol`
    ///
    /// # Example
    /// ```ignore
    /// let sym_ref = registry.get_ref(id)?;
    /// println!("{}", sym_ref);  // SymbolId(2v1)@my_crate::MyStruct
    /// ```
    #[inline]
    pub fn get_ref(&self, id: SymbolId) -> Option<crate::SymbolRef> {
        self.resolve(id)
            .map(|path| crate::SymbolRef::new(id, path.clone()))
    }

    /// Check if SymbolId is valid (with generation check)
    #[inline]
    pub fn contains(&self, id: SymbolId) -> bool {
        self.id_to_path.contains_key(id)
    }

    // ========== Metadata Access ==========

    /// Get kind
    #[inline]
    pub fn kind(&self, id: SymbolId) -> Option<SymbolKind> {
        self.kinds.get(id).copied()
    }

    /// Get span
    #[inline]
    pub fn span(&self, id: SymbolId) -> Option<&FileSpan> {
        self.spans.get(id)
    }

    /// Get visibility
    #[inline]
    pub fn visibility(&self, id: SymbolId) -> Option<&Visibility> {
        self.visibility.get(id)
    }

    /// Get parent symbol (for InSymbol)
    #[inline]
    pub fn parent(&self, id: SymbolId) -> Option<SymbolId> {
        self.parents.get(id).copied()
    }

    // ========== Metadata Mutation ==========

    /// Set/update span
    pub fn set_span(&mut self, id: SymbolId, span: FileSpan) -> Result<(), InvalidSymbolId> {
        if !self.contains(id) {
            return Err(InvalidSymbolId(id));
        }
        self.spans.insert(id, span);
        Ok(())
    }

    /// Set/update visibility
    pub fn set_visibility(&mut self, id: SymbolId, vis: Visibility) -> Result<(), InvalidSymbolId> {
        if !self.contains(id) {
            return Err(InvalidSymbolId(id));
        }
        self.visibility.insert(id, vis);
        Ok(())
    }

    /// Set/update kind
    pub fn set_kind(&mut self, id: SymbolId, kind: SymbolKind) -> Result<(), InvalidSymbolId> {
        if !self.contains(id) {
            return Err(InvalidSymbolId(id));
        }
        self.kinds.insert(id, kind);
        Ok(())
    }

    /// Remove a symbol from the registry
    ///
    /// Returns the path of the removed symbol, or None if the ID was invalid.
    /// Also removes the persistent UUID mapping if present.
    pub fn remove(&mut self, id: SymbolId) -> Option<SymbolPath> {
        let path = self.id_to_path.remove(id)?;
        self.path_to_id.remove(&path);
        self.kinds.remove(id);
        self.spans.remove(id);
        self.visibility.remove(id);
        self.parents.remove(id);

        // Clean up re-exports pointing to this symbol
        if let Some(aliases) = self.re_exports.remove(id) {
            for info in aliases {
                self.alias_to_canonical.remove(&info.alias_path);
            }
        }

        // Clean up UUID mapping
        if let Some(uuid) = self.id_to_uuid.remove(id) {
            self.uuid_to_id.remove(&uuid);
        }

        Some(path)
    }

    /// Rename a symbol
    ///
    /// Returns the old path on success.
    pub fn rename(
        &mut self,
        id: SymbolId,
        new_path: SymbolPath,
    ) -> Result<SymbolPath, RenameError> {
        // Validate ID exists
        let old_path = self
            .id_to_path
            .get(id)
            .ok_or(RenameError::InvalidId(id))?
            .clone();

        // Check new path doesn't conflict
        if self.path_to_id.contains_key(&new_path) {
            return Err(RenameError::PathExists(Box::new(new_path)));
        }

        // Update mappings
        self.path_to_id.remove(&old_path);
        self.path_to_id.insert(new_path.clone(), id);
        self.id_to_path[id] = new_path;

        Ok(old_path)
    }

    // ========== Name-based Lookup ==========

    /// Find all symbols with the given name (last segment of path).
    ///
    /// Also includes canonical symbols that have re-export aliases matching the name.
    pub fn find_by_name(&self, name: &str) -> Vec<SymbolId> {
        let mut results: Vec<SymbolId> = self
            .id_to_path
            .iter()
            .filter(|(_, path)| path.name() == name)
            .map(|(id, _)| id)
            .collect();

        // Include canonical IDs reachable via alias paths matching this name
        for (alias_path, &canonical_id) in &self.alias_to_canonical {
            if alias_path.name() == name && !results.contains(&canonical_id) {
                results.push(canonical_id);
            }
        }

        results
    }

    /// Find a single symbol by name (returns first match)
    pub fn lookup_by_name(&self, name: &str) -> Option<SymbolId> {
        self.id_to_path
            .iter()
            .find(|(_, path)| path.name() == name)
            .map(|(id, _)| id)
    }

    // ========== Re-export Management ==========

    /// Register a re-export
    pub fn register_reexport(
        &mut self,
        canonical_id: SymbolId,
        alias_path: SymbolPath,
        origin_file: WorkspaceFilePath,
    ) -> Result<(), InvalidSymbolId> {
        if !self.contains(canonical_id) {
            return Err(InvalidSymbolId(canonical_id));
        }

        // Add alias → canonical mapping
        self.alias_to_canonical
            .insert(alias_path.clone(), canonical_id);

        // Add canonical → aliases mapping
        let info = ReExportInfo {
            alias_path,
            origin_file,
        };
        self.re_exports
            .entry(canonical_id)
            .expect("canonical_id was validated by self.contains() above")
            .or_default()
            .push(info);

        Ok(())
    }

    /// Unregister a re-export
    pub fn unregister_reexport(
        &mut self,
        alias_path: &SymbolPath,
    ) -> Result<(), UnregisterReexportError> {
        let canonical_id = self
            .alias_to_canonical
            .remove(alias_path)
            .ok_or(UnregisterReexportError::NotFound)?;

        if let Some(aliases) = self.re_exports.get_mut(canonical_id) {
            aliases.retain(|info| &info.alias_path != alias_path);
            if aliases.is_empty() {
                self.re_exports.remove(canonical_id);
            }
        }

        Ok(())
    }

    /// Get re-exports for a symbol
    pub fn re_exports(&self, id: SymbolId) -> Option<&[ReExportInfo]> {
        self.re_exports.get(id).map(|v| v.as_slice())
    }

    // ========== Persistent Identity (UUID) ==========

    /// Register a symbol with persistent UUID
    ///
    /// This method assigns a stable UUID to the symbol that survives across sessions.
    /// Use this for symbols that need to be tracked through renames or serialized.
    ///
    /// # Arguments
    /// - `path`: Symbol path
    /// - `kind`: Symbol kind
    /// - `uuid`: `Some(uuid)` when restoring from serialized data, `None` to generate new
    ///
    /// # Returns
    /// - `Ok((SymbolId, Uuid))`: The runtime ID and persistent UUID
    /// - `Err(RegistrationError)`: Registration failed
    ///
    /// # Example
    /// ```ignore
    /// // New symbol (generates UUID)
    /// let (id, uuid) = registry.register_persistent(path, kind, None)?;
    ///
    /// // Restore from serialized data
    /// let (id, uuid) = registry.register_persistent(path, kind, Some(saved_uuid))?;
    /// ```
    pub fn register_persistent(
        &mut self,
        path: SymbolPath,
        kind: SymbolKind,
        uuid: Option<Uuid>,
    ) -> Result<(SymbolId, Uuid), RegistrationError> {
        // Standard registration
        let id = self.register(path, kind)?;

        // Check if UUID already assigned (idempotent for existing symbols)
        if let Some(&existing_uuid) = self.id_to_uuid.get(id) {
            // If caller provided a UUID, verify it matches
            if let Some(provided) = uuid {
                if provided != existing_uuid {
                    // UUID conflict - this is a programming error
                    // The same symbol shouldn't have different UUIDs
                    return Err(RegistrationError::UuidConflict {
                        id,
                        existing: existing_uuid,
                        provided,
                    });
                }
            }
            return Ok((id, existing_uuid));
        }

        // Assign UUID (use provided or generate new)
        let final_uuid = uuid.unwrap_or_else(Uuid::new_v4);
        self.id_to_uuid.insert(id, final_uuid);
        self.uuid_to_id.insert(final_uuid, id);

        Ok((id, final_uuid))
    }

    /// Assign a persistent UUID to an existing symbol
    ///
    /// Use this to add persistence to a symbol that was registered without UUID.
    ///
    /// # Returns
    /// - `Ok(Uuid)`: The assigned UUID (existing or new)
    /// - `Err(InvalidSymbolId)`: Symbol doesn't exist
    pub fn assign_uuid(
        &mut self,
        id: SymbolId,
        uuid: Option<Uuid>,
    ) -> Result<Uuid, InvalidSymbolId> {
        if !self.contains(id) {
            return Err(InvalidSymbolId(id));
        }

        // Return existing UUID if already assigned
        if let Some(&existing) = self.id_to_uuid.get(id) {
            return Ok(existing);
        }

        let final_uuid = uuid.unwrap_or_else(Uuid::new_v4);
        self.id_to_uuid.insert(id, final_uuid);
        self.uuid_to_id.insert(final_uuid, id);

        Ok(final_uuid)
    }

    /// Get persistent UUID for a symbol (O(1))
    ///
    /// Returns `None` if the symbol was not registered with persistence.
    #[inline]
    pub fn uuid(&self, id: SymbolId) -> Option<Uuid> {
        self.id_to_uuid.get(id).copied()
    }

    /// Lookup symbol by persistent UUID (O(1))
    ///
    /// Use this when deserializing references from saved data.
    #[inline]
    pub fn lookup_by_uuid(&self, uuid: Uuid) -> Option<SymbolId> {
        self.uuid_to_id.get(&uuid).copied()
    }

    /// Check if a symbol has a persistent UUID
    #[inline]
    pub fn has_uuid(&self, id: SymbolId) -> bool {
        self.id_to_uuid.contains_key(id)
    }

    /// Get all symbols with persistent UUIDs
    pub fn iter_persistent(&self) -> impl Iterator<Item = (SymbolId, Uuid)> + '_ {
        self.id_to_uuid.iter().map(|(id, &uuid)| (id, uuid))
    }

    /// Get count of symbols with persistent UUIDs
    pub fn persistent_count(&self) -> usize {
        self.id_to_uuid.len()
    }

    /// Preload UUID mappings from a previous session.
    ///
    /// Call this before registering symbols to restore persistent UUIDs.
    /// When `register()` is called, it will use preloaded UUIDs instead of
    /// generating new ones.
    ///
    /// # Arguments
    /// * `mappings` - HashMap of SymbolPath → UUID from previous session
    ///
    /// # Example
    /// ```ignore
    /// // Load from file
    /// let mappings: HashMap<SymbolPath, Uuid> = load_from_file(path)?;
    /// registry.preload_uuid_mapping(mappings);
    ///
    /// // Now register symbols - they'll get their previous UUIDs
    /// registry.register(path, kind)?;
    /// ```
    pub fn preload_uuid_mapping(&mut self, mappings: HashMap<SymbolPath, Uuid>) {
        self.preloaded_uuids = mappings;
    }

    /// Export current UUID mappings for persistence.
    ///
    /// Returns a HashMap of SymbolPath → UUID that can be serialized
    /// and loaded in a future session via `preload_uuid_mapping()`.
    ///
    /// # Example
    /// ```ignore
    /// // Save to file
    /// let mappings = registry.export_uuid_mapping();
    /// save_to_file(path, &mappings)?;
    /// ```
    pub fn export_uuid_mapping(&self) -> HashMap<SymbolPath, Uuid> {
        self.id_to_path
            .iter()
            .filter_map(|(id, path)| self.id_to_uuid.get(id).map(|&uuid| (path.clone(), uuid)))
            .collect()
    }

    /// Export UUID mappings as strings for JSON serialization.
    ///
    /// Converts SymbolPath and Uuid to String for easy JSON storage.
    pub fn export_uuid_mapping_strings(&self) -> HashMap<String, String> {
        self.export_uuid_mapping()
            .into_iter()
            .map(|(path, uuid)| (path.to_string(), uuid.to_string()))
            .collect()
    }

    /// Preload UUID mappings from string format (for JSON deserialization).
    ///
    /// Parses string keys/values back to SymbolPath/Uuid.
    /// Invalid entries are silently skipped.
    pub fn preload_uuid_mapping_strings(&mut self, mappings: HashMap<String, String>) {
        let parsed: HashMap<SymbolPath, Uuid> = mappings
            .into_iter()
            .filter_map(|(path_str, uuid_str)| {
                let path = SymbolPath::parse(&path_str).ok()?;
                let uuid = Uuid::parse_str(&uuid_str).ok()?;
                Some((path, uuid))
            })
            .collect();
        self.preloaded_uuids = parsed;
    }

    // ========== Iteration ==========

    /// Iterate over all symbols
    pub fn iter(&self) -> impl Iterator<Item = (SymbolId, &SymbolPath)> {
        self.id_to_path.iter()
    }

    /// Iterate over symbols of a specific kind
    pub fn iter_by_kind(&self, kind: SymbolKind) -> impl Iterator<Item = SymbolId> + '_ {
        self.kinds
            .iter()
            .filter(move |(_, &k)| k == kind)
            .map(|(id, _)| id)
    }

    /// Iterate over symbols in a specific crate
    pub fn iter_in_crate<'a>(&'a self, crate_name: &'a str) -> impl Iterator<Item = SymbolId> + 'a {
        self.id_to_path
            .iter()
            .filter(move |(_, path)| path.crate_name() == crate_name)
            .map(|(id, _)| id)
    }

    // ========== Statistics ==========

    /// Get number of registered symbols
    pub fn len(&self) -> usize {
        self.id_to_path.len()
    }

    /// Check if registry is empty
    pub fn is_empty(&self) -> bool {
        self.id_to_path.is_empty()
    }

    /// Get memory usage statistics
    pub fn memory_stats(&self) -> MemoryStats {
        MemoryStats {
            symbol_count: self.id_to_path.len(),
            // Rough estimates
            estimated_bytes: self.id_to_path.len() * 64 // Very rough estimate
                + self.path_to_id.len() * 80
                + self.kinds.len() * 8
                + self.spans.len() * 48
                + self.visibility.len() * 16,
        }
    }
}

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

/// Memory usage statistics
#[derive(Debug, Clone)]
pub struct MemoryStats {
    /// Number of symbols currently held in the registry.
    pub symbol_count: usize,
    /// Rough byte estimate of the registry's in-memory footprint
    /// (path strings + slot map overhead); not a precise allocator total.
    pub estimated_bytes: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_path(s: &str) -> SymbolPath {
        SymbolPath::parse(s).unwrap()
    }

    #[test]
    fn test_register_and_lookup() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");
        let id = registry.register(path.clone(), SymbolKind::Struct).unwrap();

        assert!(registry.contains(id));
        assert_eq!(registry.lookup(&path), Some(id));
        assert_eq!(registry.resolve(id), Some(&path));
        assert_eq!(registry.kind(id), Some(SymbolKind::Struct));
    }

    #[test]
    fn test_register_duplicate() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");
        let id1 = registry.register(path.clone(), SymbolKind::Struct).unwrap();
        let id2 = registry.register(path.clone(), SymbolKind::Struct).unwrap();

        // Same ID returned
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_register_conflicting_kind() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");
        registry.register(path.clone(), SymbolKind::Struct).unwrap();

        // Attempt to register with different kind
        let result = registry.register(path, SymbolKind::Enum);
        assert!(matches!(
            result,
            Err(RegistrationError::ConflictingKind { .. })
        ));
    }

    #[test]
    fn test_register_var() {
        let mut registry = SymbolRegistry::new();

        // Register parent
        let fn_path = make_path("my_crate::my_fn");
        let fn_id = registry.register(fn_path, SymbolKind::Function).unwrap();

        // Register variable
        let var_id = registry
            .register_var(fn_id, VarScope::Local, "result", SymbolKind::Variable)
            .unwrap();

        // Verify
        let var_path = registry.resolve(var_id).unwrap();
        assert_eq!(var_path.to_string(), "my_crate::my_fn::$var::result");
        assert_eq!(registry.parent(var_id), Some(fn_id));
    }

    #[test]
    fn test_reexport() {
        let mut registry = SymbolRegistry::new();

        // Register canonical
        let canonical_path = make_path("std::collections::hash_map::HashMap");
        let canonical_id = registry
            .register(canonical_path, SymbolKind::Struct)
            .unwrap();

        // Register re-export
        let alias_path = make_path("std::collections::HashMap");
        let origin = WorkspaceFilePath::new_for_test("src/collections/mod.rs", "/std", "std");

        registry
            .register_reexport(canonical_id, alias_path.clone(), origin)
            .unwrap();

        // Both paths resolve to same ID
        assert_eq!(registry.lookup(&alias_path), Some(canonical_id));
    }

    #[test]
    fn test_iter_by_kind() {
        let mut registry = SymbolRegistry::new();

        registry
            .register(make_path("my_crate::Struct1"), SymbolKind::Struct)
            .unwrap();
        registry
            .register(make_path("my_crate::Struct2"), SymbolKind::Struct)
            .unwrap();
        registry
            .register(make_path("my_crate::func"), SymbolKind::Function)
            .unwrap();

        let structs: Vec<_> = registry.iter_by_kind(SymbolKind::Struct).collect();
        assert_eq!(structs.len(), 2);

        let funcs: Vec<_> = registry.iter_by_kind(SymbolKind::Function).collect();
        assert_eq!(funcs.len(), 1);
    }

    // ========== UUID Persistence Tests ==========

    #[test]
    fn test_register_persistent_new() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");
        let (id, uuid) = registry
            .register_persistent(path.clone(), SymbolKind::Struct, None)
            .unwrap();

        // Verify bidirectional mapping
        assert_eq!(registry.uuid(id), Some(uuid));
        assert_eq!(registry.lookup_by_uuid(uuid), Some(id));
        assert!(registry.has_uuid(id));
    }

    #[test]
    fn test_register_persistent_returns_auto_uuid() {
        let mut registry = SymbolRegistry::new();

        // With auto-UUID on register(), register_persistent() without
        // explicit UUID just returns the auto-generated one
        let path = make_path("my_crate::MyStruct");
        let (id, uuid) = registry
            .register_persistent(path, SymbolKind::Struct, None)
            .unwrap();

        // UUID was auto-assigned by register()
        assert_eq!(registry.uuid(id), Some(uuid));
        assert_eq!(registry.lookup_by_uuid(uuid), Some(id));
    }

    #[test]
    fn test_register_persistent_idempotent() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");

        // First registration
        let (id1, uuid1) = registry
            .register_persistent(path.clone(), SymbolKind::Struct, None)
            .unwrap();

        // Second registration (same path)
        let (id2, uuid2) = registry
            .register_persistent(path, SymbolKind::Struct, None)
            .unwrap();

        // Should return same ID and UUID
        assert_eq!(id1, id2);
        assert_eq!(uuid1, uuid2);
    }

    #[test]
    fn test_uuid_survives_rename() {
        let mut registry = SymbolRegistry::new();

        // Register with UUID
        let old_path = make_path("my_crate::OldName");
        let (id, uuid) = registry
            .register_persistent(old_path, SymbolKind::Struct, None)
            .unwrap();

        // Rename
        let new_path = make_path("my_crate::NewName");
        registry.rename(id, new_path.clone()).unwrap();

        // UUID should be preserved (same entity, different name)
        assert_eq!(registry.uuid(id), Some(uuid));
        assert_eq!(registry.lookup_by_uuid(uuid), Some(id));

        // Path should be updated
        assert_eq!(registry.resolve(id), Some(&new_path));
    }

    #[test]
    fn test_uuid_removed_on_delete() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");
        let (id, uuid) = registry
            .register_persistent(path, SymbolKind::Struct, None)
            .unwrap();

        // Remove symbol
        registry.remove(id);

        // UUID mapping should be cleaned up
        assert!(registry.uuid(id).is_none());
        assert!(registry.lookup_by_uuid(uuid).is_none());
    }

    #[test]
    fn test_auto_uuid_on_register() {
        let mut registry = SymbolRegistry::new();

        // All symbols now get UUID automatically on register
        let path = make_path("my_crate::MyStruct");
        let id = registry.register(path, SymbolKind::Struct).unwrap();

        // UUID is assigned automatically
        assert!(registry.has_uuid(id));
        let uuid = registry.uuid(id).unwrap();
        assert_eq!(registry.lookup_by_uuid(uuid), Some(id));

        // assign_uuid returns existing UUID (idempotent)
        let uuid2 = registry.assign_uuid(id, None).unwrap();
        assert_eq!(uuid, uuid2);
    }

    #[test]
    fn test_iter_persistent() {
        let mut registry = SymbolRegistry::new();

        // All symbols now get UUID automatically
        let id0 = registry
            .register(make_path("my_crate::Symbol0"), SymbolKind::Struct)
            .unwrap();
        let id1 = registry
            .register(make_path("my_crate::Symbol1"), SymbolKind::Struct)
            .unwrap();
        let id2 = registry
            .register(make_path("my_crate::Symbol2"), SymbolKind::Enum)
            .unwrap();

        // All 3 symbols should have UUIDs
        let persistent: Vec<_> = registry.iter_persistent().collect();
        assert_eq!(persistent.len(), 3);
        assert_eq!(registry.persistent_count(), 3);

        // Verify each symbol has a UUID
        assert!(registry.has_uuid(id0));
        assert!(registry.has_uuid(id1));
        assert!(registry.has_uuid(id2));
    }

    #[test]
    fn test_uuid_conflict_error() {
        let mut registry = SymbolRegistry::new();

        let path = make_path("my_crate::MyStruct");
        let different_uuid = Uuid::new_v4();

        // First, register normally (auto-assigns UUID)
        let id = registry.register(path.clone(), SymbolKind::Struct).unwrap();
        let auto_uuid = registry.uuid(id).unwrap();

        // Try to register_persistent with a different UUID - should conflict
        let result = registry.register_persistent(path, SymbolKind::Struct, Some(different_uuid));

        assert!(matches!(
            result,
            Err(RegistrationError::UuidConflict { .. })
        ));

        // Verify original UUID is unchanged
        assert_eq!(registry.uuid(id), Some(auto_uuid));
    }

    // ========== Re-export + find_by_name Tests ==========

    #[test]
    fn test_find_by_name_includes_aliases() {
        let mut registry = SymbolRegistry::new();

        // Register canonical symbol: parking_lot::Mutex
        let canonical_path = make_path("parking_lot::Mutex");
        let canonical_id = registry
            .register(canonical_path, SymbolKind::Struct)
            .unwrap();

        // Register re-export alias: tokio::sync::Mutex → parking_lot::Mutex
        let alias_path = make_path("tokio::sync::Mutex");
        let file_path = WorkspaceFilePath::new_for_test("src/sync/mod.rs", "/tmp/tokio", "tokio");
        registry
            .register_reexport(canonical_id, alias_path, file_path)
            .unwrap();

        // find_by_name("Mutex") should find the canonical via alias
        let results = registry.find_by_name("Mutex");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0], canonical_id);
    }

    #[test]
    fn test_find_by_name_no_duplicate_with_alias() {
        let mut registry = SymbolRegistry::new();

        // Canonical symbol has name "Mutex" in its path
        let canonical_path = make_path("parking_lot::Mutex");
        let canonical_id = registry
            .register(canonical_path, SymbolKind::Struct)
            .unwrap();

        // Alias also ends in "Mutex"
        let alias_path = make_path("tokio::sync::Mutex");
        let file_path = WorkspaceFilePath::new_for_test("src/sync/mod.rs", "/tmp/tokio", "tokio");
        registry
            .register_reexport(canonical_id, alias_path, file_path)
            .unwrap();

        // Should not duplicate: canonical already found via id_to_path
        let results = registry.find_by_name("Mutex");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_lookup_resolves_alias() {
        let mut registry = SymbolRegistry::new();

        let canonical_path = make_path("my_crate::inner::Config");
        let canonical_id = registry
            .register(canonical_path, SymbolKind::Struct)
            .unwrap();

        let alias_path = make_path("my_crate::Config");
        let file_path = WorkspaceFilePath::new_for_test("src/lib.rs", "/tmp/my_crate", "my_crate");
        registry
            .register_reexport(canonical_id, alias_path.clone(), file_path)
            .unwrap();

        // lookup with alias path should return canonical ID
        assert_eq!(registry.lookup(&alias_path), Some(canonical_id));
    }
}