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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
//! SymbolPath - Rust ecosystem-wide unique symbol identifier

use std::fmt::{self, Display, Formatter};
use std::str::FromStr;

use compact_str::CompactString;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;

use crate::crate_name::CrateName;
use crate::error::ParseError;
use crate::file_path::WorkspaceFilePath;
use crate::var_scope::VarScope;

/// Path segment
///
/// A single component of a SymbolPath. Just a name string.
/// Kind information is managed by SymbolRegistry, not by Segment.
///
/// # Invariants
/// - Must be a valid Rust identifier, OR
/// - Must be a numeric string (for tuple fields like `0`, `1`)
/// - Must be a scope marker (for InSymbol: `$param`, `$var`, `$field`)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Segment(CompactString);

impl Segment {
    /// Create a new segment with validation
    ///
    /// # Errors
    /// - `ParseError::InvalidIdentifier`: Not a valid Rust identifier
    pub fn new(name: impl AsRef<str>) -> Result<Self, ParseError> {
        let name = name.as_ref();
        validate_rust_identifier(name)?;
        Ok(Self(name.into()))
    }

    /// Create without validation (internal use)
    pub(crate) fn new_unchecked(name: impl AsRef<str>) -> Self {
        Self(name.as_ref().into())
    }

    /// Get the segment name
    pub fn name(&self) -> &str {
        &self.0
    }

    /// Create a tuple field segment (numeric)
    ///
    /// # Examples
    /// ```
    /// # use ryo_symbol::Segment;
    /// let seg = Segment::tuple_field(0);
    /// assert_eq!(seg.name(), "0");
    /// ```
    pub fn tuple_field(index: usize) -> Self {
        Self(index.to_string().into())
    }

    /// Check if this is a tuple field (all digits)
    pub fn is_tuple_field(&self) -> bool {
        !self.0.is_empty() && self.0.chars().all(|c| c.is_ascii_digit())
    }

    /// Get tuple field index if this is a tuple field
    pub fn tuple_field_index(&self) -> Option<usize> {
        if self.is_tuple_field() {
            self.0.parse().ok()
        } else {
            None
        }
    }

    /// Check if this is a scope marker ($param, $var, $field, $body)
    pub fn is_scope_marker(&self) -> bool {
        self.0.starts_with('$')
    }

    /// Get the VarScope if this is a scope marker
    pub fn as_var_scope(&self) -> Option<VarScope> {
        VarScope::from_segment(&self.0)
    }

    // ========== Scope Segment Constructors ==========

    /// Parameter scope segment (`$param`)
    pub fn param_scope() -> Self {
        Self::new_unchecked("$param")
    }

    /// Variable scope segment (`$var`)
    pub fn local_scope() -> Self {
        Self::new_unchecked("$var")
    }

    /// Field scope segment (`$field`)
    pub fn field_scope() -> Self {
        Self::new_unchecked("$field")
    }

    /// Body scope segment (`$body`)
    pub fn body_scope() -> Self {
        Self::new_unchecked("$body")
    }

    /// Statement scope segment (`$stmt`)
    pub fn stmt_scope() -> Self {
        Self::new_unchecked("$stmt")
    }

    /// Expression scope segment (`$expr`)
    pub fn expr_scope() -> Self {
        Self::new_unchecked("$expr")
    }

    // ========== Impl Block Constructors ==========

    /// Inherent impl segment: `<impl Type>`
    pub fn inherent_impl(self_ty: &str) -> Self {
        Self::new_unchecked(format!("<impl {}>", self_ty))
    }

    /// Trait impl segment: `<impl Trait for Type>`
    pub fn trait_impl(trait_name: &str, self_ty: &str) -> Self {
        Self::new_unchecked(format!("<impl {} for {}>", trait_name, self_ty))
    }

    // ========== Impl Block Checks ==========

    /// Check if this is an impl block segment (`<impl ...>`)
    pub fn is_impl(&self) -> bool {
        self.0.starts_with("<impl ") && self.0.ends_with('>')
    }

    /// Check if this is a trait impl segment (`<impl Trait for Type>`)
    pub fn is_trait_impl(&self) -> bool {
        self.is_impl() && self.0.contains(" for ")
    }

    /// Extract the self type from an impl segment.
    ///
    /// - `<impl Type>` → `Some("Type")`
    /// - `<impl Trait for Type>` → `Some("Type")`
    /// - non-impl → `None`
    pub fn impl_self_ty(&self) -> Option<&str> {
        if !self.is_impl() {
            return None;
        }
        // Strip "<impl " (6 chars) and ">" (1 char)
        let inner = &self.0[6..self.0.len() - 1];
        if let Some(pos) = inner.find(" for ") {
            Some(&inner[pos + 5..])
        } else {
            Some(inner)
        }
    }

    /// Extract the trait name from a trait impl segment.
    ///
    /// - `<impl Trait for Type>` → `Some("Trait")`
    /// - `<impl Type>` → `None`
    /// - non-impl → `None`
    pub fn impl_trait(&self) -> Option<&str> {
        if !self.is_impl() {
            return None;
        }
        let inner = &self.0[6..self.0.len() - 1];
        inner.find(" for ").map(|pos| &inner[..pos])
    }

    // ========== Scope Segment Checks ==========

    /// Check if this is a parameter scope segment (`$param`)
    pub fn is_param_scope(&self) -> bool {
        self.0.as_str() == "$param"
    }

    /// Check if this is a local variable scope segment (`$var`)
    pub fn is_local_scope(&self) -> bool {
        self.0.as_str() == "$var"
    }

    /// Check if this is a field scope segment (`$field`)
    pub fn is_field_scope(&self) -> bool {
        self.0.as_str() == "$field"
    }

    /// Check if this is a body scope segment (`$body`)
    pub fn is_body_scope(&self) -> bool {
        self.0.as_str() == "$body"
    }

    /// Check if this is a statement scope segment (`$stmt`)
    pub fn is_stmt_scope(&self) -> bool {
        self.0.as_str() == "$stmt"
    }

    /// Check if this is an expression scope segment (`$expr`)
    pub fn is_expr_scope(&self) -> bool {
        self.0.as_str() == "$expr"
    }
}

impl Display for Segment {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Validate a Rust identifier
///
/// Valid: `[a-zA-Z_][a-zA-Z0-9_]*` or all digits (tuple field) or scope marker ($...)
fn validate_rust_identifier(s: &str) -> Result<(), ParseError> {
    if s.is_empty() {
        return Err(ParseError::InvalidIdentifier(s.to_string()));
    }

    // Tuple field (all digits) is OK
    if s.chars().all(|c| c.is_ascii_digit()) {
        return Ok(());
    }

    // Scope marker ($param, $var, $field, $body, $stmt, $expr) is OK
    if s.starts_with('$') {
        if VarScope::from_segment(s).is_some() || matches!(s, "$body" | "$stmt" | "$expr") {
            return Ok(());
        }
        return Err(ParseError::InvalidIdentifier(s.to_string()));
    }

    // Impl block segment (e.g., "<impl Counter>", "<impl Trait for Type>")
    if s.starts_with("<impl ") && s.ends_with('>') {
        return Ok(());
    }

    // Rust identifier rules
    let mut chars = s.chars();
    let first = chars
        .next()
        .expect("non-empty checked at function entry (s.is_empty() guard)");
    if !first.is_ascii_alphabetic() && first != '_' {
        return Err(ParseError::InvalidIdentifier(s.to_string()));
    }

    for c in chars {
        if !c.is_ascii_alphanumeric() && c != '_' {
            return Err(ParseError::InvalidIdentifier(s.to_string()));
        }
    }

    Ok(())
}

/// Rust ecosystem-wide unique symbol path
///
/// # Format
/// ```text
/// tokio::sync::Mutex::lock
/// std::collections::HashMap::insert
/// ryo_core::mutations::AddMethod::apply
/// ```
///
/// # Invariants
/// - segments is non-empty
/// - First segment is always the crate name
/// - Each segment is a valid Rust identifier (or tuple field, or scope marker)
/// - crate_root_depth is either 1 (lib crate) or 2 (bin crate with main:: prefix)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SymbolPath {
    /// Path segments (crate name first)
    ///
    /// Up to 12 elements stored inline. Typical Rust code has 5-8 levels,
    /// but nested impl blocks or macro-generated code can go deeper.
    segments: SmallVec<[Segment; 12]>,

    /// Depth to crate root (1 for lib, 2 for bin with main:: prefix)
    ///
    /// This is precomputed during construction for O(1) access.
    /// - `my_lib::utils::Helper` → crate_root_depth = 1
    /// - `main::my_app::utils::Helper` → crate_root_depth = 2
    crate_root_depth: u8,
}

impl SymbolPath {
    // ========== Public API (controlled creation) ==========

    /// Create from file path (external API)
    ///
    /// This is the primary way to create a SymbolPath from outside the crate.
    ///
    /// # Arguments
    /// - `crate_name`: The crate containing the file
    /// - `path`: The file path within the workspace
    ///
    /// # Returns
    /// A SymbolPath representing the module path for this file
    pub fn from_file_path(
        crate_name: &CrateName,
        path: &WorkspaceFilePath,
    ) -> Result<Self, ParseError> {
        let mut builder = Self::builder(crate_name.as_str());

        // Convert file path to module path
        // e.g., "src/foo/bar.rs" -> ["foo", "bar"]
        // e.g., "src/foo/mod.rs" -> ["foo"]
        // e.g., "src/lib.rs" -> [] (crate root)
        // e.g., "crates/my_crate/src/foo.rs" -> ["foo"]
        let relative = path.as_relative();
        let mut components: Vec<_> = relative
            .components()
            .filter_map(|c| c.as_os_str().to_str())
            .collect();

        // Handle "crates/<name>/src/" pattern - skip to src/
        // This handles workspace paths like "crates/my_crate/src/lib.rs"
        if let Some(src_idx) = components.iter().position(|&c| c == "src") {
            components = components[src_idx..].to_vec();
        }

        // Remove "src" prefix if present
        if components.first() == Some(&"src") {
            components.remove(0);
        }

        // Process remaining components
        for (i, component) in components.iter().enumerate() {
            let is_last = i == components.len() - 1;

            if is_last {
                // Handle file name
                let name = *component;
                if name == "lib.rs" || name == "main.rs" || name == "mod.rs" {
                    // These don't add to the path
                    continue;
                }
                // Strip .rs extension
                if let Some(module_name) = name.strip_suffix(".rs") {
                    builder = builder.push(module_name);
                }
            } else {
                // Directory name becomes module
                builder = builder.push(*component);
            }
        }

        builder.build()
    }

    /// Create from WorkspaceFilePath (uses embedded crate_name)
    ///
    /// This is the simplest way to create a SymbolPath from a file path.
    /// Since WorkspaceFilePath now contains the crate_name, no external
    /// provider is needed.
    ///
    /// # Example
    /// ```ignore
    /// let path = WorkspaceFilePath::new_for_test("src/foo/bar.rs", "/workspace", "my_crate");
    /// let symbol = SymbolPath::from_workspace_file(&path)?;
    /// // → my_crate::foo::bar
    /// ```
    pub fn from_workspace_file(path: &WorkspaceFilePath) -> Result<Self, ParseError> {
        Self::from_file_path(path.crate_name(), path)
    }

    /// Create a symbol path for an item within a file
    ///
    /// # Arguments
    /// - `path`: The file containing the item
    /// - `item_name`: The name of the item (struct, fn, etc.)
    ///
    /// # Example
    /// ```ignore
    /// let path = WorkspaceFilePath::new_for_test("src/foo.rs", "/workspace", "my_crate");
    /// let symbol = SymbolPath::item_in_file(&path, "MyStruct")?;
    /// // → my_crate::foo::MyStruct
    /// ```
    pub fn item_in_file(path: &WorkspaceFilePath, item_name: &str) -> Result<Self, ParseError> {
        let module = Self::from_workspace_file(path)?;
        let full_path = format!("{}::{}", module, item_name);
        Self::parse(&full_path)
    }

    /// Create a symbol path for a nested item (e.g., impl block item, enum variant)
    ///
    /// # Arguments
    /// - `path`: The file containing the item
    /// - `segments`: Additional path segments after the module
    ///
    /// # Example
    /// ```ignore
    /// let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
    /// let symbol = SymbolPath::nested_in_file(&path, &["Foo", "new"])?;
    /// // → my_crate::Foo::new
    /// ```
    pub fn nested_in_file(path: &WorkspaceFilePath, segments: &[&str]) -> Result<Self, ParseError> {
        let module = Self::from_workspace_file(path)?;
        let mut full_path = module.to_string();
        for seg in segments {
            full_path.push_str("::");
            full_path.push_str(seg);
        }
        Self::parse(&full_path)
    }

    /// Convert a WorkspaceFilePath to its corresponding SymbolPath string representation.
    ///
    /// This is the core conversion function from file paths to symbol paths. It handles
    /// both library and binary entry points, applying the correct naming convention for each.
    ///
    /// # Binary Entry Points (main.rs)
    ///
    /// Binary entry points use the `main::` prefix to distinguish them from library symbols:
    ///
    /// ```ignore
    /// // For src/main.rs in crate "my_app":
    /// module_path_str(path) → "main::my_app"
    ///
    /// // For src/main.rs with nested symbol:
    /// // File: src/main.rs with fn main() {}
    /// module_path_str(path) → "main::my_app"
    /// // Then the full symbol path becomes: "main::my_app::main"
    /// ```
    ///
    /// This `main::` prefix serves critical purposes:
    /// 1. **Disambiguation**: Prevents conflicts between lib.rs and main.rs symbols
    /// 2. **File Resolution**: `RegistryGenerator` uses `is_main_symbol()` to determine
    ///    whether to output to `src/main.rs` or `src/lib.rs`
    /// 3. **Bin-Only Detection**: Crates with only main.rs (no lib.rs) work correctly
    ///    because symbols are explicitly marked as binary symbols
    ///
    /// # Library Entry Points (lib.rs)
    ///
    /// Library entry points use the crate name directly:
    ///
    /// ```ignore
    /// // For src/lib.rs in crate "my_lib":
    /// module_path_str(path) → "my_lib"
    /// ```
    ///
    /// # Module Files
    ///
    /// Nested module files follow standard Rust module path conventions:
    ///
    /// ```ignore
    /// // For src/models.rs:
    /// module_path_str(path) → "my_crate::models"
    ///
    /// // For src/models/user.rs:
    /// module_path_str(path) → "my_crate::models::user"
    /// ```
    ///
    /// # Reverse Conversion
    ///
    /// The reverse conversion (SymbolPath → WorkspaceFilePath) is handled by:
    /// - `FilePathResolver::resolve_candidates_with_crate_info()` - Uses CargoMetadataProvider
    ///   to determine the correct file path, handling both lib and bin targets
    ///
    /// # Example Flow (Bin-Only Crate)
    ///
    /// ```ignore
    /// // 1. File Loading (src/main.rs → SymbolPath)
    /// let path = WorkspaceFilePath::new(..., "src/main.rs", "my_app");
    /// let symbol_path = SymbolPath::module_path_str(&path);
    /// // → "main::my_app"
    ///
    /// // 2. Symbol Registration
    /// registry.register(SymbolPath::parse("main::my_app::Status")?, SymbolKind::Enum);
    ///
    /// // 3. File Generation (SymbolPath → WorkspaceFilePath)
    /// let candidates = file_resolver.resolve_candidates_with_crate_info(
    ///     &SymbolPath::parse("main::my_app::Status")?,
    ///     &crate_info
    /// );
    /// // → ["src/main.rs"] (because is_main_symbol() returns true)
    /// ```
    ///
    /// # See Also
    ///
    /// - [`SymbolPath::is_main_symbol()`] - Checks if a symbol is from a binary entry
    /// - `FilePathResolver::resolve_candidates_with_crate_info()` - Reverse conversion
    /// - `RegistryGenerator::generate()` - Uses is_main_symbol() to determine output file
    pub fn module_path_str(path: &WorkspaceFilePath) -> String {
        let crate_name = path.crate_name().to_module_name();
        let relative = path.as_relative();
        let path_str = relative.to_string_lossy();

        // Handle "crates/<name>/src/" pattern - find and skip to src/
        let work_path = if let Some(src_idx) = path_str.find("/src/") {
            // Skip everything before and including "src/"
            &path_str[src_idx + 5..]
        } else {
            // Remove "src/" prefix if present at the start
            path_str.strip_prefix("src/").unwrap_or(&path_str)
        };

        // Remove ".rs" suffix
        let without_rs = work_path.strip_suffix(".rs").unwrap_or(work_path);

        // Handle mod.rs - strip the trailing /mod
        let module_part = without_rs.strip_suffix("/mod").unwrap_or(without_rs);

        // Handle lib.rs and main.rs as crate root
        if module_part == "lib" {
            return crate_name;
        } else if module_part == "main" {
            // Binary entry: prefix with "main::" to distinguish from library symbols
            return format!("main::{}", crate_name);
        }

        // Convert path separators to ::
        let module_path = module_part.replace('/', "::");
        format!("{}::{}", crate_name, module_path)
    }

    // ========== Parsing ==========

    /// Calculate crate root depth from segments
    ///
    /// # Returns
    /// - 2 if first segment is "main" (bin crate: main::crate_name)
    /// - 1 otherwise (lib crate: crate_name)
    ///
    /// # Panics
    /// - If segments is empty (design invariant violation)
    /// - If first segment is "main" but no second segment exists
    fn calculate_crate_root_depth(segments: &[Segment]) -> u8 {
        assert!(
            !segments.is_empty(),
            "SymbolPath segments must not be empty"
        );

        let first = segments[0].name();
        if first == "main" {
            // main:: prefix requires at least 2 segments: main::crate_name
            if segments.len() < 2 {
                panic!(
                    "Invalid main symbol path: 'main' prefix requires crate name (e.g., main::my_app), got: main"
                );
            }
            2
        } else {
            1
        }
    }

    /// Parse from string representation (e.g., "my_crate::foo::Bar")
    ///
    /// Handles `::` inside `<impl ...>` segments correctly by treating
    /// angle-bracketed blocks as atomic (e.g., `<impl io::Write for Foo>`
    /// is a single segment, not split on `io::Write`).
    pub fn parse(s: &str) -> Result<Self, ParseError> {
        if s.is_empty() {
            return Err(ParseError::Empty);
        }

        let segments: Result<SmallVec<[Segment; 12]>, _> = split_respecting_angle_brackets(s)
            .into_iter()
            .map(Segment::new)
            .collect();

        let segments = segments?;

        if segments.is_empty() {
            return Err(ParseError::Empty);
        }

        // CRITICAL: Reject semantic keywords (crate, self, super)
        // SymbolPath must be canonical (e.g., "tokio::net::TcpStream")
        // Semantic keywords are context-dependent and must be resolved before parsing
        let first = segments[0].name();
        if matches!(first, "crate" | "self" | "super") {
            return Err(ParseError::SemanticKeyword(first.to_string()));
        }

        // Validate main:: prefix requires crate name
        if first == "main" && segments.len() < 2 {
            return Err(ParseError::InvalidIdentifier(
                "main:: prefix requires crate name (e.g., main::my_app)".to_string(),
            ));
        }

        let crate_root_depth = Self::calculate_crate_root_depth(&segments);

        Ok(Self {
            segments,
            crate_root_depth,
        })
    }

    /// Parse with registry validation - ensures crate name exists in registry.
    ///
    /// Use this when constructing paths from user input or DSL where the crate
    /// name must be validated against known crates.
    ///
    /// # Errors
    /// - `ParseError::UnknownCrate` if the crate name is not in the registry
    /// - All errors from `parse()`
    pub fn parse_validated(s: &str, registry: &crate::SymbolRegistry) -> Result<Self, ParseError> {
        let path = Self::parse(s)?;

        // Check if crate name exists in registry
        let crate_name = path.crate_name();
        let crate_exists = registry.iter().any(|(_, p)| p.crate_name() == crate_name);

        if !crate_exists {
            let known: Vec<_> = registry
                .iter()
                .map(|(_, p)| p.crate_name())
                .collect::<std::collections::HashSet<_>>()
                .into_iter()
                .collect();
            return Err(ParseError::UnknownCrate {
                path: s.to_string(),
                crate_name: crate_name.to_string(),
                known: known.join(", "),
            });
        }

        Ok(path)
    }

    /// Construct from segments (with validation)
    pub fn from_segments(
        segments: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Self, ParseError> {
        let segments: SmallVec<[Segment; 12]> = segments
            .into_iter()
            .map(|s| Segment::new(s))
            .collect::<Result<_, _>>()?;

        if segments.is_empty() {
            return Err(ParseError::Empty);
        }

        let crate_root_depth = Self::calculate_crate_root_depth(&segments);

        Ok(Self {
            segments,
            crate_root_depth,
        })
    }

    /// Create a builder for constructing SymbolPath
    ///
    /// # Examples
    /// ```
    /// # use ryo_symbol::SymbolPath;
    /// let path = SymbolPath::builder("my_crate")
    ///     .push("module")
    ///     .push("MyStruct")
    ///     .build()
    ///     .unwrap();
    /// assert_eq!(path.to_string(), "my_crate::module::MyStruct");
    /// ```
    pub fn builder(crate_name: impl Into<String>) -> SymbolPathBuilder {
        SymbolPathBuilder::new(crate_name)
    }

    /// Create a path with variable scope (for variable registration)
    ///
    /// # Examples
    /// ```
    /// # use ryo_symbol::{SymbolPath, VarScope};
    /// let fn_path = SymbolPath::parse("my_crate::my_fn").unwrap();
    /// let var_path = fn_path.with_var_scope(VarScope::Param, "x").unwrap();
    /// assert_eq!(var_path.to_string(), "my_crate::my_fn::$param::x");
    /// ```
    pub fn with_var_scope(&self, scope: VarScope, name: &str) -> Result<Self, ParseError> {
        let mut segments = self.segments.clone();
        segments.push(Segment::new_unchecked(scope.segment()));
        segments.push(Segment::new(name)?);
        Ok(Self {
            segments,
            crate_root_depth: self.crate_root_depth, // Inherit from parent
        })
    }

    // ========== Accessors ==========

    /// Get the crate name (first segment)
    #[inline]
    pub fn crate_name(&self) -> &str {
        self.segments[0].name()
    }

    /// Check if this is a main.rs symbol (starts with "main::")
    ///
    /// Main symbols use a special prefix to distinguish them from library symbols.
    /// This allows explicit targeting of binary entry points in Intent DSL.
    ///
    /// # Example
    /// ```ignore
    /// let main_symbol = SymbolPath::parse("main::my_crate::Config")?;
    /// assert!(main_symbol.is_main_symbol());
    ///
    /// let lib_symbol = SymbolPath::parse("my_crate::Config")?;
    /// assert!(!lib_symbol.is_main_symbol());
    /// ```
    #[inline]
    pub fn is_main_symbol(&self) -> bool {
        self.crate_name() == "main"
    }

    /// Get the actual crate name for main symbols
    ///
    /// For paths like "main::my_crate::Foo", returns "my_crate".
    /// Returns None if this is not a main symbol or has insufficient depth.
    ///
    /// # Example
    /// ```ignore
    /// let path = SymbolPath::parse("main::my_crate::Config")?;
    /// assert_eq!(path.main_target_crate(), Some("my_crate"));
    ///
    /// let lib_path = SymbolPath::parse("my_crate::Config")?;
    /// assert_eq!(lib_path.main_target_crate(), None);
    /// ```
    pub fn main_target_crate(&self) -> Option<&str> {
        if self.is_main_symbol() && self.depth() >= 2 {
            self.segment(1).map(|s| s.name())
        } else {
            None
        }
    }

    /// Convert a main symbol path to its library equivalent
    ///
    /// Strips the "main::" prefix, converting "main::my_crate::Foo" to "my_crate::Foo".
    /// Returns None if this is not a main symbol.
    ///
    /// # Example
    /// ```ignore
    /// let main_path = SymbolPath::parse("main::my_crate::Config")?;
    /// let lib_path = main_path.to_lib_path()?;
    /// assert_eq!(lib_path.to_string(), "my_crate::Config");
    /// ```
    pub fn to_lib_path(&self) -> Option<SymbolPath> {
        if !self.is_main_symbol() || self.depth() < 2 {
            return None;
        }
        // Skip the "main" prefix and build new path
        let segments: SmallVec<[Segment; 12]> = self.segments[1..].iter().cloned().collect();
        Some(Self {
            segments,
            crate_root_depth: 1, // lib crate has depth 1
        })
    }

    // ========== Crate Root API (New) ==========

    /// Check if this symbol path represents a crate root itself
    ///
    /// Returns true if this path is the crate root module (not a submodule).
    ///
    /// # Examples
    /// ```ignore
    /// let lib_root = SymbolPath::parse("my_lib")?;
    /// assert!(lib_root.is_crate_root());
    ///
    /// let lib_mod = SymbolPath::parse("my_lib::utils")?;
    /// assert!(!lib_mod.is_crate_root());
    ///
    /// let bin_root = SymbolPath::parse("main::my_app")?;
    /// assert!(bin_root.is_crate_root());
    ///
    /// let bin_mod = SymbolPath::parse("main::my_app::utils")?;
    /// assert!(!bin_mod.is_crate_root());
    /// ```
    #[inline]
    pub fn is_crate_root(&self) -> bool {
        self.segments.len() == self.crate_root_depth as usize
    }

    /// Get the actual crate name (excluding main:: prefix)
    ///
    /// Returns the real crate name, stripping the "main::" prefix for binary crates.
    ///
    /// # Examples
    /// ```ignore
    /// let lib_path = SymbolPath::parse("my_lib::Config")?;
    /// assert_eq!(lib_path.actual_crate_name(), "my_lib");
    ///
    /// let bin_path = SymbolPath::parse("main::my_app::Config")?;
    /// assert_eq!(bin_path.actual_crate_name(), "my_app");
    /// ```
    #[inline]
    pub fn actual_crate_name(&self) -> &str {
        if self.crate_root_depth == 2 {
            // main::crate_name → return "crate_name"
            self.segments[1].name()
        } else {
            // crate_name → return "crate_name"
            self.segments[0].name()
        }
    }

    /// Get the module path relative to crate root
    ///
    /// Returns segments after the crate root.
    ///
    /// # Examples
    /// ```ignore
    /// let path = SymbolPath::parse("my_lib::utils::Helper")?;
    /// let mod_path = path.mod_path();
    /// assert_eq!(mod_path.len(), 2); // ["utils", "Helper"]
    ///
    /// let bin_path = SymbolPath::parse("main::my_app::utils::Helper")?;
    /// let bin_mod_path = bin_path.mod_path();
    /// assert_eq!(bin_mod_path.len(), 2); // ["utils", "Helper"]
    ///
    /// let root = SymbolPath::parse("my_lib")?;
    /// assert_eq!(root.mod_path().len(), 0); // []
    /// ```
    #[inline]
    pub fn mod_path(&self) -> &[Segment] {
        &self.segments[self.crate_root_depth as usize..]
    }

    /// Get the depth (number of segments)
    #[inline]
    pub fn depth(&self) -> usize {
        self.segments.len()
    }

    /// Iterate over segment names
    pub fn segments(&self) -> impl Iterator<Item = &str> {
        self.segments.iter().map(|s| s.name())
    }

    /// Get segment references as slice
    pub fn segment_refs(&self) -> &[Segment] {
        &self.segments
    }

    /// Get segment at index
    pub fn segment(&self, index: usize) -> Option<&Segment> {
        self.segments.get(index)
    }

    /// Get the last segment (symbol name)
    #[inline]
    pub fn name(&self) -> &str {
        self.segments.last().map(|s| s.name()).unwrap_or("")
    }

    // ========== Navigation ==========

    /// Get the parent path
    ///
    /// # Examples
    /// ```ignore
    /// let path = SymbolPath::parse("tokio::sync::Mutex::lock")?;
    /// assert_eq!(path.parent().unwrap().to_string(), "tokio::sync::Mutex");
    /// ```
    pub fn parent(&self) -> Option<SymbolPath> {
        if self.segments.len() <= 1 {
            return None;
        }
        let mut segments = self.segments.clone();
        segments.pop();
        Some(Self {
            segments,
            crate_root_depth: self.crate_root_depth, // Inherit from self
        })
    }

    /// Check if this path is an ancestor of another
    pub fn is_ancestor_of(&self, other: &SymbolPath) -> bool {
        if self.segments.len() >= other.segments.len() {
            return false;
        }
        self.segments
            .iter()
            .zip(other.segments.iter())
            .all(|(a, b)| a == b)
    }

    /// Check if this path is a descendant of another
    pub fn is_descendant_of(&self, other: &SymbolPath) -> bool {
        other.is_ancestor_of(self)
    }

    /// Check if both paths are in the same crate
    #[inline]
    pub fn same_crate(&self, other: &SymbolPath) -> bool {
        self.crate_name() == other.crate_name()
    }

    /// Get the common ancestor of two paths
    pub fn common_ancestor(&self, other: &SymbolPath) -> Option<SymbolPath> {
        let mut common: SmallVec<[Segment; 12]> = SmallVec::new();

        for (a, b) in self.segments.iter().zip(other.segments.iter()) {
            if a == b {
                common.push(a.clone());
            } else {
                break;
            }
        }

        if common.is_empty() {
            None
        } else {
            let crate_root_depth = Self::calculate_crate_root_depth(&common);
            Some(Self {
                segments: common,
                crate_root_depth,
            })
        }
    }

    /// Construct a child path by appending a segment.
    ///
    /// # Example
    /// ```
    /// # use ryo_symbol::SymbolPath;
    /// let path = SymbolPath::parse("tokio::sync").unwrap();
    /// let child = path.child("Mutex").unwrap();
    /// assert_eq!(child.to_string(), "tokio::sync::Mutex");
    /// ```
    pub fn child(&self, name: impl AsRef<str>) -> Result<SymbolPath, ParseError> {
        let segment = Segment::new(name)?;
        let mut segments = self.segments.clone();
        segments.push(segment);
        Ok(SymbolPath {
            segments,
            crate_root_depth: self.crate_root_depth, // Inherit from parent
        })
    }

    /// Append an inherent impl segment: `parent::<impl Type>`
    pub fn child_inherent_impl(&self, self_ty: &str) -> SymbolPath {
        let mut segments = self.segments.clone();
        segments.push(Segment::inherent_impl(self_ty));
        SymbolPath {
            segments,
            crate_root_depth: self.crate_root_depth,
        }
    }

    /// Append a trait impl segment: `parent::<impl Trait for Type>`
    pub fn child_trait_impl(&self, trait_name: &str, self_ty: &str) -> SymbolPath {
        let mut segments = self.segments.clone();
        segments.push(Segment::trait_impl(trait_name, self_ty));
        SymbolPath {
            segments,
            crate_root_depth: self.crate_root_depth,
        }
    }

    /// Get the module path (parent of this symbol).
    ///
    /// Returns the path without the final item name.
    /// For `tokio::sync::Mutex::lock`, returns `"tokio::sync::Mutex"`.
    /// For a crate root like `tokio`, returns `"tokio"`.
    pub fn module_path(&self) -> String {
        if self.segments.len() <= 1 {
            self.crate_name().to_string()
        } else {
            self.segments[..self.segments.len() - 1]
                .iter()
                .map(|s| s.name())
                .collect::<Vec<_>>()
                .join("::")
        }
    }

    /// Create a new path with the last segment renamed.
    ///
    /// If the last segment matches `from`, it is replaced with `to`.
    /// Otherwise, returns a clone of self.
    pub fn with_renamed_last_segment(&self, from: &str, to: &str) -> SymbolPath {
        if self.name() != from {
            return self.clone();
        }

        let mut segments = self.segments.clone();
        if let Some(last) = segments.last_mut() {
            *last = Segment::new_unchecked(to);
        }
        SymbolPath {
            segments,
            crate_root_depth: self.crate_root_depth, // Inherit from self
        }
    }

    // ========== InSymbol Support ==========

    /// Check if this is an InSymbol (variable/parameter/field)
    pub fn is_in_symbol(&self) -> bool {
        self.segments.iter().any(|s| s.is_scope_marker())
    }

    /// Get the containing symbol path (for InSymbol)
    ///
    /// `my_crate::my_fn::$param::x` → `my_crate::my_fn`
    pub fn containing_symbol(&self) -> Option<SymbolPath> {
        let pos = self.segments.iter().position(|s| s.is_scope_marker())?;
        if pos == 0 {
            return None;
        }
        Some(Self {
            segments: self.segments[..pos].into(),
            crate_root_depth: self.crate_root_depth, // Inherit from self
        })
    }

    /// Get the variable name (for InSymbol)
    ///
    /// `my_crate::my_fn::$param::x` → `"x"`
    pub fn var_name(&self) -> Option<&str> {
        if !self.is_in_symbol() {
            return None;
        }
        self.segments.last().map(|s| s.name())
    }

    /// Get the VarScope if this is an InSymbol path
    pub fn var_scope(&self) -> Option<VarScope> {
        self.segments
            .iter()
            .find(|s| s.is_scope_marker())
            .and_then(|s| s.as_var_scope())
    }

    // ========== Body Path Navigation ==========

    /// Check if this path contains a `$body` segment
    pub fn has_body_segment(&self) -> bool {
        self.segments.iter().any(|s| s.is_body_scope())
    }

    /// Get the position of the `$body` segment
    pub fn body_segment_index(&self) -> Option<usize> {
        self.segments.iter().position(|s| s.is_body_scope())
    }

    /// Extract body indices (numeric segments after `$body`)
    ///
    /// # Example
    /// ```
    /// # use ryo_symbol::SymbolPath;
    /// let path = SymbolPath::parse("my_crate::my_fn::$body::0::1::2").unwrap();
    /// assert_eq!(path.body_indices(), Some(vec![0, 1, 2]));
    ///
    /// let no_body = SymbolPath::parse("my_crate::my_fn").unwrap();
    /// assert_eq!(no_body.body_indices(), None);
    /// ```
    pub fn body_indices(&self) -> Option<Vec<usize>> {
        let body_idx = self.body_segment_index()?;
        let indices: Option<Vec<usize>> = self.segments[body_idx + 1..]
            .iter()
            .map(|s| s.tuple_field_index())
            .collect();
        indices
    }

    /// Get the function path (everything before `$body`)
    ///
    /// # Example
    /// ```
    /// # use ryo_symbol::SymbolPath;
    /// let path = SymbolPath::parse("my_crate::my_fn::$body::0::1").unwrap();
    /// let fn_path = path.function_path().unwrap();
    /// assert_eq!(fn_path.to_string(), "my_crate::my_fn");
    /// ```
    pub fn function_path(&self) -> Option<SymbolPath> {
        let body_idx = self.body_segment_index()?;
        if body_idx == 0 {
            return None;
        }
        let segments: SmallVec<[Segment; 12]> = self.segments[..body_idx].iter().cloned().collect();
        let crate_root_depth = Self::calculate_crate_root_depth(&segments);
        Some(SymbolPath {
            segments,
            crate_root_depth,
        })
    }

    /// Split into function path and body indices
    ///
    /// # Returns
    /// `Some((function_path, body_indices))` if path contains `$body`, `None` otherwise.
    pub fn split_at_body(&self) -> Option<(SymbolPath, Vec<usize>)> {
        let fn_path = self.function_path()?;
        let indices = self.body_indices()?;
        Some((fn_path, indices))
    }
}

impl Display for SymbolPath {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let path = self
            .segments
            .iter()
            .map(|s| s.name())
            .collect::<Vec<_>>()
            .join("::");
        write!(f, "{}", path)
    }
}

impl FromStr for SymbolPath {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Builder for SymbolPath
///
/// # Validation Strategy
/// - `push()`: No validation (performance)
/// - `build()`: Validate all segments at once (safety)
pub struct SymbolPathBuilder {
    segments: SmallVec<[Segment; 12]>,
}

impl SymbolPathBuilder {
    fn new(crate_name: impl Into<String>) -> Self {
        let mut segments = SmallVec::new();
        segments.push(Segment::new_unchecked(crate_name.into()));
        Self { segments }
    }

    /// Add a segment (no validation until build())
    pub fn push(mut self, name: impl AsRef<str>) -> Self {
        self.segments.push(Segment::new_unchecked(name));
        self
    }

    /// Build the SymbolPath (validates all segments)
    ///
    /// # Errors
    /// - `ParseError::Empty`: No segments
    /// - `ParseError::InvalidIdentifier`: Invalid Rust identifier
    pub fn build(self) -> Result<SymbolPath, ParseError> {
        if self.segments.is_empty() {
            return Err(ParseError::Empty);
        }

        // Validate all segments
        for seg in &self.segments {
            validate_rust_identifier(seg.name())?;
        }

        let crate_root_depth = SymbolPath::calculate_crate_root_depth(&self.segments);

        Ok(SymbolPath {
            segments: self.segments,
            crate_root_depth,
        })
    }
}

/// Split a path string by `::`, but treat `<...>` blocks as atomic.
///
/// Standard `split("::")` breaks paths like `foo::<impl io::Write for Bar>::method`
/// because the `::` inside `<impl io::Write ...>` is treated as a separator.
/// This function tracks angle bracket depth to avoid splitting inside `<...>`.
fn split_respecting_angle_brackets(s: &str) -> Vec<&str> {
    let mut segments = Vec::new();
    let mut depth = 0u32;
    let mut start = 0;
    let bytes = s.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        match bytes[i] {
            b'<' => {
                depth += 1;
                i += 1;
            }
            b'>' => {
                depth = depth.saturating_sub(1);
                i += 1;
            }
            b':' if depth == 0 && i + 1 < len && bytes[i + 1] == b':' => {
                segments.push(&s[start..i]);
                i += 2; // skip "::"
                start = i;
            }
            _ => {
                i += 1;
            }
        }
    }

    // Push the final segment
    if start <= len {
        segments.push(&s[start..len]);
    }

    segments
}

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

    #[test]
    fn test_parse_simple() {
        let path = SymbolPath::parse("tokio::sync::Mutex").unwrap();
        assert_eq!(path.crate_name(), "tokio");
        assert_eq!(path.depth(), 3);
        assert_eq!(path.name(), "Mutex");
        assert_eq!(path.to_string(), "tokio::sync::Mutex");
    }

    #[test]
    fn test_builder() {
        let path = SymbolPath::builder("tokio")
            .push("sync")
            .push("Mutex")
            .push("lock")
            .build()
            .unwrap();

        assert_eq!(path.to_string(), "tokio::sync::Mutex::lock");
    }

    #[test]
    fn test_parent() {
        let path = SymbolPath::parse("tokio::sync::Mutex::lock").unwrap();
        let parent = path.parent().unwrap();
        assert_eq!(parent.to_string(), "tokio::sync::Mutex");

        // Crate root has no parent
        let crate_path = SymbolPath::parse("tokio").unwrap();
        assert!(crate_path.parent().is_none());
    }

    #[test]
    fn test_ancestor() {
        let parent = SymbolPath::parse("tokio::sync").unwrap();
        let child = SymbolPath::parse("tokio::sync::Mutex::lock").unwrap();

        assert!(parent.is_ancestor_of(&child));
        assert!(child.is_descendant_of(&parent));
        assert!(!child.is_ancestor_of(&parent));
    }

    #[test]
    fn test_common_ancestor() {
        let path1 = SymbolPath::parse("tokio::sync::Mutex::lock").unwrap();
        let path2 = SymbolPath::parse("tokio::sync::RwLock::read").unwrap();

        let common = path1.common_ancestor(&path2).unwrap();
        assert_eq!(common.to_string(), "tokio::sync");
    }

    #[test]
    fn test_tuple_field() {
        let seg = Segment::tuple_field(0);
        assert!(seg.is_tuple_field());
        assert_eq!(seg.tuple_field_index(), Some(0));
    }

    #[test]
    fn test_in_symbol() {
        let path = SymbolPath::parse("my_crate::my_fn").unwrap();
        let var_path = path.with_var_scope(VarScope::Param, "x").unwrap();

        assert!(var_path.is_in_symbol());
        assert_eq!(var_path.var_name(), Some("x"));
        assert_eq!(
            var_path.containing_symbol().unwrap().to_string(),
            "my_crate::my_fn"
        );
    }

    #[test]
    fn test_from_file_path() {
        let crate_name = CrateName::new_for_test("my_crate");

        // lib.rs -> crate root
        let lib_path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        let sym = SymbolPath::from_file_path(&crate_name, &lib_path).unwrap();
        assert_eq!(sym.to_string(), "my_crate");

        // src/foo/bar.rs -> my_crate::foo::bar
        let mod_path = WorkspaceFilePath::new_for_test("src/foo/bar.rs", "/workspace", "my_crate");
        let sym = SymbolPath::from_file_path(&crate_name, &mod_path).unwrap();
        assert_eq!(sym.to_string(), "my_crate::foo::bar");

        // src/foo/mod.rs -> my_crate::foo
        let mod_path = WorkspaceFilePath::new_for_test("src/foo/mod.rs", "/workspace", "my_crate");
        let sym = SymbolPath::from_file_path(&crate_name, &mod_path).unwrap();
        assert_eq!(sym.to_string(), "my_crate::foo");
    }

    #[test]
    fn test_from_workspace_file() {
        // Uses embedded crate_name from WorkspaceFilePath
        let path = WorkspaceFilePath::new_for_test("src/foo/bar.rs", "/workspace", "my_crate");
        let sym = SymbolPath::from_workspace_file(&path).unwrap();
        assert_eq!(sym.to_string(), "my_crate::foo::bar");

        // lib.rs
        let lib_path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        let sym = SymbolPath::from_workspace_file(&lib_path).unwrap();
        assert_eq!(sym.to_string(), "my_crate");
    }

    #[test]
    fn test_item_in_file() {
        let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        let sym = SymbolPath::item_in_file(&path, "MyStruct").unwrap();
        assert_eq!(sym.to_string(), "my_crate::MyStruct");

        let path = WorkspaceFilePath::new_for_test("src/foo/bar.rs", "/workspace", "my_crate");
        let sym = SymbolPath::item_in_file(&path, "Baz").unwrap();
        assert_eq!(sym.to_string(), "my_crate::foo::bar::Baz");
    }

    #[test]
    fn test_nested_in_file() {
        let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        let sym = SymbolPath::nested_in_file(&path, &["Foo", "new"]).unwrap();
        assert_eq!(sym.to_string(), "my_crate::Foo::new");
    }

    #[test]
    fn test_module_path_str() {
        let path = WorkspaceFilePath::new_for_test("src/foo/bar.rs", "/workspace", "my_crate");
        assert_eq!(SymbolPath::module_path_str(&path), "my_crate::foo::bar");

        let lib_path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "my_crate");
        assert_eq!(SymbolPath::module_path_str(&lib_path), "my_crate");

        let mod_path = WorkspaceFilePath::new_for_test("src/foo/mod.rs", "/workspace", "my_crate");
        assert_eq!(SymbolPath::module_path_str(&mod_path), "my_crate::foo");

        // Test "crates/<name>/src/" pattern
        let workspace_path =
            WorkspaceFilePath::new_for_test("crates/mylib/src/lib.rs", "/workspace", "mylib");
        assert_eq!(SymbolPath::module_path_str(&workspace_path), "mylib");

        let workspace_path2 =
            WorkspaceFilePath::new_for_test("crates/mylib/src/foo.rs", "/workspace", "mylib");
        assert_eq!(SymbolPath::module_path_str(&workspace_path2), "mylib::foo");
    }

    #[test]
    fn test_from_file_path_workspace_pattern() {
        // Test "crates/<name>/src/" pattern
        let path =
            WorkspaceFilePath::new_for_test("crates/mylib/src/lib.rs", "/workspace", "mylib");
        let symbol = SymbolPath::from_workspace_file(&path).unwrap();
        assert_eq!(symbol.to_string(), "mylib");

        let path2 =
            WorkspaceFilePath::new_for_test("crates/mylib/src/foo.rs", "/workspace", "mylib");
        let symbol2 = SymbolPath::from_workspace_file(&path2).unwrap();
        assert_eq!(symbol2.to_string(), "mylib::foo");

        let path3 =
            WorkspaceFilePath::new_for_test("crates/mylib/src/foo/bar.rs", "/workspace", "mylib");
        let symbol3 = SymbolPath::from_workspace_file(&path3).unwrap();
        assert_eq!(symbol3.to_string(), "mylib::foo::bar");
    }

    #[test]
    fn test_main_symbol() {
        // Main symbol detection
        let main_path = SymbolPath::parse("main::my_crate::Config").unwrap();
        assert!(main_path.is_main_symbol());
        assert_eq!(main_path.main_target_crate(), Some("my_crate"));

        // Library symbol (not main)
        let lib_path = SymbolPath::parse("my_crate::Config").unwrap();
        assert!(!lib_path.is_main_symbol());
        assert_eq!(lib_path.main_target_crate(), None);

        // Main symbol with nested path
        let nested_main = SymbolPath::parse("main::my_crate::module::Foo").unwrap();
        assert!(nested_main.is_main_symbol());
        assert_eq!(nested_main.main_target_crate(), Some("my_crate"));

        // Just "main" is invalid (main:: prefix requires crate name)
        let just_main = SymbolPath::parse("main");
        assert!(just_main.is_err());
    }

    #[test]
    fn test_to_lib_path() {
        // Convert main symbol to lib path
        let main_path = SymbolPath::parse("main::my_crate::Config").unwrap();
        let lib_path = main_path.to_lib_path().unwrap();
        assert_eq!(lib_path.to_string(), "my_crate::Config");
        assert!(!lib_path.is_main_symbol());

        // Nested main symbol
        let nested = SymbolPath::parse("main::my_crate::module::Foo").unwrap();
        let lib = nested.to_lib_path().unwrap();
        assert_eq!(lib.to_string(), "my_crate::module::Foo");

        // Library path returns None
        let lib_path = SymbolPath::parse("my_crate::Config").unwrap();
        assert!(lib_path.to_lib_path().is_none());

        // Just "main" is invalid (parse will fail)
        let just_main = SymbolPath::parse("main");
        assert!(just_main.is_err());
    }

    #[test]
    fn test_is_crate_root() {
        // Library crate roots
        let lib_root = SymbolPath::parse("my_lib").unwrap();
        assert!(lib_root.is_crate_root());

        let lib_mod = SymbolPath::parse("my_lib::utils").unwrap();
        assert!(!lib_mod.is_crate_root());

        let lib_nested = SymbolPath::parse("my_lib::utils::Helper").unwrap();
        assert!(!lib_nested.is_crate_root());

        // Binary crate roots
        let bin_root = SymbolPath::parse("main::my_app").unwrap();
        assert!(bin_root.is_crate_root());

        let bin_mod = SymbolPath::parse("main::my_app::utils").unwrap();
        assert!(!bin_mod.is_crate_root());

        let bin_nested = SymbolPath::parse("main::my_app::utils::Helper").unwrap();
        assert!(!bin_nested.is_crate_root());
    }

    #[test]
    fn test_actual_crate_name() {
        // Library crate
        let lib_path = SymbolPath::parse("my_lib::Config").unwrap();
        assert_eq!(lib_path.actual_crate_name(), "my_lib");

        // Binary crate
        let bin_path = SymbolPath::parse("main::my_app::Config").unwrap();
        assert_eq!(bin_path.actual_crate_name(), "my_app");

        // Nested paths
        let nested = SymbolPath::parse("main::my_app::utils::Helper").unwrap();
        assert_eq!(nested.actual_crate_name(), "my_app");
    }

    #[test]
    fn test_mod_path() {
        // Library crate root - no module path
        let lib_root = SymbolPath::parse("my_lib").unwrap();
        assert_eq!(lib_root.mod_path().len(), 0);

        // Library crate with module
        let lib_mod = SymbolPath::parse("my_lib::utils").unwrap();
        assert_eq!(lib_mod.mod_path().len(), 1);
        assert_eq!(lib_mod.mod_path()[0].name(), "utils");

        let lib_nested = SymbolPath::parse("my_lib::utils::Helper").unwrap();
        assert_eq!(lib_nested.mod_path().len(), 2);
        assert_eq!(lib_nested.mod_path()[0].name(), "utils");
        assert_eq!(lib_nested.mod_path()[1].name(), "Helper");

        // Binary crate root - no module path
        let bin_root = SymbolPath::parse("main::my_app").unwrap();
        assert_eq!(bin_root.mod_path().len(), 0);

        // Binary crate with module
        let bin_mod = SymbolPath::parse("main::my_app::utils").unwrap();
        assert_eq!(bin_mod.mod_path().len(), 1);
        assert_eq!(bin_mod.mod_path()[0].name(), "utils");

        let bin_nested = SymbolPath::parse("main::my_app::utils::Helper").unwrap();
        assert_eq!(bin_nested.mod_path().len(), 2);
        assert_eq!(bin_nested.mod_path()[0].name(), "utils");
        assert_eq!(bin_nested.mod_path()[1].name(), "Helper");
    }

    #[test]
    fn test_reject_semantic_keywords() {
        // SymbolPath must be canonical - semantic keywords are forbidden

        // "crate" is not allowed (use actual crate name)
        let result = SymbolPath::parse("crate");
        assert!(matches!(result, Err(ParseError::SemanticKeyword(_))));
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("semantic keyword 'crate' not allowed"),
            "Error message should mention semantic keyword"
        );

        // "crate::foo" is not allowed
        let result = SymbolPath::parse("crate::foo");
        assert!(matches!(result, Err(ParseError::SemanticKeyword(_))));

        // "self" is not allowed
        let result = SymbolPath::parse("self");
        assert!(matches!(result, Err(ParseError::SemanticKeyword(_))));

        // "self::foo" is not allowed
        let result = SymbolPath::parse("self::foo");
        assert!(matches!(result, Err(ParseError::SemanticKeyword(_))));

        // "super" is not allowed
        let result = SymbolPath::parse("super");
        assert!(matches!(result, Err(ParseError::SemanticKeyword(_))));

        // "super::foo" is not allowed
        let result = SymbolPath::parse("super::foo");
        assert!(matches!(result, Err(ParseError::SemanticKeyword(_))));

        // Valid canonical paths are OK
        assert!(SymbolPath::parse("my_crate").is_ok());
        assert!(SymbolPath::parse("my_crate::foo").is_ok());
        assert!(SymbolPath::parse("tokio::net::TcpStream").is_ok());
    }

    // ========== Impl Segment Tests ==========

    #[test]
    fn test_segment_inherent_impl() {
        let seg = Segment::inherent_impl("Counter");
        assert_eq!(seg.name(), "<impl Counter>");
        assert!(seg.is_impl());
        assert!(!seg.is_trait_impl());
        assert_eq!(seg.impl_self_ty(), Some("Counter"));
        assert_eq!(seg.impl_trait(), None);
    }

    #[test]
    fn test_segment_trait_impl() {
        let seg = Segment::trait_impl("Display", "Counter");
        assert_eq!(seg.name(), "<impl Display for Counter>");
        assert!(seg.is_impl());
        assert!(seg.is_trait_impl());
        assert_eq!(seg.impl_self_ty(), Some("Counter"));
        assert_eq!(seg.impl_trait(), Some("Display"));
    }

    #[test]
    fn test_segment_non_impl() {
        let seg = Segment::new("foo").unwrap();
        assert!(!seg.is_impl());
        assert!(!seg.is_trait_impl());
        assert_eq!(seg.impl_self_ty(), None);
        assert_eq!(seg.impl_trait(), None);
    }

    #[test]
    fn test_segment_impl_validation_roundtrip() {
        // Constructed impl segments must pass validation
        let inherent = Segment::inherent_impl("MyStruct");
        assert!(Segment::new(inherent.name()).is_ok());

        let trait_impl = Segment::trait_impl("Clone", "MyStruct");
        assert!(Segment::new(trait_impl.name()).is_ok());
    }

    #[test]
    fn test_symbolpath_child_inherent_impl() {
        let module = SymbolPath::parse("my_crate::module").unwrap();
        let impl_path = module.child_inherent_impl("TodoList");
        assert_eq!(impl_path.to_string(), "my_crate::module::<impl TodoList>");
        assert_eq!(impl_path.depth(), 3);

        // Method under impl's parent type
        let method = module.child("TodoList").unwrap().child("new").unwrap();
        assert_eq!(method.to_string(), "my_crate::module::TodoList::new");
    }

    #[test]
    fn test_symbolpath_child_trait_impl() {
        let module = SymbolPath::parse("my_crate::module").unwrap();
        let impl_path = module.child_trait_impl("Display", "TodoList");
        assert_eq!(
            impl_path.to_string(),
            "my_crate::module::<impl Display for TodoList>"
        );

        // Method under trait impl
        let method = impl_path.child("fmt").unwrap();
        assert_eq!(
            method.to_string(),
            "my_crate::module::<impl Display for TodoList>::fmt"
        );
    }

    #[test]
    fn test_symbolpath_impl_parse_roundtrip() {
        // Display → parse roundtrip
        let module = SymbolPath::parse("my_crate").unwrap();
        let impl_path = module.child_inherent_impl("Foo");
        let reparsed = SymbolPath::parse(&impl_path.to_string()).unwrap();
        assert_eq!(impl_path, reparsed);

        let trait_path = module.child_trait_impl("Bar", "Foo");
        let reparsed = SymbolPath::parse(&trait_path.to_string()).unwrap();
        assert_eq!(trait_path, reparsed);
    }

    #[test]
    fn test_impl_segment_last_segment_inspection() {
        let path = SymbolPath::parse("my_crate::module").unwrap();
        let impl_path = path.child_trait_impl("Iterator", "MyIter");

        let last = impl_path.segment(impl_path.depth() - 1).unwrap();
        assert!(last.is_impl());
        assert!(last.is_trait_impl());
        assert_eq!(last.impl_self_ty(), Some("MyIter"));
        assert_eq!(last.impl_trait(), Some("Iterator"));
    }

    #[test]
    fn test_impl_parent_navigation() {
        let path = SymbolPath::parse("my_crate").unwrap();
        let impl_path = path.child_trait_impl("Display", "Config");
        let method = impl_path.child("fmt").unwrap();

        // parent of method → impl path
        let parent = method.parent().unwrap();
        assert_eq!(parent, impl_path);

        // parent of impl → module
        let grandparent = parent.parent().unwrap();
        assert_eq!(grandparent, path);
    }

    #[test]
    fn test_parse_roundtrip_qualified_trait_impl() {
        // BUG: SymbolPath::parse splits on "::" naively, breaking qualified
        // trait names like "io::Write" inside <impl io::Write for Writer<'_>>.
        // This causes ASTRegistry to fail lookup for methods of such impls.
        let built = SymbolPath::parse("axum::helpers")
            .unwrap()
            .child_trait_impl("io::Write", "Writer < '_ >");
        let method = built.child("write").unwrap();

        // to_string should include the qualified trait name
        let method_str = method.to_string();
        assert_eq!(
            method_str,
            "axum::helpers::<impl io::Write for Writer < '_ >>::write"
        );

        // parse(to_string) must round-trip correctly
        let reparsed = SymbolPath::parse(&method_str)
            .expect("parse must handle :: inside <impl ...> segments");
        assert_eq!(reparsed, method, "round-trip must preserve segments");
        assert_eq!(reparsed.name(), "write");
        assert_eq!(reparsed.depth(), 4); // axum, helpers, <impl ...>, write
    }
}