syster-base 0.3.4-alpha

Core library for SysML v2 and KerML parsing, AST, and semantic analysis
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
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
//! Symbol extraction from AST — pure functions that return symbols.
//!
//! This module provides functions to extract symbols from a parsed AST.
//! Unlike the old visitor-based approach, these are pure functions that
//! return data rather than mutating state.
//!
//! The extraction uses the normalized syntax layer (`crate::syntax::normalized`)
//! to provide a unified extraction path for both SysML and KerML files.

use std::sync::Arc;

use uuid::Uuid;

use crate::base::FileId;
use crate::parser::Direction;
use crate::syntax::normalized::{
    Multiplicity, NormalizedAlias, NormalizedComment, NormalizedDefKind, NormalizedDefinition,
    NormalizedDependency, NormalizedElement, NormalizedImport, NormalizedPackage,
    NormalizedRelKind, NormalizedRelationship, NormalizedUsage, NormalizedUsageKind,
};

/// Generate a new unique element ID for XMI interchange.
pub fn new_element_id() -> Arc<str> {
    Uuid::new_v4().to_string().into()
}

/// The kind of reference - determines resolution strategy.
///
/// Type references (TypedBy, Specializes) resolve via scope walking.
/// Feature references (Redefines, Subsets, References) resolve via inheritance hierarchy.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RefKind {
    /// `: Type` - type annotation, resolves via scope
    TypedBy,
    /// `:> Type` for types - specialization, resolves via scope
    Specializes,
    /// `:>> feature` - redefinition, resolves via inheritance
    Redefines,
    /// `:> feature` for features - subsetting, resolves via inheritance
    Subsets,
    /// `::> feature` - references/featured-by, resolves via inheritance
    References,
    /// Reference in an expression - context dependent
    Expression,
    /// Other relationship types (performs, satisfies, etc.)
    Other,
}

impl RefKind {
    /// Returns true if this is a type reference that should resolve via scope walking.
    pub fn is_type_reference(&self) -> bool {
        matches!(self, RefKind::TypedBy | RefKind::Specializes)
    }

    /// Returns true if this is a feature reference that resolves via inheritance.
    pub fn is_feature_reference(&self) -> bool {
        matches!(
            self,
            RefKind::Redefines | RefKind::Subsets | RefKind::References
        )
    }

    /// Convert from NormalizedRelKind.
    pub fn from_normalized(kind: NormalizedRelKind) -> Self {
        match kind {
            NormalizedRelKind::TypedBy => RefKind::TypedBy,
            NormalizedRelKind::Specializes => RefKind::Specializes,
            NormalizedRelKind::Redefines => RefKind::Redefines,
            NormalizedRelKind::Subsets => RefKind::Subsets,
            NormalizedRelKind::References => RefKind::References,
            NormalizedRelKind::Expression => RefKind::Expression,
            _ => RefKind::Other,
        }
    }

    /// Get a display label for this reference kind.
    pub fn display(&self) -> &'static str {
        match self {
            RefKind::TypedBy => "typed by",
            RefKind::Specializes => "specializes",
            RefKind::Redefines => "redefines",
            RefKind::Subsets => "subsets",
            RefKind::References => "references",
            RefKind::Expression => "expression",
            RefKind::Other => "other",
        }
    }
}

// ============================================================================
// RELATIONSHIPS
// ============================================================================

/// The kind of relationship between symbols.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RelationshipKind {
    /// `:>` - specialization (for definitions)
    Specializes,
    /// `:` - typing (for usages)
    TypedBy,
    /// `:>>` - redefinition
    Redefines,
    /// `subsets` - subsetting
    Subsets,
    /// `::>` - references/featured-by
    References,
    // Domain-specific relationships
    /// `satisfy` - requirement satisfaction
    Satisfies,
    /// `perform` - action performance
    Performs,
    /// `exhibit` - state exhibition
    Exhibits,
    /// `include` - use case inclusion
    Includes,
    /// `assert` - constraint assertion
    Asserts,
    /// `verify` - verification
    Verifies,
}

impl RelationshipKind {
    /// Convert from NormalizedRelKind.
    pub fn from_normalized(kind: NormalizedRelKind) -> Option<Self> {
        match kind {
            NormalizedRelKind::Specializes => Some(RelationshipKind::Specializes),
            NormalizedRelKind::TypedBy => Some(RelationshipKind::TypedBy),
            NormalizedRelKind::Redefines => Some(RelationshipKind::Redefines),
            NormalizedRelKind::Subsets => Some(RelationshipKind::Subsets),
            NormalizedRelKind::References => Some(RelationshipKind::References),
            NormalizedRelKind::Satisfies => Some(RelationshipKind::Satisfies),
            NormalizedRelKind::Performs => Some(RelationshipKind::Performs),
            NormalizedRelKind::Exhibits => Some(RelationshipKind::Exhibits),
            NormalizedRelKind::Includes => Some(RelationshipKind::Includes),
            NormalizedRelKind::Asserts => Some(RelationshipKind::Asserts),
            NormalizedRelKind::Verifies => Some(RelationshipKind::Verifies),
            // Expression, About, Meta, Crosses are not shown as relationships
            _ => None,
        }
    }

    /// Get a display label for this relationship kind.
    pub fn display(&self) -> &'static str {
        match self {
            RelationshipKind::Specializes => "Specializes",
            RelationshipKind::TypedBy => "Typed by",
            RelationshipKind::Redefines => "Redefines",
            RelationshipKind::Subsets => "Subsets",
            RelationshipKind::References => "References",
            RelationshipKind::Satisfies => "Satisfies",
            RelationshipKind::Performs => "Performs",
            RelationshipKind::Exhibits => "Exhibits",
            RelationshipKind::Includes => "Includes",
            RelationshipKind::Asserts => "Asserts",
            RelationshipKind::Verifies => "Verifies",
        }
    }
}

/// A relationship from this symbol to another.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct HirRelationship {
    /// The kind of relationship
    pub kind: RelationshipKind,
    /// The target name as written in source
    pub target: Arc<str>,
    /// The resolved qualified name (if resolved)
    pub resolved_target: Option<Arc<str>>,
    /// Start line of the target reference (0-indexed)
    pub start_line: u32,
    /// Start column (0-indexed)
    pub start_col: u32,
    /// End line (0-indexed)
    pub end_line: u32,
    /// End column (0-indexed)
    pub end_col: u32,
}

impl HirRelationship {
    /// Create a new relationship.
    pub fn new(kind: RelationshipKind, target: impl Into<Arc<str>>) -> Self {
        Self {
            kind,
            target: target.into(),
            resolved_target: None,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 0,
        }
    }

    /// Create a new relationship with span information.
    pub fn with_span(
        kind: RelationshipKind,
        target: impl Into<Arc<str>>,
        start_line: u32,
        start_col: u32,
        end_line: u32,
        end_col: u32,
    ) -> Self {
        Self {
            kind,
            target: target.into(),
            resolved_target: None,
            start_line,
            start_col,
            end_line,
            end_col,
        }
    }
}

/// A type reference with its source location.
///
/// This tracks where a type name appears in the source code,
/// enabling go-to-definition from type annotations.
///
/// Feature chains like `takePicture.focus` are detected at resolution time
/// by checking if TypeRefs are adjacent (separated by a dot). This avoids
/// storing chain metadata in the HIR layer.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TypeRef {
    /// The target type name as written in source (e.g., "Car", "focus")
    pub target: Arc<str>,
    /// The fully resolved qualified name (e.g., "Vehicle::Car", "TakePicture::focus")
    /// This is computed during the semantic resolution pass.
    pub resolved_target: Option<Arc<str>>,
    /// The kind of reference - determines resolution strategy.
    pub kind: RefKind,
    /// Start line (0-indexed)
    pub start_line: u32,
    /// Start column (0-indexed)
    pub start_col: u32,
    /// End line (0-indexed)
    pub end_line: u32,
    /// End column (0-indexed)
    pub end_col: u32,
}

impl TypeRef {
    /// Create a new type reference.
    pub fn new(
        target: impl Into<Arc<str>>,
        kind: RefKind,
        start_line: u32,
        start_col: u32,
        end_line: u32,
        end_col: u32,
    ) -> Self {
        Self {
            target: target.into(),
            resolved_target: None,
            kind,
            start_line,
            start_col,
            end_line,
            end_col,
        }
    }

    /// Check if a position is within this type reference.
    pub fn contains(&self, line: u32, col: u32) -> bool {
        let after_start =
            line > self.start_line || (line == self.start_line && col >= self.start_col);
        let before_end = line < self.end_line || (line == self.end_line && col <= self.end_col);
        after_start && before_end
    }

    /// Check if another TypeRef immediately follows this one (separated by a dot).
    /// Used to detect feature chains like `takePicture.focus` at resolution time.
    pub fn immediately_precedes(&self, other: &TypeRef) -> bool {
        // Must be on the same line
        if self.end_line != other.start_line {
            return false;
        }
        // The other ref must start exactly 1 character after this one ends (the dot)
        self.end_col + 1 == other.start_col
    }

    /// Get the best target to use for resolution - resolved if available, else raw.
    pub fn effective_target(&self) -> &Arc<str> {
        self.resolved_target.as_ref().unwrap_or(&self.target)
    }
}

/// A type reference that can be either a simple reference or a chain.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TypeRefKind {
    /// A simple reference like `Vehicle`
    Simple(TypeRef),
    /// A feature chain like `engine.power.value`
    Chain(TypeRefChain),
}

impl TypeRefKind {
    /// Get all individual TypeRefs for iteration
    pub fn as_refs(&self) -> Vec<&TypeRef> {
        match self {
            TypeRefKind::Simple(r) => vec![r],
            TypeRefKind::Chain(c) => c.parts.iter().collect(),
        }
    }

    /// Check if this is a chain
    pub fn is_chain(&self) -> bool {
        matches!(self, TypeRefKind::Chain(_))
    }

    /// Get the first part's target name
    pub fn first_target(&self) -> &Arc<str> {
        match self {
            TypeRefKind::Simple(r) => &r.target,
            TypeRefKind::Chain(c) => &c.parts[0].target,
        }
    }

    /// Check if a position is within this type reference
    pub fn contains(&self, line: u32, col: u32) -> bool {
        match self {
            TypeRefKind::Simple(r) => r.contains(line, col),
            TypeRefKind::Chain(c) => c.parts.iter().any(|r| r.contains(line, col)),
        }
    }

    /// Find which part contains the position (for chains)
    pub fn part_at(&self, line: u32, col: u32) -> Option<(usize, &TypeRef)> {
        match self {
            TypeRefKind::Simple(r) if r.contains(line, col) => Some((0, r)),
            TypeRefKind::Chain(c) => c
                .parts
                .iter()
                .enumerate()
                .find(|(_, r)| r.contains(line, col)),
            _ => None,
        }
    }
}

/// A chain of type references like `engine.power.value`
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TypeRefChain {
    /// The parts of the chain, each with its own span
    pub parts: Vec<TypeRef>,
}

impl TypeRefChain {
    /// Get the full dotted path
    pub fn as_dotted_string(&self) -> String {
        self.parts
            .iter()
            .map(|p| p.target.as_ref())
            .collect::<Vec<_>>()
            .join(".")
    }
}

/// A symbol extracted from the AST.
///
/// This is a simplified symbol type for the new HIR layer.
/// It captures the essential information needed for IDE features.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct HirSymbol {
    /// The simple name of the symbol
    pub name: Arc<str>,
    /// The short name alias (e.g., "m" for "metre"), if any
    pub short_name: Option<Arc<str>>,
    /// The fully qualified name
    pub qualified_name: Arc<str>,
    /// Unique element ID for XMI interchange.
    /// Generated at parse time for all symbols, preserved on import/export.
    pub element_id: Arc<str>,
    /// What kind of symbol this is
    pub kind: SymbolKind,
    /// The file containing this symbol
    pub file: FileId,
    /// Start line (0-indexed)
    pub start_line: u32,
    /// Start column (0-indexed)
    pub start_col: u32,
    /// End line (0-indexed)
    pub end_line: u32,
    /// End column (0-indexed)
    pub end_col: u32,
    /// Short name span (for hover support on short names)
    pub short_name_start_line: Option<u32>,
    pub short_name_start_col: Option<u32>,
    pub short_name_end_line: Option<u32>,
    pub short_name_end_col: Option<u32>,
    /// Documentation comment, if any
    pub doc: Option<Arc<str>>,
    /// Types this symbol specializes/subsets (kept for backwards compat)
    pub supertypes: Vec<Arc<str>>,
    /// All relationships from this symbol (specializes, typed by, satisfies, etc.)
    pub relationships: Vec<HirRelationship>,
    /// Type references with their source locations (for goto-definition on type annotations)
    pub type_refs: Vec<TypeRefKind>,
    /// Whether this symbol is public (for imports: re-exported to child scopes)
    pub is_public: bool,
    /// View-specific data (for ViewDefinition, ViewUsage, etc.)
    pub view_data: Option<crate::hir::views::ViewData>,
    /// Metadata types applied to this symbol (e.g., ["Safety", "Approved"])
    /// Used for filter import evaluation (SysML v2 §7.5.4)
    pub metadata_annotations: Vec<Arc<str>>,
    /// Whether this symbol is abstract (for definitions and usages)
    pub is_abstract: bool,
    /// Whether this symbol is a variation (for definitions and usages)
    pub is_variation: bool,
    /// Whether this symbol is readonly (for usages only)
    pub is_readonly: bool,
    /// Whether this symbol is derived (for usages only)
    pub is_derived: bool,
    /// Whether this symbol is parallel (for state usages)
    pub is_parallel: bool,
    /// Whether this symbol is individual (singleton occurrence)
    pub is_individual: bool,
    /// Whether this symbol is an end feature (connector endpoint)
    pub is_end: bool,
    /// Whether this symbol has a default value
    pub is_default: bool,
    /// Whether this symbol's values are ordered
    pub is_ordered: bool,
    /// Whether this symbol's values are nonunique (can have duplicates)
    pub is_nonunique: bool,
    /// Whether this symbol is a portion (slice of occurrence)
    pub is_portion: bool,
    /// Direction (in, out, inout) for ports and parameters
    pub direction: Option<Direction>,
    /// Multiplicity bounds [lower..upper]
    pub multiplicity: Option<Multiplicity>,
}

/// The kind of a symbol.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SymbolKind {
    Package,
    // Definitions
    PartDefinition,
    ItemDefinition,
    ActionDefinition,
    PortDefinition,
    AttributeDefinition,
    ConnectionDefinition,
    InterfaceDefinition,
    AllocationDefinition,
    RequirementDefinition,
    ConstraintDefinition,
    StateDefinition,
    CalculationDefinition,
    UseCaseDefinition,
    AnalysisCaseDefinition,
    ConcernDefinition,
    ViewDefinition,
    ViewpointDefinition,
    RenderingDefinition,
    ViewUsage,
    ViewpointUsage,
    RenderingUsage,
    EnumerationDefinition,
    MetadataDefinition,
    Interaction,
    // KerML Definitions
    DataType,
    Class,
    Structure,
    Behavior,
    Function,
    Association,
    // Usages
    PartUsage,
    ItemUsage,
    ActionUsage,
    PortUsage,
    AttributeUsage,
    ConnectionUsage,
    InterfaceUsage,
    AllocationUsage,
    RequirementUsage,
    ConstraintUsage,
    StateUsage,
    TransitionUsage,
    CalculationUsage,
    ReferenceUsage,
    OccurrenceUsage,
    FlowConnectionUsage,
    // Relationships
    ExposeRelationship,
    // Other
    Import,
    Alias,
    Comment,
    Dependency,
    // Generic fallback
    Other,
}

impl SymbolKind {
    /// Create from a NormalizedDefKind.
    pub fn from_definition_kind(kind: &NormalizedDefKind) -> Self {
        match kind {
            NormalizedDefKind::Part => Self::PartDefinition,
            NormalizedDefKind::Item => Self::ItemDefinition,
            NormalizedDefKind::Action => Self::ActionDefinition,
            NormalizedDefKind::Port => Self::PortDefinition,
            NormalizedDefKind::Attribute => Self::AttributeDefinition,
            NormalizedDefKind::Connection => Self::ConnectionDefinition,
            NormalizedDefKind::Interface => Self::InterfaceDefinition,
            NormalizedDefKind::Allocation => Self::AllocationDefinition,
            NormalizedDefKind::Requirement => Self::RequirementDefinition,
            NormalizedDefKind::Constraint => Self::ConstraintDefinition,
            NormalizedDefKind::State => Self::StateDefinition,
            NormalizedDefKind::Calculation => Self::CalculationDefinition,
            NormalizedDefKind::UseCase => Self::UseCaseDefinition,
            NormalizedDefKind::AnalysisCase => Self::AnalysisCaseDefinition,
            NormalizedDefKind::Concern => Self::ConcernDefinition,
            NormalizedDefKind::View => Self::ViewDefinition,
            NormalizedDefKind::Viewpoint => Self::ViewpointDefinition,
            NormalizedDefKind::Rendering => Self::RenderingDefinition,
            NormalizedDefKind::Enumeration => Self::EnumerationDefinition,
            // KerML definitions
            NormalizedDefKind::DataType => Self::DataType,
            NormalizedDefKind::Class => Self::Class,
            NormalizedDefKind::Structure => Self::Structure,
            NormalizedDefKind::Behavior => Self::Behavior,
            NormalizedDefKind::Function => Self::Function,
            NormalizedDefKind::Association => Self::Association,
            NormalizedDefKind::Metaclass => Self::MetadataDefinition,
            NormalizedDefKind::Interaction => Self::Interaction,
            NormalizedDefKind::Other => Self::Other,
        }
    }

    /// Create from a NormalizedUsageKind.
    pub fn from_usage_kind(kind: &NormalizedUsageKind) -> Self {
        match kind {
            NormalizedUsageKind::Part => Self::PartUsage,
            NormalizedUsageKind::Item => Self::ItemUsage,
            NormalizedUsageKind::Action => Self::ActionUsage,
            NormalizedUsageKind::Port => Self::PortUsage,
            NormalizedUsageKind::Attribute => Self::AttributeUsage,
            NormalizedUsageKind::Connection => Self::ConnectionUsage,
            NormalizedUsageKind::Interface => Self::InterfaceUsage,
            NormalizedUsageKind::Allocation => Self::AllocationUsage,
            NormalizedUsageKind::Requirement => Self::RequirementUsage,
            NormalizedUsageKind::Constraint => Self::ConstraintUsage,
            NormalizedUsageKind::State => Self::StateUsage,
            NormalizedUsageKind::Calculation => Self::CalculationUsage,
            NormalizedUsageKind::Reference => Self::ReferenceUsage,
            NormalizedUsageKind::Occurrence => Self::OccurrenceUsage,
            NormalizedUsageKind::Flow => Self::FlowConnectionUsage,
            NormalizedUsageKind::Transition => Self::TransitionUsage,
            NormalizedUsageKind::Accept => Self::ActionUsage, // Accept payloads are action usages
            NormalizedUsageKind::End => Self::PortUsage,      // Connection endpoints are like ports
            NormalizedUsageKind::Fork => Self::ActionUsage,   // Fork nodes are action usages
            NormalizedUsageKind::Join => Self::ActionUsage,   // Join nodes are action usages
            NormalizedUsageKind::Merge => Self::ActionUsage,  // Merge nodes are action usages
            NormalizedUsageKind::Decide => Self::ActionUsage, // Decide nodes are action usages
            NormalizedUsageKind::Feature => Self::PartUsage,  // KerML features map to part usage
            NormalizedUsageKind::View => Self::ViewUsage,
            NormalizedUsageKind::Viewpoint => Self::ViewpointUsage,
            NormalizedUsageKind::Rendering => Self::RenderingUsage,
            NormalizedUsageKind::Other => Self::Other,
        }
    }

    /// Get a display string for this kind (capitalized for UI display).
    pub fn display(&self) -> &'static str {
        match self {
            Self::Package => "Package",
            Self::PartDefinition => "Part def",
            Self::ItemDefinition => "Item def",
            Self::ActionDefinition => "Action def",
            Self::PortDefinition => "Port def",
            Self::AttributeDefinition => "Attribute def",
            Self::ConnectionDefinition => "Connection def",
            Self::InterfaceDefinition => "Interface def",
            Self::AllocationDefinition => "Allocation def",
            Self::RequirementDefinition => "Requirement def",
            Self::ConstraintDefinition => "Constraint def",
            Self::StateDefinition => "State def",
            Self::CalculationDefinition => "Calc def",
            Self::UseCaseDefinition => "Use case def",
            Self::AnalysisCaseDefinition => "Analysis case def",
            Self::ConcernDefinition => "Concern def",
            Self::ViewDefinition => "View def",
            Self::ViewpointDefinition => "Viewpoint def",
            Self::RenderingDefinition => "Rendering def",
            Self::ViewUsage => "View",
            Self::ViewpointUsage => "Viewpoint",
            Self::RenderingUsage => "Rendering",
            Self::EnumerationDefinition => "Enum def",
            Self::MetadataDefinition => "Metaclass def",
            Self::Interaction => "Interaction def",
            // KerML definitions
            Self::DataType => "Datatype",
            Self::Class => "Class",
            Self::Structure => "Struct",
            Self::Behavior => "Behavior",
            Self::Function => "Function",
            Self::Association => "Assoc",
            Self::PartUsage => "Part",
            Self::ItemUsage => "Item",
            Self::ActionUsage => "Action",
            Self::PortUsage => "Port",
            Self::AttributeUsage => "Attribute",
            Self::ConnectionUsage => "Connection",
            Self::InterfaceUsage => "Interface",
            Self::AllocationUsage => "Allocation",
            Self::RequirementUsage => "Requirement",
            Self::ConstraintUsage => "Constraint",
            Self::StateUsage => "State",
            Self::TransitionUsage => "Transition",
            Self::CalculationUsage => "Calc",
            Self::ReferenceUsage => "Ref",
            Self::OccurrenceUsage => "Occurrence",
            Self::FlowConnectionUsage => "Flow",
            Self::ExposeRelationship => "Expose",
            Self::Import => "Import",
            Self::Alias => "Alias",
            Self::Comment => "Comment",
            Self::Dependency => "Dependency",
            Self::Other => "Element",
        }
    }

    /// Convert a normalized definition kind to a SymbolKind.
    pub fn from_normalized_def_kind(kind: NormalizedDefKind) -> Self {
        match kind {
            NormalizedDefKind::Part => Self::PartDefinition,
            NormalizedDefKind::Item => Self::ItemDefinition,
            NormalizedDefKind::Action => Self::ActionDefinition,
            NormalizedDefKind::Port => Self::PortDefinition,
            NormalizedDefKind::Attribute => Self::AttributeDefinition,
            NormalizedDefKind::Connection => Self::ConnectionDefinition,
            NormalizedDefKind::Interface => Self::InterfaceDefinition,
            NormalizedDefKind::Allocation => Self::AllocationDefinition,
            NormalizedDefKind::Requirement => Self::RequirementDefinition,
            NormalizedDefKind::Constraint => Self::ConstraintDefinition,
            NormalizedDefKind::State => Self::StateDefinition,
            NormalizedDefKind::Calculation => Self::CalculationDefinition,
            NormalizedDefKind::UseCase => Self::UseCaseDefinition,
            NormalizedDefKind::AnalysisCase => Self::AnalysisCaseDefinition,
            NormalizedDefKind::Concern => Self::ConcernDefinition,
            NormalizedDefKind::View => Self::ViewDefinition,
            NormalizedDefKind::Viewpoint => Self::ViewpointDefinition,
            NormalizedDefKind::Rendering => Self::RenderingDefinition,
            NormalizedDefKind::Enumeration => Self::EnumerationDefinition,
            // KerML definitions
            NormalizedDefKind::DataType => Self::DataType,
            NormalizedDefKind::Class => Self::Class,
            NormalizedDefKind::Structure => Self::Structure,
            NormalizedDefKind::Behavior => Self::Behavior,
            NormalizedDefKind::Function => Self::Function,
            NormalizedDefKind::Association => Self::Association,
            NormalizedDefKind::Metaclass => Self::MetadataDefinition,
            NormalizedDefKind::Interaction => Self::Interaction,
            NormalizedDefKind::Other => Self::Other,
        }
    }

    /// Convert a normalized usage kind to a SymbolKind.
    pub fn from_normalized_usage_kind(kind: NormalizedUsageKind) -> Self {
        match kind {
            NormalizedUsageKind::Part => Self::PartUsage,
            NormalizedUsageKind::Item => Self::ItemUsage,
            NormalizedUsageKind::Action => Self::ActionUsage,
            NormalizedUsageKind::Port => Self::PortUsage,
            NormalizedUsageKind::Attribute => Self::AttributeUsage,
            NormalizedUsageKind::Connection => Self::ConnectionUsage,
            NormalizedUsageKind::Interface => Self::InterfaceUsage,
            NormalizedUsageKind::Allocation => Self::AllocationUsage,
            NormalizedUsageKind::Requirement => Self::RequirementUsage,
            NormalizedUsageKind::Constraint => Self::ConstraintUsage,
            NormalizedUsageKind::State => Self::StateUsage,
            NormalizedUsageKind::Calculation => Self::CalculationUsage,
            NormalizedUsageKind::Reference => Self::ReferenceUsage,
            NormalizedUsageKind::Occurrence => Self::OccurrenceUsage,
            NormalizedUsageKind::Flow => Self::FlowConnectionUsage,
            NormalizedUsageKind::Transition => Self::TransitionUsage,
            NormalizedUsageKind::Accept => Self::ActionUsage, // Accept payloads are action usages
            NormalizedUsageKind::End => Self::PortUsage,      // Connection endpoints are like ports
            NormalizedUsageKind::Fork => Self::ActionUsage,   // Fork nodes are action usages
            NormalizedUsageKind::Join => Self::ActionUsage,   // Join nodes are action usages
            NormalizedUsageKind::Merge => Self::ActionUsage,  // Merge nodes are action usages
            NormalizedUsageKind::Decide => Self::ActionUsage, // Decide nodes are action usages
            NormalizedUsageKind::View => Self::ViewUsage,
            NormalizedUsageKind::Viewpoint => Self::ViewpointUsage,
            NormalizedUsageKind::Rendering => Self::RenderingUsage,
            // KerML features are treated as attribute usages
            NormalizedUsageKind::Feature => Self::AttributeUsage,
            NormalizedUsageKind::Other => Self::Other,
        }
    }
}

// ============================================================================
// EXTRACTION CONTEXT
// ============================================================================

struct ExtractionContext {
    file: FileId,
    prefix: String,
    /// Counter for generating unique anonymous scope names
    anon_counter: u32,
    /// Stack of scope segments for proper push/pop
    scope_stack: Vec<String>,
    /// Line index for converting byte offsets to line/column
    line_index: crate::base::LineIndex,
}

impl ExtractionContext {
    fn qualified_name(&self, name: &str) -> String {
        if self.prefix.is_empty() {
            name.to_string()
        } else {
            format!("{}::{}", self.prefix, name)
        }
    }

    /// Get the current scope name (the prefix without trailing ::)
    fn current_scope_name(&self) -> String {
        self.prefix.clone()
    }

    fn push_scope(&mut self, name: &str) {
        self.scope_stack.push(name.to_string());
        if self.prefix.is_empty() {
            self.prefix = name.to_string();
        } else {
            self.prefix = format!("{}::{}", self.prefix, name);
        }
    }

    fn pop_scope(&mut self) {
        if let Some(popped) = self.scope_stack.pop() {
            // Remove the last segment (which may contain ::) plus the joining ::
            let suffix_len = if self.scope_stack.is_empty() {
                popped.len()
            } else {
                popped.len() + 2 // +2 for the "::" separator
            };
            self.prefix
                .truncate(self.prefix.len().saturating_sub(suffix_len));
        }
    }

    /// Generate a unique anonymous scope name
    fn next_anon_scope(&mut self, rel_prefix: &str, target: &str, line: u32) -> String {
        self.anon_counter += 1;
        format!("<{}{}#{}@L{}>", rel_prefix, target, self.anon_counter, line)
    }

    /// Convert a TextRange to SpanInfo using the line index
    fn range_to_info(&self, range: Option<rowan::TextRange>) -> SpanInfo {
        match range {
            Some(r) => {
                let start = self.line_index.line_col(r.start());
                let end = self.line_index.line_col(r.end());
                SpanInfo {
                    start_line: start.line,
                    start_col: start.col,
                    end_line: end.line,
                    end_col: end.col,
                }
            }
            None => SpanInfo::default(),
        }
    }

    /// Convert a TextRange to optional line/col values (for short_name fields)
    fn range_to_optional(
        &self,
        range: Option<rowan::TextRange>,
    ) -> (Option<u32>, Option<u32>, Option<u32>, Option<u32>) {
        match range {
            Some(r) => {
                let start = self.line_index.line_col(r.start());
                let end = self.line_index.line_col(r.end());
                (
                    Some(start.line),
                    Some(start.col),
                    Some(end.line),
                    Some(end.col),
                )
            }
            None => (None, None, None, None),
        }
    }
}

// ============================================================================
// UNIFIED EXTRACTION (using normalized types)
// ============================================================================

/// Result of symbol extraction, including both symbols and scope filters.
#[derive(Debug, Default)]
pub struct ExtractionResult {
    /// Extracted symbols.
    pub symbols: Vec<HirSymbol>,
    /// Filters for each scope (scope qualified name -> metadata names).
    /// Elements imported into a scope must have ALL listed metadata to be visible.
    /// These come from `filter @Metadata;` statements.
    pub scope_filters: Vec<(Arc<str>, Vec<String>)>,
    /// Filters for specific imports (import qualified name -> metadata names).
    /// These come from bracket syntax: `import X::*[@Filter]`
    pub import_filters: Vec<(Arc<str>, Vec<String>)>,
}

/// Extract all symbols from any syntax file using the normalized adapter layer.
///
/// This is the preferred extraction function as it handles both SysML and KerML
/// through a unified code path.
pub fn extract_symbols_unified(file: FileId, syntax: &crate::syntax::SyntaxFile) -> Vec<HirSymbol> {
    extract_with_filters(file, syntax).symbols
}

/// Extract symbols and filters from any syntax file.
///
/// Returns both symbols and scope filter information for import filtering.
pub fn extract_with_filters(file: FileId, syntax: &crate::syntax::SyntaxFile) -> ExtractionResult {
    let mut result = ExtractionResult::default();
    let line_index = syntax.line_index();
    let mut context = ExtractionContext {
        file,
        prefix: String::new(),
        anon_counter: 0,
        scope_stack: Vec::new(),
        line_index,
    };

    // Get the rowan SourceFile and iterate over its members
    if let Some(source_file) = syntax.source_file() {
        for member in source_file.members() {
            let normalized = NormalizedElement::from_rowan(&member);
            extract_from_normalized(&mut result, &mut context, &normalized);
        }
    }

    result
}

/// Extract from a normalized element.
fn extract_from_normalized(
    result: &mut ExtractionResult,
    ctx: &mut ExtractionContext,
    element: &NormalizedElement,
) {
    match element {
        NormalizedElement::Package(pkg) => extract_from_normalized_package(result, ctx, pkg),
        NormalizedElement::Definition(def) => {
            extract_from_normalized_definition(&mut result.symbols, ctx, def)
        }
        NormalizedElement::Usage(usage) => {
            extract_from_normalized_usage(&mut result.symbols, ctx, usage)
        }
        NormalizedElement::Import(import) => {
            // Extract import symbol
            extract_from_normalized_import(&mut result.symbols, ctx, import);
            // Store bracket filters if present
            if !import.filters.is_empty() {
                let import_qname = ctx.qualified_name(&format!("import:{}", import.path));
                result
                    .import_filters
                    .push((Arc::from(import_qname.as_str()), import.filters.clone()));
            }
        }
        NormalizedElement::Alias(alias) => {
            extract_from_normalized_alias(&mut result.symbols, ctx, alias)
        }
        NormalizedElement::Comment(comment) => {
            extract_from_normalized_comment(&mut result.symbols, ctx, comment)
        }
        NormalizedElement::Dependency(dep) => {
            extract_from_normalized_dependency(&mut result.symbols, ctx, dep)
        }
        NormalizedElement::Filter(filter) => {
            // Store filter for current scope (for import filtering)
            let scope = ctx.current_scope_name();
            if !filter.metadata_refs.is_empty() {
                result.scope_filters.push((
                    Arc::from(scope.as_str()),
                    filter.metadata_refs.iter().map(|s| s.to_string()).collect(),
                ));
            }

            // Create type_refs for all qualified names in the filter expression
            // so hover/go-to-def works on filter terms like `Safety::isMandatory`
            if !filter.all_refs.is_empty() {
                let type_refs: Vec<TypeRefKind> = filter
                    .all_refs
                    .iter()
                    .map(|(name, range)| {
                        let start = ctx.line_index.line_col(range.start());
                        let end = ctx.line_index.line_col(range.end());
                        TypeRefKind::Simple(TypeRef {
                            target: Arc::from(name.as_str()),
                            resolved_target: None,
                            kind: RefKind::Other, // Filter refs are expression-like
                            start_line: start.line,
                            start_col: start.col,
                            end_line: end.line,
                            end_col: end.col,
                        })
                    })
                    .collect();

                // Create an anonymous symbol to hold the type_refs
                let span = ctx.range_to_info(filter.range);
                let filter_qname = ctx.qualified_name(&format!("<filter@L{}>", span.start_line));
                result.symbols.push(HirSymbol {
                    name: Arc::from("<filter>"),
                    short_name: None,
                    qualified_name: Arc::from(filter_qname.as_str()),
                    element_id: new_element_id(),
                    kind: SymbolKind::Other,
                    file: ctx.file,
                    start_line: span.start_line,
                    start_col: span.start_col,
                    end_line: span.end_line,
                    end_col: span.end_col,
                    short_name_start_line: None,
                    short_name_start_col: None,
                    short_name_end_line: None,
                    short_name_end_col: None,
                    doc: None,
                    supertypes: Vec::new(),
                    relationships: Vec::new(),
                    type_refs,
                    is_public: false,
                    view_data: None,
                    metadata_annotations: Vec::new(),
                    is_abstract: false,
                    is_variation: false,
                    is_readonly: false,
                    is_derived: false,
                    is_parallel: false,
                    is_individual: false,
                    is_end: false,
                    is_default: false,
                    is_ordered: false,
                    is_nonunique: false,
                    is_portion: false,
                    direction: None,
                    multiplicity: None,
                });
            }
        }
        NormalizedElement::Expose(_expose) => {
            // Expose relationships are handled during view extraction, not symbol extraction
        }
    }
}

/// Extract from a normalized element into a symbol list (no filter support).
/// Used for nested extraction within definitions/usages.
fn extract_from_normalized_into_symbols(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    element: &NormalizedElement,
) {
    match element {
        NormalizedElement::Package(pkg) => {
            // For nested packages, create a temporary result
            let mut result = ExtractionResult::default();
            extract_from_normalized_package(&mut result, ctx, pkg);
            symbols.extend(result.symbols);
        }
        NormalizedElement::Definition(def) => extract_from_normalized_definition(symbols, ctx, def),
        NormalizedElement::Usage(usage) => extract_from_normalized_usage(symbols, ctx, usage),
        NormalizedElement::Import(import) => extract_from_normalized_import(symbols, ctx, import),
        NormalizedElement::Alias(alias) => extract_from_normalized_alias(symbols, ctx, alias),
        NormalizedElement::Comment(comment) => {
            extract_from_normalized_comment(symbols, ctx, comment)
        }
        NormalizedElement::Dependency(dep) => extract_from_normalized_dependency(symbols, ctx, dep),
        NormalizedElement::Filter(_filter) => {
            // Filters don't produce symbols, they're metadata for views
            // They will be extracted when processing the parent view definition
        }
        NormalizedElement::Expose(_expose) => {
            // Expose relationships don't produce symbols, they define view visibility
            // They will be extracted when processing the parent view definition/usage
        }
    }
}

fn extract_from_normalized_package(
    result: &mut ExtractionResult,
    ctx: &mut ExtractionContext,
    pkg: &NormalizedPackage,
) {
    let name = match &pkg.name {
        Some(n) => strip_quotes(n),
        None => return,
    };

    let qualified_name = ctx.qualified_name(&name);
    // Use name_range for precise position, fall back to full range
    let span = ctx.range_to_info(pkg.name_range.or(pkg.range));

    // Extract doc comment
    let doc = pkg.doc.as_ref().map(|s| Arc::from(s.trim()));

    result.symbols.push(HirSymbol {
        name: Arc::from(name.as_str()),
        short_name: pkg.short_name.as_ref().map(|s| Arc::from(s.as_str())),
        qualified_name: Arc::from(qualified_name.as_str()),
        element_id: new_element_id(),
        kind: SymbolKind::Package,
        file: ctx.file,
        start_line: span.start_line,
        start_col: span.start_col,
        end_line: span.end_line,
        end_col: span.end_col,
        short_name_start_line: None,
        short_name_start_col: None,
        short_name_end_line: None,
        short_name_end_col: None,
        doc,
        supertypes: Vec::new(),
        relationships: Vec::new(),
        type_refs: Vec::new(),
        is_public: false,
        view_data: None,
        metadata_annotations: Vec::new(),
        is_abstract: false,
        is_variation: false,
        is_readonly: false,
        is_derived: false,
        is_parallel: false,
        is_individual: false,
        is_end: false,
        is_default: false,
        is_ordered: false,
        is_nonunique: false,
        is_portion: false,
        direction: None,
        multiplicity: None,
    });

    ctx.push_scope(&name);
    for child in &pkg.children {
        extract_from_normalized(result, ctx, child);
    }
    ctx.pop_scope();
}

/// Get the implicit supertype for a definition kind based on SysML kernel library.
/// In SysML, all definitions implicitly specialize their kernel metaclass:
/// - `part def X` implicitly specializes `Parts::Part`
/// - `item def X` implicitly specializes `Items::Item`
/// - `action def X` implicitly specializes `Actions::Action`
/// - etc.
fn implicit_supertype_for_def_kind(kind: NormalizedDefKind) -> Option<&'static str> {
    match kind {
        NormalizedDefKind::Part => Some("Parts::Part"),
        NormalizedDefKind::Item => Some("Items::Item"),
        NormalizedDefKind::Action => Some("Actions::Action"),
        NormalizedDefKind::State => Some("States::StateAction"),
        NormalizedDefKind::Constraint => Some("Constraints::ConstraintCheck"),
        NormalizedDefKind::Requirement => Some("Requirements::RequirementCheck"),
        NormalizedDefKind::Calculation => Some("Calculations::Calculation"),
        NormalizedDefKind::Port => Some("Ports::Port"),
        // Use BinaryConnection for connection def since most connections are binary
        // and need access to source/target features from BinaryLinkObject
        NormalizedDefKind::Connection => Some("Connections::BinaryConnection"),
        NormalizedDefKind::Interface => Some("Interfaces::Interface"),
        NormalizedDefKind::Allocation => Some("Allocations::Allocation"),
        NormalizedDefKind::UseCase => Some("UseCases::UseCase"),
        NormalizedDefKind::AnalysisCase => Some("AnalysisCases::AnalysisCase"),
        NormalizedDefKind::Attribute => Some("Attributes::AttributeValue"),
        _ => None,
    }
}

/// Get the implicit supertype for a usage kind based on SysML kernel library.
/// In SysML, usages implicitly specialize their kernel metaclass base type:
/// - `part x` implicitly specializes `Parts::Part`
/// - `item x` implicitly specializes `Items::Item`
/// - `message x` implicitly specializes `Flows::Message`
/// - `flow x` implicitly specializes `Flows::Flow`
/// - etc.
fn implicit_supertype_for_usage_kind(kind: NormalizedUsageKind) -> Option<&'static str> {
    match kind {
        NormalizedUsageKind::Part => Some("Parts::Part"),
        NormalizedUsageKind::Item => Some("Items::Item"),
        NormalizedUsageKind::Action => Some("Actions::Action"),
        NormalizedUsageKind::State => Some("States::StateAction"),
        NormalizedUsageKind::Flow => Some("Flows::Message"),
        NormalizedUsageKind::Connection => Some("Connections::Connection"),
        NormalizedUsageKind::Interface => Some("Interfaces::Interface"),
        NormalizedUsageKind::Allocation => Some("Allocations::Allocation"),
        NormalizedUsageKind::Requirement => Some("Requirements::RequirementCheck"),
        NormalizedUsageKind::Constraint => Some("Constraints::ConstraintCheck"),
        NormalizedUsageKind::Calculation => Some("Calculations::Calculation"),
        NormalizedUsageKind::Port => Some("Ports::Port"),
        NormalizedUsageKind::Attribute => Some("Attributes::AttributeValue"),
        _ => None,
    }
}

/// Extract relationships from normalized relationships.
fn extract_relationships_from_normalized(
    relationships: &[NormalizedRelationship],
    line_index: &crate::base::LineIndex,
) -> Vec<HirRelationship> {
    relationships
        .iter()
        .filter_map(|rel| {
            RelationshipKind::from_normalized(rel.kind).map(|kind| {
                let (start_line, start_col, end_line, end_col) = rel
                    .range
                    .map(|r| {
                        let start = line_index.line_col(r.start());
                        let end = line_index.line_col(r.end());
                        (start.line, start.col, end.line, end.col)
                    })
                    .unwrap_or((0, 0, 0, 0));
                HirRelationship::with_span(
                    kind,
                    rel.target.as_str().as_ref(),
                    start_line,
                    start_col,
                    end_line,
                    end_col,
                )
            })
        })
        .collect()
}

/// Extract metadata annotations from normalized relationships and children.
/// Returns the simple names of metadata types applied to this element.
///
/// Metadata can be applied in two ways:
/// 1. Via `relationships.meta` (e.g., from expression contexts)
/// 2. Via nested metadata usage children (e.g., `part x { @Safety; }`)
///
/// For nested metadata usages, we look at children that have no original name
/// (anonymous usages) and are typed by metadata definitions.
fn extract_metadata_annotations(
    relationships: &[NormalizedRelationship],
    children: &[NormalizedElement],
) -> Vec<Arc<str>> {
    let mut annotations = Vec::new();

    // Extract from relationships (Meta kind)
    for rel in relationships.iter() {
        if matches!(rel.kind, NormalizedRelKind::Meta) {
            let target = rel.target.as_str();
            let simple_name = target.rsplit("::").next().unwrap_or(&target);
            annotations.push(Arc::from(simple_name));
        }
    }

    // Extract from children that are metadata usages
    // In SysML, `@Safety` inside a body becomes a child usage typed by Safety
    // These children are originally anonymous (name=None in the source) but get
    // generated anon names during extraction. We identify them by:
    // 1. Having no original name (name.is_none()) - they're originally anonymous
    // 2. Having a TypedBy relationship to what looks like a metadata type
    for child in children.iter() {
        if let NormalizedElement::Usage(usage) = child {
            // Metadata usages are originally anonymous in the source
            // (the name gets assigned later during symbol extraction)
            if usage.name.is_none() {
                for rel in &usage.relationships {
                    if matches!(rel.kind, NormalizedRelKind::TypedBy) {
                        let target = rel.target.as_str();
                        let simple_name = target.rsplit("::").next().unwrap_or(&target);
                        annotations.push(Arc::from(simple_name));
                    }
                }
            }
        }
    }

    annotations
}

fn extract_from_normalized_definition(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    def: &NormalizedDefinition,
) {
    let name = match &def.name {
        Some(n) => strip_quotes(n),
        None => return,
    };

    let qualified_name = ctx.qualified_name(&name);
    let kind = SymbolKind::from_normalized_def_kind(def.kind);
    // Use name_range for precise position, fall back to full range
    let span = ctx.range_to_info(def.name_range.or(def.range));
    let (sn_start_line, sn_start_col, sn_end_line, sn_end_col) =
        ctx.range_to_optional(def.short_name_range);

    // Extract explicit supertypes from relationships
    let mut supertypes: Vec<Arc<str>> = def
        .relationships
        .iter()
        .filter(|r| matches!(r.kind, NormalizedRelKind::Specializes))
        .map(|r| Arc::from(r.target.as_str().as_ref()))
        .collect();

    // Add implicit supertypes from SysML kernel library if no explicit specialization
    // This models the implicit inheritance: part def → Part, item def → Item, etc.
    if supertypes.is_empty() {
        if let Some(implicit) = implicit_supertype_for_def_kind(def.kind) {
            supertypes.push(Arc::from(implicit));
        }
    }

    // Extract type references from relationships
    let type_refs = extract_type_refs_from_normalized(&def.relationships, &ctx.line_index);

    // Extract all relationships for hover display
    let relationships = extract_relationships_from_normalized(&def.relationships, &ctx.line_index);

    // Extract metadata annotations for filter imports
    let metadata_annotations = extract_metadata_annotations(&def.relationships, &def.children);

    // Extract doc comment
    let doc = def.doc.as_ref().map(|s| Arc::from(s.trim()));

    // Extract view-specific data if this is a view/viewpoint/rendering
    let view_data = extract_view_data_from_definition(def, def.kind);

    symbols.push(HirSymbol {
        name: Arc::from(name.as_str()),
        short_name: def.short_name.as_ref().map(|s| Arc::from(s.as_str())),
        qualified_name: Arc::from(qualified_name.as_str()),
        element_id: new_element_id(),
        kind,
        file: ctx.file,
        start_line: span.start_line,
        start_col: span.start_col,
        end_line: span.end_line,
        end_col: span.end_col,
        short_name_start_line: sn_start_line,
        short_name_start_col: sn_start_col,
        short_name_end_line: sn_end_line,
        short_name_end_col: sn_end_col,
        doc,
        supertypes,
        relationships,
        type_refs,
        is_public: false,
        view_data,
        metadata_annotations,
        is_abstract: def.is_abstract,
        is_variation: def.is_variation,
        is_readonly: false,
        is_derived: false,
        is_parallel: false,
        is_individual: def.is_individual,
        is_end: false,
        is_default: false,
        is_ordered: false,
        is_nonunique: false,
        is_portion: false,
        direction: None,
        multiplicity: None,
    });

    // Recurse into children
    ctx.push_scope(&name);
    for child in &def.children {
        extract_from_normalized_into_symbols(symbols, ctx, child);
    }
    ctx.pop_scope();
}

fn extract_from_normalized_usage(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    usage: &NormalizedUsage,
) {
    // Extract type references even for anonymous usages
    let type_refs = extract_type_refs_from_normalized(&usage.relationships, &ctx.line_index);

    // Extract all relationships for hover display
    let relationships =
        extract_relationships_from_normalized(&usage.relationships, &ctx.line_index);

    // Extract metadata annotations for filter imports
    let metadata_annotations = extract_metadata_annotations(&usage.relationships, &usage.children);

    // For anonymous usages, attach refs to the parent but still recurse into children
    let name = match &usage.name {
        Some(n) => strip_quotes(n),
        None => {
            // Attach ONLY type refs (not feature refs) to parent for anonymous usages
            // Feature refs (Redefines, Subsets, Specializes) need inheritance context
            // that the parent doesn't have
            // Also skip packages - they shouldn't have type_refs from their anonymous children
            if !type_refs.is_empty() {
                if let Some(parent) = symbols
                    .iter_mut()
                    .rev()
                    .find(|s| s.qualified_name.as_ref() == ctx.prefix)
                {
                    // Skip packages - they shouldn't inherit type_refs from anonymous children
                    if parent.kind != SymbolKind::Package {
                        // Only extend TypedBy refs - feature refs would cause false "undefined reference" errors
                        let typing_refs: Vec<_> = type_refs
                            .iter()
                            .filter(
                                |tr| matches!(tr, TypeRefKind::Simple(r) if r.kind == RefKind::TypedBy),
                            )
                            .cloned()
                            .collect();
                        parent.type_refs.extend(typing_refs);
                    }
                }
            }

            // Generate unique anonymous scope name for children
            // Try to use relationship target for meaningful names, otherwise use generic anon
            let line = usage
                .range
                .map(|r| ctx.line_index.line_col(r.start()).line)
                .unwrap_or(0);

            let anon_scope = usage
                .relationships
                .iter()
                .find(|r| !matches!(r.kind, NormalizedRelKind::Expression))
                .map(|r| {
                    let prefix = match r.kind {
                        NormalizedRelKind::Subsets => ":>",
                        NormalizedRelKind::TypedBy => ":",
                        NormalizedRelKind::Specializes => ":>:",
                        NormalizedRelKind::Redefines => ":>>",
                        NormalizedRelKind::About => "about:",
                        NormalizedRelKind::Performs => "perform:",
                        NormalizedRelKind::Satisfies => "satisfy:",
                        NormalizedRelKind::Exhibits => "exhibit:",
                        NormalizedRelKind::Includes => "include:",
                        NormalizedRelKind::Asserts => "assert:",
                        NormalizedRelKind::Verifies => "verify:",
                        NormalizedRelKind::References => "ref:",
                        NormalizedRelKind::Meta => "meta:",
                        NormalizedRelKind::Crosses => "crosses:",
                        NormalizedRelKind::Expression => "~",
                        NormalizedRelKind::FeatureChain => "chain:",
                        NormalizedRelKind::Conjugates => "~:",
                        // State/Transition
                        NormalizedRelKind::TransitionSource => "from:",
                        NormalizedRelKind::TransitionTarget => "then:",
                        NormalizedRelKind::SuccessionSource => "first:",
                        NormalizedRelKind::SuccessionTarget => "then:",
                        // Message
                        NormalizedRelKind::AcceptedMessage => "accept:",
                        NormalizedRelKind::AcceptVia => "via:",
                        NormalizedRelKind::SentMessage => "send:",
                        NormalizedRelKind::SendVia => "via:",
                        NormalizedRelKind::SendTo => "to:",
                        NormalizedRelKind::MessageSource => "from:",
                        NormalizedRelKind::MessageTarget => "to:",
                        // Requirement/Constraint
                        NormalizedRelKind::Assumes => "assume:",
                        NormalizedRelKind::Requires => "require:",
                        // Allocation/Connection
                        NormalizedRelKind::AllocateSource => "allocate:",
                        NormalizedRelKind::AllocateTo => "to:",
                        NormalizedRelKind::BindSource => "bind:",
                        NormalizedRelKind::BindTarget => "=:",
                        NormalizedRelKind::ConnectSource => "connect:",
                        NormalizedRelKind::ConnectTarget => "to:",
                        NormalizedRelKind::FlowItem => "flow:",
                        NormalizedRelKind::FlowSource => "from:",
                        NormalizedRelKind::FlowTarget => "to:",
                        NormalizedRelKind::InterfaceEnd => "end:",
                        // View
                        NormalizedRelKind::Exposes => "expose:",
                        NormalizedRelKind::Renders => "render:",
                        NormalizedRelKind::Filters => "filter:",
                        // Dependency
                        NormalizedRelKind::DependencySource => "dep:",
                        NormalizedRelKind::DependencyTarget => "to:",
                    };
                    ctx.next_anon_scope(prefix, &r.target.as_str(), line)
                })
                // Fallback: always create a unique scope for anonymous usages with children
                .unwrap_or_else(|| ctx.next_anon_scope("anon", "", line));

            // Create a symbol for the anonymous usage so it can be looked up during resolution
            // This is needed for satisfy/perform/exhibit blocks where children need to resolve
            // redefines in the context of the satisfied/performed/exhibited element
            let qualified_name = ctx.qualified_name(&anon_scope);
            let kind = SymbolKind::from_normalized_usage_kind(usage.kind);
            // For anonymous usages, use the first non-expression relationship's range as the span
            // This ensures hover works on the redefines/subsets target, not the keyword (e.g., "port")
            let anon_span_range = usage
                .relationships
                .iter()
                .find(|r| !matches!(r.kind, NormalizedRelKind::Expression))
                .and_then(|r| r.range)
                .or(usage.range);
            let span = ctx.range_to_info(anon_span_range);

            // Build supertypes for anonymous symbol:
            // 1. From relationships (Redefines, Subsets, TypedBy, Specializes, Satisfies, Verifies)
            // 2. From parent's TypedBy (so we can resolve inherited members)
            // Note: Satisfies/Verifies blocks should inherit from the satisfied/verified requirement
            //       so that nested members can resolve redefines targets in the satisfied element
            let mut anon_supertypes: Vec<Arc<str>> = usage
                .relationships
                .iter()
                .filter(|r| {
                    matches!(
                        r.kind,
                        NormalizedRelKind::TypedBy
                            | NormalizedRelKind::Subsets
                            | NormalizedRelKind::Specializes
                            | NormalizedRelKind::Redefines
                            | NormalizedRelKind::Satisfies
                            | NormalizedRelKind::Verifies
                    )
                })
                .map(|r| Arc::from(r.target.as_str().as_ref()))
                .collect();

            // Add parent's TypedBy types so inherited members are visible
            // This handles cases like: `spatialCF: Type { :>> mRefs }` where mRefs is from Type
            if let Some(parent) = symbols
                .iter()
                .rev()
                .find(|s| s.qualified_name.as_ref() == ctx.prefix)
            {
                for supertype in &parent.supertypes {
                    if !anon_supertypes.contains(supertype) {
                        anon_supertypes.push(supertype.clone());
                    }
                }
            }

            let anon_symbol = HirSymbol {
                file: ctx.file,
                name: Arc::from(anon_scope.as_str()),
                short_name: None,
                qualified_name: Arc::from(qualified_name.as_str()),
                element_id: new_element_id(),
                kind,
                start_line: span.start_line,
                start_col: span.start_col,
                end_line: span.end_line,
                end_col: span.end_col,
                short_name_start_line: None,
                short_name_start_col: None,
                short_name_end_line: None,
                short_name_end_col: None,
                supertypes: anon_supertypes,
                relationships: relationships.clone(),
                type_refs,
                doc: None,
                is_public: false,
                view_data: None,
                metadata_annotations: metadata_annotations.clone(),
                is_abstract: usage.is_abstract,
                is_variation: usage.is_variation,
                is_readonly: usage.is_readonly,
                is_derived: usage.is_derived,
                is_parallel: usage.is_parallel,
                is_individual: usage.is_individual,
                is_end: usage.is_end,
                is_default: usage.is_default,
                is_ordered: usage.is_ordered,
                is_nonunique: usage.is_nonunique,
                is_portion: usage.is_portion,
                direction: usage.direction,
                multiplicity: usage.multiplicity,
            };
            symbols.push(anon_symbol);

            // Push scope for children of anonymous usages
            ctx.push_scope(&anon_scope);

            // Recurse into children for anonymous usages
            for child in &usage.children {
                extract_from_normalized_into_symbols(symbols, ctx, child);
            }

            ctx.pop_scope();
            return;
        }
    };

    let qualified_name = ctx.qualified_name(&name);
    let kind = SymbolKind::from_normalized_usage_kind(usage.kind);
    // Use name_range for precise position, fall back to full range
    let span = ctx.range_to_info(usage.name_range.or(usage.range));
    let (sn_start_line, sn_start_col, sn_end_line, sn_end_col) =
        ctx.range_to_optional(usage.short_name_range);

    // Extract typing and subsetting as supertypes
    // For member resolution, we need to look in:
    // - TypedBy: explicit type annotation (`: Type`)
    // - Subsets: subset relationship (`:>` on usages)
    // - Specializes: specialization (`:>` can also be specializes in some contexts)
    // - Redefines: redefinition (`:>>` on usages) - needed for inherited member lookup
    // - Performs/Exhibits/Includes/etc.: domain-specific relationships that establish type context
    //   e.g., `perform takePicture :> TakePicture` - the performed action defines the type hierarchy
    let mut supertypes: Vec<Arc<str>> = usage
        .relationships
        .iter()
        .filter(|r| {
            matches!(
                r.kind,
                NormalizedRelKind::TypedBy
                    | NormalizedRelKind::Subsets
                    | NormalizedRelKind::Specializes
                    | NormalizedRelKind::Redefines
                    | NormalizedRelKind::Performs
                    | NormalizedRelKind::Exhibits
                    | NormalizedRelKind::Includes
                    | NormalizedRelKind::Satisfies
                    | NormalizedRelKind::Asserts
                    | NormalizedRelKind::Verifies
            )
        })
        .map(|r| Arc::from(r.target.as_str().as_ref()))
        .collect();

    // Detect implicit redefinition: if parent has a type, and that type has a member
    // with the same name as this usage, then this usage implicitly redefines that member.
    // e.g., `action transport : TransportScenario { action trigger { ... } }`
    // Here `transport::trigger` implicitly redefines `TransportScenario::trigger`
    if supertypes.is_empty() && !ctx.prefix.is_empty() {
        // Find the parent symbol
        if let Some(parent) = symbols
            .iter()
            .rev()
            .find(|s| s.qualified_name.as_ref() == ctx.prefix)
        {
            // Check if parent has a type
            if let Some(parent_type) = parent.supertypes.first() {
                // The parent_type might be unqualified (e.g., "TransportScenario")
                // We need to find the fully qualified version
                let parent_type_qualified = symbols
                    .iter()
                    .find(|s| {
                        s.name.as_ref() == parent_type.as_ref()
                            || s.qualified_name.as_ref() == parent_type.as_ref()
                    })
                    .map(|s| s.qualified_name.clone());

                if let Some(type_qname) = parent_type_qualified {
                    // Look for a member in the parent's type with the same name
                    let potential_redef = format!("{}::{}", type_qname, name);
                    if symbols
                        .iter()
                        .any(|s| s.qualified_name.as_ref() == potential_redef)
                    {
                        supertypes.push(Arc::from(potential_redef));
                    }
                }
            }
        }
    }

    // Add implicit supertypes from SysML kernel library if no explicit supertypes present
    // This models the implicit inheritance: part → Parts::Part, item → Items::Item, etc.
    // Only add if no explicit type/specialization (otherwise we rely on that)
    if supertypes.is_empty() {
        if let Some(implicit) = implicit_supertype_for_usage_kind(usage.kind) {
            supertypes.push(Arc::from(implicit));
        }
    }

    // Extract doc comment
    let doc = usage.doc.as_ref().map(|s| Arc::from(s.trim()));

    // Extract view-specific data if this is a view/viewpoint/rendering
    let typed_by = supertypes.first();
    let view_data = extract_view_data_from_usage(usage, usage.kind, typed_by);

    symbols.push(HirSymbol {
        name: Arc::from(name.as_str()),
        short_name: usage.short_name.as_ref().map(|s| Arc::from(s.as_str())),
        qualified_name: Arc::from(qualified_name.as_str()),
        element_id: new_element_id(),
        kind,
        file: ctx.file,
        start_line: span.start_line,
        start_col: span.start_col,
        end_line: span.end_line,
        end_col: span.end_col,
        short_name_start_line: sn_start_line,
        short_name_start_col: sn_start_col,
        short_name_end_line: sn_end_line,
        short_name_end_col: sn_end_col,
        doc,
        supertypes,
        relationships,
        type_refs,
        is_public: false,
        view_data,
        metadata_annotations,
        is_abstract: usage.is_abstract,
        is_variation: usage.is_variation,
        is_readonly: usage.is_readonly,
        is_derived: usage.is_derived,
        is_parallel: usage.is_parallel,
        is_individual: usage.is_individual,
        is_end: usage.is_end,
        is_default: usage.is_default,
        is_ordered: usage.is_ordered,
        is_nonunique: usage.is_nonunique,
        is_portion: usage.is_portion,
        direction: usage.direction,
        multiplicity: usage.multiplicity,
    });

    // Recurse into children
    ctx.push_scope(&name);
    for child in &usage.children {
        extract_from_normalized_into_symbols(symbols, ctx, child);
    }
    ctx.pop_scope();
}

fn extract_from_normalized_import(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    import: &NormalizedImport,
) {
    let path = &import.path;
    let qualified_name = ctx.qualified_name(&format!("import:{}", path));

    // Use path_range for the symbol span since name is the path.
    // Fall back to full range if path_range is not available.
    let span = import
        .path_range
        .map(|r| ctx.range_to_info(Some(r)))
        .unwrap_or_else(|| ctx.range_to_info(import.range));

    // Create type_ref for the import target so hover/go-to-def works on it
    // Strip ::* or ::** suffix to get the actual package name
    let target_path = path
        .strip_suffix("::**")
        .or_else(|| path.strip_suffix("::*"))
        .unwrap_or(path);

    let type_refs = if let Some(r) = import.path_range {
        let start = ctx.line_index.line_col(r.start());
        let end = ctx.line_index.line_col(r.end());
        vec![TypeRefKind::Simple(TypeRef {
            target: Arc::from(target_path),
            resolved_target: None,
            kind: RefKind::Other, // Import targets are special
            start_line: start.line,
            start_col: start.col,
            end_line: end.line,
            end_col: end.col,
        })]
    } else {
        Vec::new()
    };

    symbols.push(HirSymbol {
        name: Arc::from(path.as_str()),
        short_name: None, // Imports don't have short names
        qualified_name: Arc::from(qualified_name.as_str()),
        element_id: new_element_id(),
        kind: SymbolKind::Import,
        file: ctx.file,
        start_line: span.start_line,
        start_col: span.start_col,
        end_line: span.end_line,
        end_col: span.end_col,
        short_name_start_line: None,
        short_name_start_col: None,
        short_name_end_line: None,
        short_name_end_col: None,
        doc: None,
        supertypes: Vec::new(),
        relationships: Vec::new(),
        type_refs,
        is_public: import.is_public,
        view_data: None,
        metadata_annotations: Vec::new(), // Imports don't have metadata
        is_abstract: false,
        is_variation: false,
        is_readonly: false,
        is_derived: false,
        is_parallel: false,
        is_individual: false,
        is_end: false,
        is_default: false,
        is_ordered: false,
        is_nonunique: false,
        is_portion: false,
        direction: None,
        multiplicity: None,
    });
}

fn extract_from_normalized_alias(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    alias: &NormalizedAlias,
) {
    let name = match &alias.name {
        Some(n) => strip_quotes(n),
        None => return,
    };

    let qualified_name = ctx.qualified_name(&name);
    // Use name_range for precise position, fall back to full range
    let span = ctx.range_to_info(alias.name_range.or(alias.range));

    // Create type_ref for the alias target so hover works on it
    let type_refs = if let Some(r) = alias.target_range {
        let start = ctx.line_index.line_col(r.start());
        let end = ctx.line_index.line_col(r.end());
        vec![TypeRefKind::Simple(TypeRef {
            target: Arc::from(alias.target.as_str()),
            resolved_target: None,
            kind: RefKind::Other, // Alias targets are special
            start_line: start.line,
            start_col: start.col,
            end_line: end.line,
            end_col: end.col,
        })]
    } else {
        Vec::new()
    };

    symbols.push(HirSymbol {
        name: Arc::from(name.as_str()),
        short_name: alias.short_name.as_ref().map(|s| Arc::from(s.as_str())),
        qualified_name: Arc::from(qualified_name.as_str()),
        element_id: new_element_id(),
        kind: SymbolKind::Alias,
        file: ctx.file,
        start_line: span.start_line,
        start_col: span.start_col,
        end_line: span.end_line,
        end_col: span.end_col,
        short_name_start_line: None, // Aliases don't have tracked short_name_span
        short_name_start_col: None,
        short_name_end_line: None,
        short_name_end_col: None,
        doc: None,
        supertypes: vec![Arc::from(alias.target.as_str())],
        relationships: Vec::new(),
        type_refs,
        is_public: false,
        view_data: None,
        metadata_annotations: Vec::new(), // Aliases don't have metadata
        is_abstract: false,
        is_variation: false,
        is_readonly: false,
        is_derived: false,
        is_parallel: false,
        is_individual: false,
        is_end: false,
        is_default: false,
        is_ordered: false,
        is_nonunique: false,
        is_portion: false,
        direction: None,
        multiplicity: None,
    });
}

fn extract_from_normalized_comment(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    comment: &NormalizedComment,
) {
    // Extract type_refs from about references
    let type_refs = extract_type_refs_from_normalized(&comment.about, &ctx.line_index);

    let (name, is_anonymous) = match &comment.name {
        Some(n) => (strip_quotes(n), false),
        None => {
            // Anonymous comment - if it has about refs, we need to track them
            // Create an internal symbol to hold the type_refs for hover/goto
            if type_refs.is_empty() {
                return; // Nothing to track
            }
            // Use a synthetic name based on the range
            let anon_name = if let Some(r) = comment.range {
                let pos = ctx.line_index.line_col(r.start());
                format!("<anonymous_comment_{}_{}>", pos.line, pos.col)
            } else {
                "<anonymous_comment>".to_string()
            };
            (anon_name, true)
        }
    };

    let qualified_name = ctx.qualified_name(&name);
    let span = ctx.range_to_info(comment.range);

    symbols.push(HirSymbol {
        name: Arc::from(name.as_str()),
        short_name: comment.short_name.as_ref().map(|s| Arc::from(s.as_str())),
        qualified_name: Arc::from(qualified_name.as_str()),
        element_id: new_element_id(),
        kind: SymbolKind::Comment,
        file: ctx.file,
        start_line: span.start_line,
        start_col: span.start_col,
        end_line: span.end_line,
        end_col: span.end_col,
        short_name_start_line: None, // Comments don't have tracked short_name_span
        short_name_start_col: None,
        short_name_end_line: None,
        short_name_end_col: None,
        doc: if is_anonymous {
            None
        } else {
            Some(Arc::from(comment.content.as_str()))
        },
        supertypes: Vec::new(),
        relationships: Vec::new(),
        type_refs,
        is_public: false,
        view_data: None,
        metadata_annotations: Vec::new(), // Comments don't have metadata
        is_abstract: false,
        is_variation: false,
        is_readonly: false,
        is_derived: false,
        is_parallel: false,
        is_individual: false,
        is_end: false,
        is_default: false,
        is_ordered: false,
        is_nonunique: false,
        is_portion: false,
        direction: None,
        multiplicity: None,
    });
}

/// Extract type references from normalized relationships.
///
/// Chains are now preserved explicitly from the normalized layer.
/// Each TypeRef now includes its RefKind so callers can distinguish
/// type references from feature references.
fn extract_type_refs_from_normalized(
    relationships: &[NormalizedRelationship],
    line_index: &crate::base::LineIndex,
) -> Vec<TypeRefKind> {
    use crate::syntax::normalized::RelTarget;

    let mut type_refs = Vec::new();

    for rel in relationships.iter() {
        let ref_kind = RefKind::from_normalized(rel.kind);

        match &rel.target {
            RelTarget::Chain(chain) => {
                // Emit as a TypeRefChain with individual parts
                let num_parts = chain.parts.len();
                let parts: Vec<TypeRef> = chain
                    .parts
                    .iter()
                    .enumerate()
                    .map(|(idx, part)| {
                        let (start_line, start_col, end_line, end_col) = if let Some(r) = part.range
                        {
                            let start = line_index.line_col(r.start());
                            let end = line_index.line_col(r.end());
                            (start.line, start.col, end.line, end.col)
                        } else if idx == num_parts - 1 {
                            // For the last part, fallback to relationship range if available
                            if let Some(r) = rel.range {
                                let start = line_index.line_col(r.start());
                                let end = line_index.line_col(r.end());
                                (start.line, start.col, end.line, end.col)
                            } else {
                                (0, 0, 0, 0)
                            }
                        } else {
                            // Non-last parts without ranges are synthetic (not hoverable)
                            (0, 0, 0, 0)
                        };
                        TypeRef {
                            target: Arc::from(part.name.as_str()),
                            resolved_target: None,
                            kind: ref_kind,
                            start_line,
                            start_col,
                            end_line,
                            end_col,
                        }
                    })
                    .collect();

                if !parts.is_empty() {
                    type_refs.push(TypeRefKind::Chain(TypeRefChain { parts }));
                }
            }
            RelTarget::Simple(target) => {
                if let Some(r) = rel.range {
                    let start = line_index.line_col(r.start());
                    let end = line_index.line_col(r.end());
                    type_refs.push(TypeRefKind::Simple(TypeRef {
                        target: Arc::from(target.as_str()),
                        resolved_target: None,
                        kind: ref_kind,
                        start_line: start.line,
                        start_col: start.col,
                        end_line: end.line,
                        end_col: end.col,
                    }));

                    // Also add prefix segments as references (e.g., Vehicle::speed -> Vehicle)
                    let parts: Vec<&str> = target.split("::").collect();
                    if parts.len() > 1 {
                        let mut prefix = String::new();
                        for (i, part) in parts.iter().enumerate() {
                            if i == parts.len() - 1 {
                                break;
                            }
                            if !prefix.is_empty() {
                                prefix.push_str("::");
                            }
                            prefix.push_str(part);

                            type_refs.push(TypeRefKind::Simple(TypeRef {
                                target: Arc::from(prefix.as_str()),
                                resolved_target: None,
                                kind: ref_kind,
                                start_line: start.line,
                                start_col: start.col,
                                end_line: end.line,
                                end_col: end.col,
                            }));
                        }
                    }
                }
            }
        }
    }

    type_refs
}

/// Extract symbols from a normalized dependency.
fn extract_from_normalized_dependency(
    symbols: &mut Vec<HirSymbol>,
    ctx: &mut ExtractionContext,
    dep: &NormalizedDependency,
) {
    // Collect type refs from sources, targets, and relationships (including prefix metadata)
    let mut type_refs = extract_type_refs_from_normalized(&dep.sources, &ctx.line_index);
    type_refs.extend(extract_type_refs_from_normalized(
        &dep.targets,
        &ctx.line_index,
    ));
    type_refs.extend(extract_type_refs_from_normalized(
        &dep.relationships,
        &ctx.line_index,
    ));

    // If dependency has a name, create a symbol for it
    if let Some(name) = &dep.name {
        let qualified_name = ctx.qualified_name(name);
        let span = ctx.range_to_info(dep.range);

        symbols.push(HirSymbol {
            name: Arc::from(name.as_str()),
            short_name: dep.short_name.as_ref().map(|s| Arc::from(s.as_str())),
            qualified_name: Arc::from(qualified_name.as_str()),
            element_id: new_element_id(),
            kind: SymbolKind::Dependency,
            file: ctx.file,
            start_line: span.start_line,
            start_col: span.start_col,
            end_line: span.end_line,
            end_col: span.end_col,
            short_name_start_line: None,
            short_name_start_col: None,
            short_name_end_line: None,
            short_name_end_col: None,
            doc: None,
            supertypes: Vec::new(),
            relationships: Vec::new(),
            type_refs,
            is_public: false,
            view_data: None,
            metadata_annotations: Vec::new(),
            is_abstract: false,
            is_variation: false,
            is_readonly: false,
            is_derived: false,
            is_parallel: false,
            is_individual: false,
            is_end: false,
            is_default: false,
            is_ordered: false,
            is_nonunique: false,
            is_portion: false,
            direction: None,
            multiplicity: None,
        });
    } else if !type_refs.is_empty() {
        // Anonymous dependency - attach type refs to parent or create anonymous symbol
        // For now, create an anonymous symbol so refs are tracked
        let span = ctx.range_to_info(dep.range);

        symbols.push(HirSymbol {
            name: Arc::from("<anonymous-dependency>"),
            short_name: None,
            qualified_name: Arc::from(format!("{}::<anonymous-dependency>", ctx.prefix)),
            element_id: new_element_id(),
            kind: SymbolKind::Dependency,
            file: ctx.file,
            start_line: span.start_line,
            start_col: span.start_col,
            end_line: span.end_line,
            end_col: span.end_col,
            short_name_start_line: None,
            short_name_start_col: None,
            short_name_end_line: None,
            short_name_end_col: None,
            doc: None,
            supertypes: Vec::new(),
            relationships: Vec::new(),
            type_refs,
            is_public: false,
            view_data: None,
            metadata_annotations: Vec::new(),
            is_abstract: false,
            is_variation: false,
            is_readonly: false,
            is_derived: false,
            is_parallel: false,
            is_individual: false,
            is_end: false,
            is_default: false,
            is_ordered: false,
            is_nonunique: false,
            is_portion: false,
            direction: None,
            multiplicity: None,
        });
    }
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

/// Span information extracted from an AST node.
#[derive(Clone, Copy, Debug, Default)]
struct SpanInfo {
    start_line: u32,
    start_col: u32,
    end_line: u32,
    end_col: u32,
}

/// Strip single quotes from a string.
fn strip_quotes(s: &str) -> String {
    if s.starts_with('\'') && s.ends_with('\'') && s.len() >= 2 {
        s[1..s.len() - 1].to_string()
    } else {
        s.to_string()
    }
}

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

    #[test]
    fn test_symbol_kind_display() {
        assert_eq!(SymbolKind::PartDefinition.display(), "Part def");
        assert_eq!(SymbolKind::PartUsage.display(), "Part");
    }

    #[test]
    fn test_strip_quotes() {
        assert_eq!(strip_quotes("'hello'"), "hello");
        assert_eq!(strip_quotes("hello"), "hello");
        assert_eq!(strip_quotes("'"), "'");
    }

    #[test]
    fn test_extraction_context() {
        let mut ctx = ExtractionContext {
            file: FileId::new(0),
            prefix: String::new(),
            anon_counter: 0,
            scope_stack: Vec::new(),
            line_index: crate::base::LineIndex::new(""),
        };

        assert_eq!(ctx.qualified_name("Foo"), "Foo");

        ctx.push_scope("Outer");
        assert_eq!(ctx.qualified_name("Inner"), "Outer::Inner");

        ctx.push_scope("Deep");
        assert_eq!(ctx.qualified_name("Leaf"), "Outer::Deep::Leaf");

        ctx.pop_scope();
        assert_eq!(ctx.qualified_name("Sibling"), "Outer::Sibling");

        ctx.pop_scope();
        assert_eq!(ctx.qualified_name("Root"), "Root");
    }

    #[test]
    fn test_direction_and_multiplicity_extraction() {
        use crate::base::FileId;
        use crate::syntax::parser::parse_content;

        let source = r#"part def Vehicle {
            in port fuelIn : FuelType[1];
            out port exhaust : GasType[0..*];
            inout port control : ControlType[1..5];
            part wheels[4];
        }"#;

        let syntax = parse_content(source, std::path::Path::new("test.sysml")).unwrap();
        let symbols = super::extract_symbols_unified(FileId::new(0), &syntax);

        // Find the ports and verify direction
        let fuel_in = symbols
            .iter()
            .find(|s| s.name.as_ref() == "fuelIn")
            .unwrap();
        assert_eq!(fuel_in.direction, Some(Direction::In));
        assert_eq!(
            fuel_in.multiplicity,
            Some(Multiplicity {
                lower: Some(1),
                upper: Some(1)
            })
        );

        let exhaust = symbols
            .iter()
            .find(|s| s.name.as_ref() == "exhaust")
            .unwrap();
        assert_eq!(exhaust.direction, Some(Direction::Out));
        assert_eq!(
            exhaust.multiplicity,
            Some(Multiplicity {
                lower: Some(0),
                upper: None
            })
        );

        let control = symbols
            .iter()
            .find(|s| s.name.as_ref() == "control")
            .unwrap();
        assert_eq!(control.direction, Some(Direction::InOut));
        assert_eq!(
            control.multiplicity,
            Some(Multiplicity {
                lower: Some(1),
                upper: Some(5)
            })
        );

        let wheels = symbols
            .iter()
            .find(|s| s.name.as_ref() == "wheels")
            .unwrap();
        assert_eq!(wheels.direction, None);
        assert_eq!(
            wheels.multiplicity,
            Some(Multiplicity {
                lower: Some(4),
                upper: Some(4)
            })
        );
    }
}

#[cfg(test)]
mod test_package_span {
    use super::*;
    use crate::base::FileId;
    use crate::syntax::parser::parse_content;

    #[test]
    fn test_hir_simple_package_span() {
        let source = "package SimpleVehicleModel { }";
        let syntax = parse_content(source, std::path::Path::new("test.sysml")).unwrap();

        let symbols = extract_symbols_unified(FileId(1), &syntax);

        let pkg_sym = symbols
            .iter()
            .find(|s| s.name.as_ref() == "SimpleVehicleModel")
            .unwrap();

        println!(
            "Package symbol: name='{}' start=({},{}), end=({},{})",
            pkg_sym.name, pkg_sym.start_line, pkg_sym.start_col, pkg_sym.end_line, pkg_sym.end_col
        );

        // The name "SimpleVehicleModel" starts at column 8 (after "package ")
        assert_eq!(pkg_sym.start_col, 8, "start_col should be 8");
        assert_eq!(pkg_sym.end_col, 26, "end_col should be 26");
    }

    #[test]
    fn test_hir_nested_package_span() {
        // Match the structure of VehicleIndividuals.sysml
        let source = r#"package VehicleIndividuals {
	package IndividualDefinitions {
	}
}"#;
        let syntax = parse_content(source, std::path::Path::new("test.sysml")).unwrap();

        let symbols = extract_symbols_unified(FileId(1), &syntax);

        for sym in &symbols {
            println!(
                "Symbol: name='{}' kind={:?} start=({},{}), end=({},{})",
                sym.name, sym.kind, sym.start_line, sym.start_col, sym.end_line, sym.end_col
            );
        }

        // Top-level package: "VehicleIndividuals" starts at column 8
        let outer = symbols
            .iter()
            .find(|s| s.name.as_ref() == "VehicleIndividuals")
            .unwrap();
        assert_eq!(outer.start_col, 8, "outer start_col should be 8");
        assert_eq!(
            outer.end_col, 26,
            "outer end_col should be 26 (8 + 18 = 26)"
        );

        // Nested package: "IndividualDefinitions" on line 2, with a tab prefix
        // "package IndividualDefinitions" - tab is 1 char, "package " is 8 chars = 9
        let nested = symbols
            .iter()
            .find(|s| s.name.as_ref() == "IndividualDefinitions")
            .unwrap();
        println!(
            "Nested package: start_col={}, end_col={}",
            nested.start_col, nested.end_col
        );
        // After tab (1) and "package " (8) = 9
        assert_eq!(nested.start_col, 9, "nested start_col should be 9");
        // "IndividualDefinitions" is 21 chars, so 9 + 21 = 30
        assert_eq!(nested.end_col, 30, "nested end_col should be 30");
    }
}

/// Extract view-specific data from a normalized definition if it's a view/viewpoint/rendering.
fn extract_view_data_from_definition(
    def: &NormalizedDefinition,
    kind: NormalizedDefKind,
) -> Option<crate::hir::views::ViewData> {
    use crate::hir::views::{
        ExposeRelationship, FilterCondition, ViewData, ViewDefinition, WildcardKind,
    };

    // Check if this is a view-related definition
    match kind {
        NormalizedDefKind::View => {
            let mut view_def = ViewDefinition::new();

            // Extract expose relationships and filters from children
            for child in &def.children {
                match child {
                    NormalizedElement::Expose(expose) => {
                        let wildcard = if expose.is_recursive {
                            WildcardKind::Recursive
                        } else if expose.import_path.ends_with("::*") {
                            WildcardKind::Direct
                        } else {
                            WildcardKind::None
                        };

                        let expose_rel = ExposeRelationship::new(
                            Arc::from(expose.import_path.as_str()),
                            wildcard,
                        );
                        view_def.add_expose(expose_rel);
                    }
                    NormalizedElement::Filter(filter) => {
                        // Extract metadata filters
                        for meta_ref in &filter.metadata_refs {
                            let filter_cond =
                                FilterCondition::metadata(Arc::from(meta_ref.as_str()));
                            view_def.add_filter(filter_cond);
                        }
                    }
                    _ => {} // Other children are normal nested elements
                }
            }

            Some(ViewData::ViewDefinition(view_def))
        }
        NormalizedDefKind::Viewpoint => {
            // TODO: Extract stakeholders and concerns from children
            // Viewpoints contain requirement usages that specify stakeholders
            Some(ViewData::ViewpointDefinition(
                crate::hir::views::ViewpointDefinition {
                    stakeholders: Vec::new(),
                    concerns: Vec::new(),
                    span: None, // TODO: Convert TextRange to Span
                },
            ))
        }
        NormalizedDefKind::Rendering => {
            // TODO: Extract layout algorithm from metadata or properties
            Some(ViewData::RenderingDefinition(
                crate::hir::views::RenderingDefinition {
                    layout: None,
                    span: None, // TODO: Convert TextRange to Span
                },
            ))
        }
        _ => None,
    }
}

/// Extract view-specific data from a normalized usage if it's a view/viewpoint/rendering.
fn extract_view_data_from_usage(
    _usage: &NormalizedUsage,
    _kind: NormalizedUsageKind,
    _typed_by: Option<&Arc<str>>,
) -> Option<crate::hir::views::ViewData> {
    use crate::hir::views::{ViewData, ViewUsage};

    // Check if this is a view-related usage
    match _kind {
        NormalizedUsageKind::View => {
            // TODO Phase 2: Extract expose/filter/render from usage body
            // View usages can have:
            // 1. Expose relationships to specify which elements to show
            // 2. Filter conditions to refine what's shown
            // 3. Rendering specifications to override the view definition
            //
            // Currently creates empty ViewUsage as placeholder
            Some(ViewData::ViewUsage(ViewUsage::new(_typed_by.cloned())))
        }
        NormalizedUsageKind::Viewpoint => Some(ViewData::ViewpointUsage(
            crate::hir::views::ViewpointUsage {
                viewpoint_def: _typed_by.cloned(),
                span: None, // TODO: Convert TextRange to Span
            },
        )),
        NormalizedUsageKind::Rendering => Some(ViewData::RenderingUsage(
            crate::hir::views::RenderingUsage {
                rendering_def: _typed_by.cloned(),
                span: None, // TODO: Convert TextRange to Span
            },
        )),
        _ => None,
    }
}