syster-base 0.3.3-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
//! Typed AST wrappers over the untyped rowan CST.
//!
//! This module provides strongly-typed accessors for SysML syntax nodes.
//! Each struct wraps a SyntaxNode and provides methods to access children.

use super::syntax_kind::SyntaxKind;
use super::{SyntaxNode, SyntaxToken};

// ============================================================================
// Helper utilities for reducing code duplication
// ============================================================================

/// Check if a token kind is an identifier or contextual keyword that can be used as a name.
#[inline]
fn is_name_token(kind: SyntaxKind) -> bool {
    matches!(
        kind,
        SyntaxKind::IDENT
            | SyntaxKind::START_KW
            | SyntaxKind::END_KW
            | SyntaxKind::DONE_KW
            | SyntaxKind::THIS_KW
    )
}

/// Strip surrounding single quotes from unrestricted names like `'My Name'`.
#[inline]
fn strip_unrestricted_name(text: &str) -> String {
    if text.starts_with('\'') && text.ends_with('\'') && text.len() > 1 {
        text[1..text.len() - 1].to_string()
    } else {
        text.to_string()
    }
}

/// Check if a syntax node has a direct child token of the specified kind.
///
/// This is a common pattern used throughout the AST to check for modifier keywords
/// like `abstract`, `ref`, `readonly`, etc.
///
/// # Example
/// ```ignore
/// // Instead of:
/// self.0.children_with_tokens()
///     .filter_map(|e| e.into_token())
///     .any(|t| t.kind() == SyntaxKind::ABSTRACT_KW)
///
/// // Use:
/// has_token(&self.0, SyntaxKind::ABSTRACT_KW)
/// ```
#[inline]
fn has_token(node: &SyntaxNode, kind: SyntaxKind) -> bool {
    node.children_with_tokens()
        .filter_map(|e| e.into_token())
        .any(|t| t.kind() == kind)
}

/// Find the first token that can be used as a name (identifier or contextual keyword).
#[inline]
fn find_name_token(node: &SyntaxNode) -> Option<SyntaxToken> {
    node.children_with_tokens()
        .filter_map(|e| e.into_token())
        .find(|t| is_name_token(t.kind()))
}

/// Macro to generate boolean property methods that check for a specific token kind.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     has_token_method!(is_abstract, ABSTRACT_KW, "abstract part def P {}");
///     has_token_method!(is_ref, REF_KW, "ref part p;");
/// }
/// ```
macro_rules! has_token_method {
    ($name:ident, $kind:ident) => {
        #[doc = concat!("Check if this node has the `", stringify!($kind), "` token.")]
        pub fn $name(&self) -> bool {
            has_token(&self.0, SyntaxKind::$kind)
        }
    };
    ($name:ident, $kind:ident, $example:literal) => {
        #[doc = concat!("Check if this node has the `", stringify!($kind), "` token (e.g., `", $example, "`).")]
        pub fn $name(&self) -> bool {
            has_token(&self.0, SyntaxKind::$kind)
        }
    };
}

/// Macro to generate a method that finds the first child of a specific AST type.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     first_child_method!(name, Name);
///     first_child_method!(body, NamespaceBody);
/// }
/// ```
macro_rules! first_child_method {
    ($name:ident, $type:ident) => {
        #[doc = concat!("Get the first `", stringify!($type), "` child of this node.")]
        pub fn $name(&self) -> Option<$type> {
            self.0.children().find_map($type::cast)
        }
    };
}

/// Macro to generate a method that returns an iterator over children of a specific AST type.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     children_method!(specializations, Specialization);
///     children_method!(members, NamespaceMember);
/// }
/// ```
macro_rules! children_method {
    ($name:ident, $type:ident) => {
        #[doc = concat!("Get all `", stringify!($type), "` children of this node.")]
        pub fn $name(&self) -> impl Iterator<Item = $type> + '_ {
            self.0.children().filter_map($type::cast)
        }
    };
}

/// Macro to generate a method that returns a Vec of children of a specific AST type.
///
/// Use this when the result needs to be collected (e.g., for iteration after borrowing ends).
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     children_vec_method!(targets, QualifiedName);
/// }
/// ```
macro_rules! children_vec_method {
    ($name:ident, $type:ident) => {
        #[doc = concat!("Get all `", stringify!($type), "` children of this node as a Vec.")]
        pub fn $name(&self) -> Vec<$type> {
            self.0.children().filter_map($type::cast).collect()
        }
    };
}

/// Macro to generate a method that returns an iterator over descendants of a specific AST type.
///
/// Unlike `children_method!`, this traverses the entire subtree, not just direct children.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     descendants_method!(expressions, Expression);
/// }
/// ```
macro_rules! descendants_method {
    ($name:ident, $type:ident) => {
        #[doc = concat!("Get all `", stringify!($type), "` descendants of this node.")]
        pub fn $name(&self) -> impl Iterator<Item = $type> + '_ {
            self.0.descendants().filter_map($type::cast)
        }
    };
    ($name:ident, $type:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(&self) -> impl Iterator<Item = $type> + '_ {
            self.0.descendants().filter_map($type::cast)
        }
    };
}

/// Macro to generate a method that gets the first child node of a type after a specific keyword.
///
/// This is a common pattern for things like `via port` or `by target` clauses.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     child_after_keyword_method!(via, QualifiedName, VIA_KW, "get the 'via' target port");
///     child_after_keyword_method!(by_target, QualifiedName, BY_KW, "get the 'by' target");
/// }
/// ```
macro_rules! child_after_keyword_method {
    ($name:ident, $type:ident, $keyword:ident, $doc:literal) => {
        #[doc = $doc]
        pub fn $name(&self) -> Option<$type> {
            let mut seen_keyword = false;
            for child in self.0.children_with_tokens() {
                match child {
                    rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::$keyword => {
                        seen_keyword = true;
                    }
                    rowan::NodeOrToken::Node(n) if seen_keyword => {
                        if let Some(result) = $type::cast(n) {
                            return Some(result);
                        }
                    }
                    _ => {}
                }
            }
            None
        }
    };
}

/// Macro to generate `members()` method that delegates to `body().members()`.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     body_members_method!();
/// }
/// ```
macro_rules! body_members_method {
    () => {
        /// Get members from the body.
        pub fn members(&self) -> impl Iterator<Item = NamespaceMember> + '_ {
            self.body()
                .into_iter()
                .flat_map(|body| body.members().collect::<Vec<_>>())
        }
    };
}

/// Macro to generate a method that finds the first matching token from a set of kinds.
///
/// Returns `Option<SyntaxKind>` of the matched token.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     find_token_kind_method!(kind, [ENTRY_KW, DO_KW, EXIT_KW], "Get the subaction kind.");
/// }
/// ```
macro_rules! find_token_kind_method {
    ($name:ident, [$($kind:ident),+ $(,)?], $doc:literal) => {
        #[doc = $doc]
        pub fn $name(&self) -> Option<SyntaxKind> {
            self.0
                .children_with_tokens()
                .filter_map(|e| e.into_token())
                .find(|t| matches!(t.kind(), $(SyntaxKind::$kind)|+))
                .map(|t| t.kind())
        }
    };
}

/// Macro to generate source/target pair methods from an iterator method.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     children_method!(items, Item);
///     source_target_pair!(source, target, items, Item);
/// }
/// ```
macro_rules! source_target_pair {
    ($source:ident, $target:ident, $iter_method:ident, $type:ident) => {
        #[doc = concat!("Get the first `", stringify!($type), "` (source).")]
        pub fn $source(&self) -> Option<$type> {
            self.$iter_method().next()
        }

        #[doc = concat!("Get the second `", stringify!($type), "` (target).")]
        pub fn $target(&self) -> Option<$type> {
            self.$iter_method().nth(1)
        }
    };
}

/// Macro to generate a method that maps token kinds to enum variants.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     token_to_enum_method!(direction, Direction, [
///         IN_KW => In,
///         OUT_KW => Out,
///         INOUT_KW => InOut,
///     ]);
/// }
/// ```
macro_rules! token_to_enum_method {
    ($name:ident, $enum_type:ident, [$($token:ident => $variant:ident),+ $(,)?]) => {
        pub fn $name(&self) -> Option<$enum_type> {
            for token in self.0.children_with_tokens().filter_map(|e| e.into_token()) {
                match token.kind() {
                    $(SyntaxKind::$token => return Some($enum_type::$variant),)+
                    _ => {}
                }
            }
            None
        }
    };
}

/// Macro to generate `prefix_metadata()` method that collects metadata from preceding siblings.
///
/// Usage:
/// ```ignore
/// impl MyStruct {
///     prefix_metadata_method!();
/// }
/// ```
macro_rules! prefix_metadata_method {
    () => {
        /// Get prefix metadata references from preceding siblings.
        pub fn prefix_metadata(&self) -> Vec<PrefixMetadata> {
            collect_prefix_metadata(&self.0)
        }
    };
}

/// Helper to collect prefix metadata from preceding siblings.
///
/// PREFIX_METADATA nodes precede definitions/usages in the source.
fn collect_prefix_metadata(node: &SyntaxNode) -> Vec<PrefixMetadata> {
    let mut result = Vec::new();
    let mut current = node.prev_sibling();
    while let Some(sibling) = current {
        if sibling.kind() == SyntaxKind::PREFIX_METADATA {
            if let Some(pm) = PrefixMetadata::cast(sibling.clone()) {
                result.push(pm);
            }
            current = sibling.prev_sibling();
        } else {
            break;
        }
    }
    result.reverse();
    result
}

/// Split children of a node at a keyword token.
///
/// Returns `(before, after)` where:
/// - `before` contains all nodes of type `T` before the keyword
/// - `after` contains all nodes of type `T` after the keyword
fn split_at_keyword<T: AstNode>(node: &SyntaxNode, keyword: SyntaxKind) -> (Vec<T>, Vec<T>) {
    let mut before = Vec::new();
    let mut after = Vec::new();
    let mut found_keyword = false;

    for elem in node.children_with_tokens() {
        if let Some(token) = elem.as_token() {
            if token.kind() == keyword {
                found_keyword = true;
            }
        } else if let Some(child) = elem.as_node() {
            if let Some(item) = T::cast(child.clone()) {
                if found_keyword {
                    after.push(item);
                } else {
                    before.push(item);
                }
            }
        }
    }
    (before, after)
}

/// Trait for AST nodes that wrap a SyntaxNode
pub trait AstNode: Sized {
    fn can_cast(kind: SyntaxKind) -> bool;
    fn cast(node: SyntaxNode) -> Option<Self>;
    fn syntax(&self) -> &SyntaxNode;

    /// Find all descendant nodes of a specific AST type
    fn descendants<T: AstNode>(&self) -> impl Iterator<Item = T> {
        self.syntax().descendants().filter_map(T::cast)
    }

    /// Extract doc comment preceding this node.
    /// Looks for block comments (`/* ... */`) or consecutive line comments (`// ...`)
    /// immediately preceding the node (separated only by whitespace).
    fn doc_comment(&self) -> Option<String> {
        extract_doc_comment(self.syntax())
    }
}

/// Extract doc comment from preceding trivia or COMMENT_ELEMENT of a syntax node.
///
/// SysML supports two forms of documentation:
/// 1. `doc /* content */` - formal SysML documentation (COMMENT_ELEMENT nodes)
/// 2. Regular comments `/* ... */` or `// ...` - informal doc comments (trivia)
pub fn extract_doc_comment(node: &SyntaxNode) -> Option<String> {
    let mut comments = Vec::new();
    let mut current = node.prev_sibling_or_token();

    while let Some(node_or_token) = current {
        match node_or_token {
            rowan::NodeOrToken::Token(ref t) => {
                match t.kind() {
                    SyntaxKind::WHITESPACE => {
                        // Allow whitespace, continue looking
                        current = t.prev_sibling_or_token();
                    }
                    SyntaxKind::BLOCK_COMMENT => {
                        // Block comment - use as doc
                        let text = t.text();
                        // Strip /* and */ and trim
                        let content = text
                            .strip_prefix("/*")
                            .and_then(|s| s.strip_suffix("*/"))
                            .map(clean_doc_comment)
                            .unwrap_or_default();
                        if !content.is_empty() {
                            comments.push(content);
                        }
                        // Block comment found, stop looking
                        break;
                    }
                    SyntaxKind::LINE_COMMENT => {
                        // Line comment - collect consecutive ones
                        let text = t.text();
                        // Strip // and trim
                        let content = text.strip_prefix("//").unwrap_or(text).trim();
                        if !content.is_empty() {
                            comments.push(content.to_string());
                        }
                        current = t.prev_sibling_or_token();
                    }
                    _ => break, // Any other token stops the search
                }
            }
            rowan::NodeOrToken::Node(ref n) => {
                // Check for COMMENT_ELEMENT (SysML `doc /* ... */` syntax)
                if n.kind() == SyntaxKind::COMMENT_ELEMENT {
                    // Extract the content from the COMMENT_ELEMENT
                    // The structure is: doc /* content */
                    // We need to find the BLOCK_COMMENT token inside
                    for child in n.children_with_tokens() {
                        if let rowan::NodeOrToken::Token(t) = child {
                            if t.kind() == SyntaxKind::BLOCK_COMMENT {
                                let text = t.text();
                                let content = text
                                    .strip_prefix("/*")
                                    .and_then(|s| s.strip_suffix("*/"))
                                    .map(clean_doc_comment)
                                    .unwrap_or_default();
                                if !content.is_empty() {
                                    comments.push(content);
                                }
                                break;
                            }
                        }
                    }
                    // Found doc element, stop looking
                    break;
                } else {
                    // Another node that's not a comment stops the search
                    break;
                }
            }
        }
    }

    if comments.is_empty() {
        return None;
    }

    // Reverse because we collected bottom-up
    comments.reverse();
    Some(comments.join("\n"))
}

/// Clean up doc comment content by removing leading asterisks and normalizing whitespace.
fn clean_doc_comment(s: &str) -> String {
    s.lines()
        .map(|line| {
            let trimmed = line.trim();
            // Remove leading * from doc comment lines
            if let Some(rest) = trimmed.strip_prefix('*') {
                rest.trim_start().to_string()
            } else {
                trimmed.to_string()
            }
        })
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Trait for AST tokens that wrap a SyntaxToken
pub trait AstToken: Sized {
    fn can_cast(kind: SyntaxKind) -> bool;
    fn cast(token: SyntaxToken) -> Option<Self>;
    fn syntax(&self) -> &SyntaxToken;
    fn text(&self) -> &str {
        self.syntax().text()
    }
}

// ============================================================================
// Helper macros
// ============================================================================

macro_rules! ast_node {
    ($name:ident, $kind:ident) => {
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub struct $name(SyntaxNode);

        impl AstNode for $name {
            fn can_cast(kind: SyntaxKind) -> bool {
                kind == SyntaxKind::$kind
            }

            fn cast(node: SyntaxNode) -> Option<Self> {
                if Self::can_cast(node.kind()) {
                    Some(Self(node))
                } else {
                    None
                }
            }

            fn syntax(&self) -> &SyntaxNode {
                &self.0
            }
        }
    };
}

// ============================================================================
// Root
// ============================================================================

ast_node!(SourceFile, SOURCE_FILE);

impl SourceFile {
    children_method!(members, NamespaceMember);
}

// ============================================================================
// Namespace Members
// ============================================================================

/// Any member of a namespace (package, definition, usage, import, etc.)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum NamespaceMember {
    Package(Package),
    LibraryPackage(LibraryPackage),
    Import(Import),
    Alias(Alias),
    Dependency(Dependency),
    Definition(Definition),
    Usage(Usage),
    Filter(ElementFilter),
    Metadata(MetadataUsage),
    Comment(Comment),
    /// Standalone bind statement (e.g., `bind p1 = p2;`)
    Bind(BindingConnector),
    /// Standalone succession (e.g., `first a then b;`)
    Succession(Succession),
    /// Transition usage (e.g., `accept sig : Signal then running;`)
    Transition(TransitionUsage),
    /// KerML connector (e.g., `connector link;`)
    Connector(Connector),
    /// Connect usage (e.g., `connect p ::> a to b;`)
    ConnectUsage(ConnectUsage),
    /// Send action usage (e.g., `send x via port`)
    SendAction(SendActionUsage),
    /// Accept action usage (e.g., `accept e : Signal via port`)
    AcceptAction(AcceptActionUsage),
    /// State subaction (e.g., `entry action initial;`)
    StateSubaction(StateSubaction),
    /// Control node (fork, join, merge, decide)
    ControlNode(ControlNode),
    /// For loop action usage (e.g., `for n : Integer in (1,2,3) { }`)
    ForLoop(ForLoopActionUsage),
    /// If action usage (e.g., `if x == 1 then A1;`)
    IfAction(IfActionUsage),
    /// While loop action usage (e.g., `while x > 0 { }`)
    WhileLoop(WhileLoopActionUsage),
}

impl AstNode for NamespaceMember {
    fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::PACKAGE
                | SyntaxKind::LIBRARY_PACKAGE
                | SyntaxKind::IMPORT
                | SyntaxKind::ALIAS_MEMBER
                | SyntaxKind::DEPENDENCY
                | SyntaxKind::DEFINITION
                | SyntaxKind::USAGE
                | SyntaxKind::SUBJECT_USAGE
                | SyntaxKind::ACTOR_USAGE
                | SyntaxKind::STAKEHOLDER_USAGE
                | SyntaxKind::OBJECTIVE_USAGE
                | SyntaxKind::ELEMENT_FILTER_MEMBER
                | SyntaxKind::METADATA_USAGE
                | SyntaxKind::COMMENT_ELEMENT
                | SyntaxKind::BINDING_CONNECTOR
                | SyntaxKind::SUCCESSION
                | SyntaxKind::TRANSITION_USAGE
                | SyntaxKind::CONNECTOR
                | SyntaxKind::CONNECT_USAGE
                | SyntaxKind::SEND_ACTION_USAGE
                | SyntaxKind::ACCEPT_ACTION_USAGE
                | SyntaxKind::STATE_SUBACTION
                | SyntaxKind::CONTROL_NODE
                | SyntaxKind::FOR_LOOP_ACTION_USAGE
                | SyntaxKind::IF_ACTION_USAGE
                | SyntaxKind::WHILE_LOOP_ACTION_USAGE
        )
    }

    fn cast(node: SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::PACKAGE => Some(Self::Package(Package(node))),
            SyntaxKind::LIBRARY_PACKAGE => Some(Self::LibraryPackage(LibraryPackage(node))),
            SyntaxKind::IMPORT => Some(Self::Import(Import(node))),
            SyntaxKind::ALIAS_MEMBER => Some(Self::Alias(Alias(node))),
            SyntaxKind::DEPENDENCY => Some(Self::Dependency(Dependency(node))),
            SyntaxKind::DEFINITION => Some(Self::Definition(Definition(node))),
            SyntaxKind::USAGE
            | SyntaxKind::SUBJECT_USAGE
            | SyntaxKind::ACTOR_USAGE
            | SyntaxKind::STAKEHOLDER_USAGE
            | SyntaxKind::OBJECTIVE_USAGE => Some(Self::Usage(Usage(node))),
            SyntaxKind::ELEMENT_FILTER_MEMBER => Some(Self::Filter(ElementFilter(node))),
            SyntaxKind::METADATA_USAGE => Some(Self::Metadata(MetadataUsage(node))),
            SyntaxKind::COMMENT_ELEMENT => Some(Self::Comment(Comment(node))),
            SyntaxKind::BINDING_CONNECTOR => Some(Self::Bind(BindingConnector(node))),
            SyntaxKind::SUCCESSION => Some(Self::Succession(Succession(node))),
            SyntaxKind::TRANSITION_USAGE => Some(Self::Transition(TransitionUsage(node))),
            SyntaxKind::CONNECTOR => Some(Self::Connector(Connector(node))),
            SyntaxKind::CONNECT_USAGE => Some(Self::ConnectUsage(ConnectUsage(node))),
            SyntaxKind::SEND_ACTION_USAGE => Some(Self::SendAction(SendActionUsage(node))),
            SyntaxKind::ACCEPT_ACTION_USAGE => Some(Self::AcceptAction(AcceptActionUsage(node))),
            SyntaxKind::STATE_SUBACTION => Some(Self::StateSubaction(StateSubaction(node))),
            SyntaxKind::CONTROL_NODE => Some(Self::ControlNode(ControlNode(node))),
            SyntaxKind::FOR_LOOP_ACTION_USAGE => Some(Self::ForLoop(ForLoopActionUsage(node))),
            SyntaxKind::IF_ACTION_USAGE => Some(Self::IfAction(IfActionUsage(node))),
            SyntaxKind::WHILE_LOOP_ACTION_USAGE => {
                Some(Self::WhileLoop(WhileLoopActionUsage(node)))
            }
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        match self {
            Self::Package(n) => n.syntax(),
            Self::LibraryPackage(n) => n.syntax(),
            Self::Import(n) => n.syntax(),
            Self::Alias(n) => n.syntax(),
            Self::Dependency(n) => n.syntax(),
            Self::Definition(n) => n.syntax(),
            Self::Usage(n) => n.syntax(),
            Self::Filter(n) => n.syntax(),
            Self::Metadata(n) => n.syntax(),
            Self::Comment(n) => n.syntax(),
            Self::Bind(n) => n.syntax(),
            Self::Succession(n) => n.syntax(),
            Self::Transition(n) => n.syntax(),
            Self::Connector(n) => n.syntax(),
            Self::ConnectUsage(n) => n.syntax(),
            Self::SendAction(n) => n.syntax(),
            Self::AcceptAction(n) => n.syntax(),
            Self::StateSubaction(n) => n.syntax(),
            Self::ControlNode(n) => n.syntax(),
            Self::ForLoop(n) => n.syntax(),
            Self::IfAction(n) => n.syntax(),
            Self::WhileLoop(n) => n.syntax(),
        }
    }
}

// ============================================================================
// Package
// ============================================================================

ast_node!(Package, PACKAGE);

impl Package {
    first_child_method!(name, Name);
    first_child_method!(body, NamespaceBody);
    body_members_method!();
}

ast_node!(LibraryPackage, LIBRARY_PACKAGE);

impl LibraryPackage {
    has_token_method!(is_standard, STANDARD_KW, "standard library package P {}");
    first_child_method!(name, Name);
    first_child_method!(body, NamespaceBody);
}

ast_node!(NamespaceBody, NAMESPACE_BODY);

impl NamespaceBody {
    pub fn members(&self) -> impl Iterator<Item = NamespaceMember> + '_ {
        self.0.children().flat_map(|child| {
            // STATE_SUBACTION is a container for entry/do/exit actions
            // We need to look inside for nested members (ACCEPT_ACTION_USAGE, SEND_ACTION_USAGE)
            // as well as try casting the child itself
            if child.kind() == SyntaxKind::STATE_SUBACTION {
                // First try direct children of STATE_SUBACTION
                let nested: Vec<NamespaceMember> =
                    child.children().filter_map(NamespaceMember::cast).collect();
                if nested.is_empty() {
                    // If no nested namespace members, wrap the STATE_SUBACTION itself as a StateSubaction
                    StateSubaction::cast(child)
                        .map(NamespaceMember::StateSubaction)
                        .into_iter()
                        .collect()
                } else {
                    nested
                }
            } else {
                NamespaceMember::cast(child).into_iter().collect()
            }
        })
    }
}

// ============================================================================
// Import
// ============================================================================

ast_node!(Import, IMPORT);

impl Import {
    has_token_method!(is_all, ALL_KW, "import all P::*");
    first_child_method!(target, QualifiedName);
    has_token_method!(is_wildcard, STAR, "import P::*");

    /// Check if this is a recursive import (::**)
    pub fn is_recursive(&self) -> bool {
        // Check for STAR_STAR token (lexed as single token)
        // or two consecutive STAR tokens
        let has_star_star = self
            .0
            .descendants_with_tokens()
            .filter_map(|e| match e {
                rowan::NodeOrToken::Token(t) => Some(t),
                _ => None,
            })
            .any(|t| t.kind() == SyntaxKind::STAR_STAR);

        if has_star_star {
            return true;
        }

        // Fallback: count individual stars
        let stars: Vec<_> = self
            .0
            .children_with_tokens()
            .filter_map(|e| e.into_token())
            .filter(|t| t.kind() == SyntaxKind::STAR)
            .collect();
        stars.len() >= 2
    }

    /// Check if this is a public import
    pub fn is_public(&self) -> bool {
        // PUBLIC_KW may be a sibling (before the IMPORT node) rather than a child
        // Check both inside and before
        if has_token(&self.0, SyntaxKind::PUBLIC_KW) {
            return true;
        }

        // Check previous sibling
        if let Some(prev) = self.0.prev_sibling_or_token() {
            // Skip whitespace
            let mut current = Some(prev);
            while let Some(node_or_token) = current {
                match node_or_token {
                    rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::PUBLIC_KW => {
                        return true;
                    }
                    rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::WHITESPACE => {
                        current = t.prev_sibling_or_token();
                    }
                    _ => break,
                }
            }
        }

        false
    }

    first_child_method!(filter, FilterPackage);
}

ast_node!(FilterPackage, FILTER_PACKAGE);

impl FilterPackage {
    first_child_method!(target, QualifiedName);
    children_vec_method!(targets, QualifiedName);
}

// ============================================================================
// Alias
// ============================================================================

ast_node!(Alias, ALIAS_MEMBER);

impl Alias {
    first_child_method!(name, Name);
    first_child_method!(target, QualifiedName);
}

// ============================================================================
// Dependency
// ============================================================================

ast_node!(Dependency, DEPENDENCY);

impl Dependency {
    children_method!(qualified_names, QualifiedName);

    /// Get the source qualified name(s) - everything before "to"
    /// For `dependency a, b to c` returns [a, b]
    pub fn sources(&self) -> Vec<QualifiedName> {
        split_at_keyword(&self.0, SyntaxKind::TO_KW).0
    }

    /// Get the target qualified name - after "to"
    /// For `dependency a to c` returns c
    pub fn target(&self) -> Option<QualifiedName> {
        split_at_keyword::<QualifiedName>(&self.0, SyntaxKind::TO_KW)
            .1
            .into_iter()
            .next()
    }

    prefix_metadata_method!();
}

// ============================================================================
// Filter
// ============================================================================

ast_node!(ElementFilter, ELEMENT_FILTER_MEMBER);

impl ElementFilter {
    first_child_method!(expression, Expression);

    /// Extract metadata references from the filter expression.
    /// For `filter @Safety;` returns ["Safety"]
    pub fn metadata_refs(&self) -> Vec<String> {
        let mut refs = Vec::new();
        if let Some(expr) = self.expression() {
            // Walk the expression looking for @ followed by QUALIFIED_NAME
            let mut at_seen = false;
            for child in expr.syntax().children_with_tokens() {
                match child {
                    rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::AT => {
                        at_seen = true;
                    }
                    rowan::NodeOrToken::Node(n)
                        if at_seen && n.kind() == SyntaxKind::QUALIFIED_NAME =>
                    {
                        if let Some(qn) = QualifiedName::cast(n) {
                            refs.push(qn.to_string());
                        }
                        at_seen = false;
                    }
                    _ => {}
                }
            }
        }
        refs
    }

    /// Extract ALL qualified name references from the filter expression with their ranges.
    /// This includes both @-prefixed metadata refs and feature refs like `Safety::isMandatory`.
    /// Returns (name, range) pairs for IDE features (hover, go-to-def).
    pub fn all_qualified_refs(&self) -> Vec<(String, rowan::TextRange)> {
        let mut refs = Vec::new();
        if let Some(expr) = self.expression() {
            // Use descendants() to walk the entire tree, not just direct children
            for node in expr.syntax().descendants() {
                if node.kind() == SyntaxKind::QUALIFIED_NAME {
                    if let Some(qn) = QualifiedName::cast(node.clone()) {
                        refs.push((qn.to_string(), node.text_range()));
                    }
                }
            }
        }
        refs
    }
}

// ============================================================================
// Comment
// ============================================================================

ast_node!(Comment, COMMENT_ELEMENT);

impl Comment {
    first_child_method!(name, Name);
    children_method!(about_targets, QualifiedName);
    has_token_method!(has_about, ABOUT_KW, "doc /* text */ about x");
}

// ============================================================================
// Metadata
// ============================================================================

ast_node!(MetadataUsage, METADATA_USAGE);

impl MetadataUsage {
    first_child_method!(target, QualifiedName);

    /// Get the about target(s) - references after the 'about' keyword
    /// e.g., `@Rationale about vehicle::engine` returns [vehicle::engine]
    pub fn about_targets(&self) -> impl Iterator<Item = QualifiedName> + '_ {
        // Skip the first QualifiedName (which is the metadata type)
        // All subsequent QualifiedNames are about targets
        self.0.children().filter_map(QualifiedName::cast).skip(1)
    }

    has_token_method!(has_about, ABOUT_KW, "@Rationale about x");
    first_child_method!(body, NamespaceBody);
}

// ============================================================================
// Prefix Metadata (#name)
// ============================================================================

ast_node!(PrefixMetadata, PREFIX_METADATA);

impl PrefixMetadata {
    /// Find the IDENT token (the name after #)
    fn ident_token(&self) -> Option<SyntaxToken> {
        self.0
            .children_with_tokens()
            .filter_map(|e| e.into_token())
            .find(|t| t.kind() == SyntaxKind::IDENT)
    }

    /// Get the metadata type name (e.g., `mop` in `#mop attribute mass : Real;`)
    pub fn name(&self) -> Option<String> {
        self.ident_token().map(|t| t.text().to_string())
    }

    /// Get the text range of the identifier (for hover/goto)
    pub fn name_range(&self) -> Option<rowan::TextRange> {
        self.ident_token().map(|t| t.text_range())
    }
}

// ============================================================================
// Definition
// ============================================================================

ast_node!(Definition, DEFINITION);

impl Definition {
    has_token_method!(is_abstract, ABSTRACT_KW, "abstract part def P {}");
    has_token_method!(is_variation, VARIATION_KW, "variation part def V {}");
    has_token_method!(is_individual, INDIVIDUAL_KW, "individual part def Earth;");

    token_to_enum_method!(definition_kind, DefinitionKind, [
        PART_KW => Part,
        ATTRIBUTE_KW => Attribute,
        PORT_KW => Port,
        ITEM_KW => Item,
        ACTION_KW => Action,
        STATE_KW => State,
        CONSTRAINT_KW => Constraint,
        REQUIREMENT_KW => Requirement,
        CASE_KW => Case,
        CALC_KW => Calc,
        CONNECTION_KW => Connection,
        INTERFACE_KW => Interface,
        ALLOCATION_KW => Allocation,
        FLOW_KW => Flow,
        VIEW_KW => View,
        VIEWPOINT_KW => Viewpoint,
        RENDERING_KW => Rendering,
        METADATA_KW => Metadata,
        OCCURRENCE_KW => Occurrence,
        ENUM_KW => Enum,
        ANALYSIS_KW => Analysis,
        VERIFICATION_KW => Verification,
        USE_KW => UseCase,
        CONCERN_KW => Concern,
        // KerML definition keywords
        CLASS_KW => Class,
        STRUCT_KW => Struct,
        ASSOC_KW => Assoc,
        BEHAVIOR_KW => Behavior,
        FUNCTION_KW => Function,
        PREDICATE_KW => Predicate,
        INTERACTION_KW => Interaction,
        DATATYPE_KW => Datatype,
        CLASSIFIER_KW => Classifier,
        TYPE_KW => Type,
        METACLASS_KW => Metaclass,
    ]);

    first_child_method!(name, Name);
    children_method!(specializations, Specialization);
    first_child_method!(body, NamespaceBody);
    first_child_method!(constraint_body, ConstraintBody);

    body_members_method!();
    prefix_metadata_method!();
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefinitionKind {
    Part,
    Attribute,
    Port,
    Item,
    Action,
    State,
    Constraint,
    Requirement,
    Case,
    Calc,
    Connection,
    Interface,
    Allocation,
    Flow,
    View,
    Viewpoint,
    Rendering,
    Metadata,
    Occurrence,
    Enum,
    Analysis,
    Verification,
    UseCase,
    Concern,
    // KerML kinds
    Class,
    Struct,
    Assoc,
    Behavior,
    Function,
    Predicate,
    Interaction,
    Datatype,
    Classifier,
    Type,
    Metaclass,
}

// ============================================================================
// Usage
// ============================================================================

/// Usage node - covers USAGE and requirement-specific usage kinds
/// (SUBJECT_USAGE, ACTOR_USAGE, STAKEHOLDER_USAGE, OBJECTIVE_USAGE)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Usage(SyntaxNode);

impl AstNode for Usage {
    fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::USAGE
                | SyntaxKind::SUBJECT_USAGE
                | SyntaxKind::ACTOR_USAGE
                | SyntaxKind::STAKEHOLDER_USAGE
                | SyntaxKind::OBJECTIVE_USAGE
        )
    }

    fn cast(node: SyntaxNode) -> Option<Self> {
        if Self::can_cast(node.kind()) {
            Some(Self(node))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl Usage {
    has_token_method!(is_ref, REF_KW, "ref part p;");
    has_token_method!(is_readonly, READONLY_KW, "readonly attribute x;");
    has_token_method!(is_derived, DERIVED_KW, "derived attribute x;");
    has_token_method!(is_abstract, ABSTRACT_KW, "abstract part p;");
    has_token_method!(is_variation, VARIATION_KW, "variation part p;");
    has_token_method!(is_var, VAR_KW, "var attribute x;");
    has_token_method!(is_all, ALL_KW, "feature all instances : C[*]");
    has_token_method!(is_parallel, PARALLEL_KW, "parallel action a;");
    has_token_method!(
        is_individual,
        INDIVIDUAL_KW,
        "individual part earth : Earth;"
    );
    has_token_method!(is_end, END_KW, "end part wheel : Wheel[4];");
    has_token_method!(is_default, DEFAULT_KW, "default attribute rgb : RGB;");
    has_token_method!(is_ordered, ORDERED_KW, "ordered part wheels : Wheel[4];");
    has_token_method!(
        is_nonunique,
        NONUNIQUE_KW,
        "nonunique attribute scores : Integer[*];"
    );
    has_token_method!(is_portion, PORTION_KW, "portion part fuelLoad : Fuel;");

    token_to_enum_method!(direction, Direction, [
        IN_KW => In,
        OUT_KW => Out,
        INOUT_KW => InOut,
    ]);

    /// Get multiplicity bounds [lower..upper] from the usage.
    /// Returns (lower, upper) where None means unbounded (*).
    /// E.g., `[1..5]` -> `(Some(1), Some(5))`, `[*]` -> `(None, None)`, `[0..*]` -> `(Some(0), None)`
    pub fn multiplicity(&self) -> Option<(Option<u64>, Option<u64>)> {
        // Find MULTIPLICITY node in children first (direct multiplicity like `wheels[4]`)
        if let Some(mult_node) = self
            .0
            .children()
            .find(|n| n.kind() == SyntaxKind::MULTIPLICITY)
        {
            return Self::parse_multiplicity_node(&mult_node);
        }

        // Check for multiplicity in TYPING or SPECIALIZATION children (like `fuelIn : FuelType[1]`)
        for child in self.0.children() {
            match child.kind() {
                SyntaxKind::TYPING | SyntaxKind::SPECIALIZATION => {
                    if let Some(mult_node) = child
                        .children()
                        .find(|n| n.kind() == SyntaxKind::MULTIPLICITY)
                    {
                        return Self::parse_multiplicity_node(&mult_node);
                    }
                }
                _ => {}
            }
        }

        None
    }

    /// Parse a MULTIPLICITY node and extract bounds
    fn parse_multiplicity_node(mult_node: &SyntaxNode) -> Option<(Option<u64>, Option<u64>)> {
        let mut lower: Option<u64> = None;
        let mut upper: Option<u64> = None;
        let mut found_dot_dot = false;

        // Recursively search for INTEGER and STAR tokens in the multiplicity node
        fn find_bounds(
            node: &SyntaxNode,
            lower: &mut Option<u64>,
            upper: &mut Option<u64>,
            found_dot_dot: &mut bool,
        ) {
            for child in node.children_with_tokens() {
                match child.kind() {
                    SyntaxKind::INTEGER => {
                        if let Some(token) = child.into_token() {
                            let text = token.text();
                            if let Ok(val) = text.parse::<u64>() {
                                if *found_dot_dot {
                                    *upper = Some(val);
                                } else {
                                    *lower = Some(val);
                                }
                            }
                        }
                    }
                    SyntaxKind::STAR => {
                        // * means unbounded - leave as None
                        if *found_dot_dot {
                            *upper = None;
                        } else {
                            *lower = None;
                        }
                    }
                    SyntaxKind::DOT_DOT => {
                        *found_dot_dot = true;
                    }
                    _ => {
                        // Recurse into child nodes (e.g., LITERAL_EXPR)
                        if let Some(node) = child.into_node() {
                            find_bounds(&node, lower, upper, found_dot_dot);
                        }
                    }
                }
            }
        }

        find_bounds(mult_node, &mut lower, &mut upper, &mut found_dot_dot);

        // If no ".." found, lower is also the upper bound (e.g., [4] means [4..4])
        if !found_dot_dot && lower.is_some() {
            upper = lower;
        }

        // Only return Some if we found at least one bound or a star
        if lower.is_some() || upper.is_some() || found_dot_dot {
            Some((lower, upper))
        } else {
            // Try returning the found structure anyway - might be [*] or similar
            Some((lower, upper))
        }
    }

    /// Get prefix metadata references.
    /// e.g., `#mop attribute mass : Real;` -> returns [PrefixMetadata for "mop"]
    ///
    /// PREFIX_METADATA nodes can be in two locations depending on the usage type:
    /// 1. For most usages (part, attribute, etc.): preceding siblings in the namespace body
    /// 2. For end features: children of the USAGE node (after END_KW)
    pub fn prefix_metadata(&self) -> Vec<PrefixMetadata> {
        let mut result = collect_prefix_metadata(&self.0);

        // Also check children (for end features where PREFIX_METADATA is inside USAGE)
        for child in self.0.children() {
            if child.kind() == SyntaxKind::PREFIX_METADATA {
                if let Some(pm) = PrefixMetadata::cast(child) {
                    result.push(pm);
                }
            }
        }

        result
    }

    first_child_method!(name, Name);
    children_vec_method!(names, Name);

    first_child_method!(typing, Typing);

    child_after_keyword_method!(
        of_type,
        QualifiedName,
        OF_KW,
        "Get the 'of Type' qualified name for messages/items (e.g., `message sendCmd of SensedSpeed`)."
    );

    children_method!(specializations, Specialization);
    first_child_method!(body, NamespaceBody);
    first_child_method!(value_expression, Expression);
    first_child_method!(from_to_clause, FromToClause);
    first_child_method!(transition_usage, TransitionUsage);
    first_child_method!(succession, Succession);
    first_child_method!(perform_action_usage, PerformActionUsage);
    first_child_method!(accept_action_usage, AcceptActionUsage);
    first_child_method!(send_action_usage, SendActionUsage);
    first_child_method!(requirement_verification, RequirementVerification);
    first_child_method!(connect_usage, ConnectUsage);
    first_child_method!(constraint_body, ConstraintBody);
    first_child_method!(connector_part, ConnectorPart);
    first_child_method!(binding_connector, BindingConnector);

    has_token_method!(is_exhibit, EXHIBIT_KW, "exhibit state s;");
    has_token_method!(is_include, INCLUDE_KW, "include use case u;");
    has_token_method!(is_allocate, ALLOCATE_KW, "allocate x to y;");
    has_token_method!(is_flow, FLOW_KW, "flow x to y;");

    /// Get direct flow endpoints for flows without `from` keyword.
    /// Pattern: `flow X.Y to A.B` returns (Some(X.Y), Some(A.B))
    /// This is different from `flow name from X to Y` which uses from_to_clause().
    pub fn direct_flow_endpoints(&self) -> (Option<QualifiedName>, Option<QualifiedName>) {
        // Only applicable to flow usages
        if !self.is_flow() {
            return (None, None);
        }

        // If there's a from_to_clause, this isn't a direct flow
        if self.from_to_clause().is_some() {
            return (None, None);
        }

        // Look for pattern: FLOW_KW ... QUALIFIED_NAME TO_KW QUALIFIED_NAME
        let mut found_flow = false;
        let mut found_to = false;
        let mut source: Option<QualifiedName> = None;
        let mut target: Option<QualifiedName> = None;

        for elem in self.0.children_with_tokens() {
            if let Some(token) = elem.as_token() {
                if token.kind() == SyntaxKind::FLOW_KW {
                    found_flow = true;
                } else if token.kind() == SyntaxKind::TO_KW && found_flow {
                    found_to = true;
                }
            } else if let Some(node) = elem.as_node() {
                if found_flow && node.kind() == SyntaxKind::QUALIFIED_NAME {
                    if !found_to && source.is_none() {
                        source = QualifiedName::cast(node.clone());
                    } else if found_to && target.is_none() {
                        target = QualifiedName::cast(node.clone());
                    }
                }
            }
        }

        (source, target)
    }

    has_token_method!(is_assert, ASSERT_KW, "assert constraint c;");
    has_token_method!(is_assume, ASSUME_KW, "assume constraint c;");
    has_token_method!(is_require, REQUIRE_KW, "require constraint c;");

    token_to_enum_method!(usage_kind, UsageKind, [
        PART_KW => Part,
        ATTRIBUTE_KW => Attribute,
        PORT_KW => Port,
        ITEM_KW => Item,
        ACTION_KW => Action,
        STATE_KW => State,
        CONSTRAINT_KW => Constraint,
        REQUIREMENT_KW => Requirement,
        CASE_KW => Case,
        CALC_KW => Calc,
        CONNECTION_KW => Connection,
        INTERFACE_KW => Interface,
        ALLOCATION_KW => Allocation,
        FLOW_KW => Flow,
        MESSAGE_KW => Flow,
        OCCURRENCE_KW => Occurrence,
        REF_KW => Ref,
        // KerML usage keywords
        FEATURE_KW => Feature,
        STEP_KW => Step,
        EXPR_KW => Expr,
        CONNECTOR_KW => Connector,
    ]);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UsageKind {
    Part,
    Attribute,
    Port,
    Item,
    Action,
    State,
    Constraint,
    Requirement,
    Case,
    Calc,
    Connection,
    Interface,
    Allocation,
    Flow,
    Occurrence,
    Ref,
    // KerML
    Feature,
    Step,
    Expr,
    Connector,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
    In,
    Out,
    InOut,
}

// ============================================================================
// Names
// ============================================================================

ast_node!(Name, NAME);

impl Name {
    first_child_method!(short_name, ShortName);

    pub fn text(&self) -> Option<String> {
        find_name_token(&self.0).map(|t| t.text().to_string())
    }
}

ast_node!(ShortName, SHORT_NAME);

impl ShortName {
    pub fn text(&self) -> Option<String> {
        find_name_token(&self.0).map(|t| strip_unrestricted_name(t.text()))
    }
}

ast_node!(QualifiedName, QUALIFIED_NAME);

impl QualifiedName {
    /// Get all name segments
    /// Includes IDENT tokens and contextual keywords that can be used as identifiers
    pub fn segments(&self) -> Vec<String> {
        self.0
            .children_with_tokens()
            .filter_map(|e| e.into_token())
            .filter(|t| is_name_token(t.kind()))
            .map(|t| strip_unrestricted_name(t.text()))
            .collect()
    }

    /// Get all name segments with their text ranges
    /// Includes IDENT tokens and contextual keywords that can be used as identifiers
    pub fn segments_with_ranges(&self) -> Vec<(String, rowan::TextRange)> {
        self.0
            .children_with_tokens()
            .filter_map(|e| e.into_token())
            .filter(|t| is_name_token(t.kind()))
            .map(|t| (strip_unrestricted_name(t.text()), t.text_range()))
            .collect()
    }

    /// Get the full qualified name as a string
    /// Uses '::' for namespace paths, '.' for feature chains
    fn to_string_inner(&self) -> String {
        // Check if this is a feature chain (uses '.' separator) or namespace path (uses '::')
        let has_dot = has_token(&self.0, SyntaxKind::DOT);

        let separator = if has_dot { "." } else { "::" };
        self.segments().join(separator)
    }
}

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

// ============================================================================
// Typing and Specialization
// ============================================================================

ast_node!(Typing, TYPING);

impl Typing {
    first_child_method!(target, QualifiedName);
}

ast_node!(Specialization, SPECIALIZATION);

impl Specialization {
    token_to_enum_method!(kind, SpecializationKind, [
        COLON_GT => Specializes,
        COLON_GT_GT => Redefines,
        COLON_COLON_GT => FeatureChain,
        SPECIALIZES_KW => Specializes,
        SUBSETS_KW => Subsets,
        REDEFINES_KW => Redefines,
        REFERENCES_KW => References,
        TILDE => Conjugates,
        FROM_KW => FeatureChain,
        TO_KW => FeatureChain,
        CHAINS_KW => FeatureChain,
    ]);

    /// Check if this is a shorthand redefines (`:>>`) vs keyword (`redefines`)
    /// Returns true for `:>> name`, false for `redefines name`
    pub fn is_shorthand_redefines(&self) -> bool {
        has_token(&self.0, SyntaxKind::COLON_GT_GT)
    }

    first_child_method!(target, QualifiedName);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecializationKind {
    Specializes,
    Subsets,
    Redefines,
    References,
    Conjugates,
    /// Feature chaining via `::>` shorthand or `chains` keyword.
    /// Per SysML v2 Spec §7.3.4.5: indicates a feature chain relationship.
    /// e.g., `feature x ::> a.b` or `feature self subsets things chains things.that`
    FeatureChain,
}

// ============================================================================
// From-To Clause (for message/flow usages)
// ============================================================================

ast_node!(FromToClause, FROM_TO_CLAUSE);

impl FromToClause {
    first_child_method!(source, FromToSource);
    first_child_method!(target, FromToTarget);
}

ast_node!(FromToSource, FROM_TO_SOURCE);

impl FromToSource {
    first_child_method!(target, QualifiedName);
}

ast_node!(FromToTarget, FROM_TO_TARGET);

impl FromToTarget {
    first_child_method!(target, QualifiedName);
}

// ============================================================================
// Transition Usage
// ============================================================================

ast_node!(TransitionUsage, TRANSITION_USAGE);

impl TransitionUsage {
    /// Get the transition name (if explicitly named before 'first' keyword)
    /// e.g., `transition T first S1 then S2` returns Some(T)
    /// but `transition first S1 accept s then S2` returns None (s is the accept payload, not the name)
    pub fn name(&self) -> Option<Name> {
        use crate::parser::SyntaxKind;
        // Only return a NAME that appears before FIRST_KW, ACCEPT_KW, or other transition body keywords
        for child in self.0.children_with_tokens() {
            match &child {
                rowan::NodeOrToken::Token(t) => {
                    // If we hit first/accept/then/do/if/via before finding a name, there's no name
                    match t.kind() {
                        SyntaxKind::FIRST_KW
                        | SyntaxKind::ACCEPT_KW
                        | SyntaxKind::THEN_KW
                        | SyntaxKind::DO_KW
                        | SyntaxKind::IF_KW
                        | SyntaxKind::VIA_KW => return None,
                        _ => {}
                    }
                }
                rowan::NodeOrToken::Node(n) => {
                    if let Some(name) = Name::cast(n.clone()) {
                        return Some(name);
                    }
                }
            }
        }
        None
    }

    children_method!(specializations, Specialization);
    source_target_pair!(source, target, specializations, Specialization);

    child_after_keyword_method!(
        accept_payload_name,
        Name,
        ACCEPT_KW,
        "Get the accept payload name (e.g., `ignitionCmd` in `accept ignitionCmd:IgnitionCmd`)."
    );

    first_child_method!(accept_typing, Typing);

    child_after_keyword_method!(
        accept_via,
        QualifiedName,
        VIA_KW,
        "Get the 'via' target for the accept trigger (e.g., `ignitionCmdPort` in `accept ignitionCmd via ignitionCmdPort`)."
    );
}

// ============================================================================
// Perform Action Usage
// ============================================================================

ast_node!(PerformActionUsage, PERFORM_ACTION_USAGE);

impl PerformActionUsage {
    first_child_method!(name, Name);
    first_child_method!(typing, Typing);
    children_method!(specializations, Specialization);

    /// Get the performed action (first specialization, the action being performed)
    pub fn performed(&self) -> Option<Specialization> {
        self.specializations().next()
    }

    first_child_method!(body, NamespaceBody);
}

// ============================================================================
// Accept Action Usage
// ============================================================================

ast_node!(AcceptActionUsage, ACCEPT_ACTION_USAGE);

impl AcceptActionUsage {
    first_child_method!(name, Name);
    first_child_method!(trigger, Expression);
    first_child_method!(accepted, QualifiedName);

    child_after_keyword_method!(
        via,
        QualifiedName,
        VIA_KW,
        "Get the 'via' target port (e.g., `ignitionCmdPort` in `accept ignitionCmd via ignitionCmdPort`)."
    );
}

// ============================================================================
// Send Action Usage
// ============================================================================

ast_node!(SendActionUsage, SEND_ACTION_USAGE);

impl SendActionUsage {
    first_child_method!(payload, Expression);
    children_method!(qualified_names, QualifiedName);
}

// ============================================================================
// For Loop Action Usage
// ============================================================================

ast_node!(ForLoopActionUsage, FOR_LOOP_ACTION_USAGE);

impl ForLoopActionUsage {
    first_child_method!(variable_name, Name);
    first_child_method!(typing, Typing);
    first_child_method!(body, NamespaceBody);
    body_members_method!();
}

// ============================================================================
// If Action Usage
// ============================================================================

ast_node!(IfActionUsage, IF_ACTION_USAGE);

impl IfActionUsage {
    descendants_method!(
        expressions,
        Expression,
        "Get descendant expressions (condition and then/else targets)."
    );
    children_method!(qualified_names, QualifiedName);
    first_child_method!(body, NamespaceBody);
}

// ============================================================================
// While Loop Action Usage
// ============================================================================

ast_node!(WhileLoopActionUsage, WHILE_LOOP_ACTION_USAGE);

impl WhileLoopActionUsage {
    descendants_method!(
        expressions,
        Expression,
        "Get descendant expressions (condition)."
    );
    first_child_method!(body, NamespaceBody);
    body_members_method!();
}

// ============================================================================
// State Subaction (entry/do/exit)
// ============================================================================

ast_node!(StateSubaction, STATE_SUBACTION);

impl StateSubaction {
    find_token_kind_method!(
        kind,
        [ENTRY_KW, DO_KW, EXIT_KW],
        "Get the state subaction kind (entry, do, or exit)."
    );

    first_child_method!(name, Name);
    first_child_method!(body, NamespaceBody);

    has_token_method!(is_entry, ENTRY_KW, "entry action initial;");
    has_token_method!(is_do, DO_KW, "do action running;");
    has_token_method!(is_exit, EXIT_KW, "exit action cleanup;");
}

// ============================================================================
// Control Node (fork, join, merge, decide)
// ============================================================================

ast_node!(ControlNode, CONTROL_NODE);

impl ControlNode {
    find_token_kind_method!(
        kind,
        [FORK_KW, JOIN_KW, MERGE_KW, DECIDE_KW],
        "Get the control node kind (fork, join, merge, or decide)."
    );

    first_child_method!(name, Name);
    first_child_method!(body, NamespaceBody);

    has_token_method!(is_fork, FORK_KW, "fork forkNode;");
    has_token_method!(is_join, JOIN_KW, "join joinNode;");
    has_token_method!(is_merge, MERGE_KW, "merge mergeNode;");
    has_token_method!(is_decide, DECIDE_KW, "decide decideNode;");
}

// ============================================================================
// Requirement Verification (satisfy/verify)
// ============================================================================

ast_node!(RequirementVerification, REQUIREMENT_VERIFICATION);

impl RequirementVerification {
    has_token_method!(is_satisfy, SATISFY_KW, "satisfy requirement R;");
    has_token_method!(is_verify, VERIFY_KW, "verify requirement R;");
    has_token_method!(is_negated, NOT_KW, "not satisfy requirement R;");
    has_token_method!(is_asserted, ASSERT_KW, "assert satisfy requirement R;");
    first_child_method!(requirement, QualifiedName);
    first_child_method!(typing, Typing);

    child_after_keyword_method!(
        by_target,
        QualifiedName,
        BY_KW,
        "Get the 'by' target (e.g., `vehicle_b` in `satisfy R by vehicle_b`)."
    );
}

// ============================================================================
// KerML Connector (standalone connector, not SysML Connection)
// ============================================================================

ast_node!(Connector, CONNECTOR);

impl Connector {
    first_child_method!(name, Name);
    first_child_method!(typing, Typing);
    first_child_method!(connector_part, ConnectorPart);

    /// Get connector endpoints directly
    /// Returns iterator over connector ends for `from ... to ...` or `connect ... to ...`
    /// Looks in both CONNECTOR_PART (if present) and direct CONNECTION_END children
    pub fn ends(&self) -> impl Iterator<Item = ConnectorEnd> + '_ {
        // First try CONNECTOR_PART, then direct CONNECTION_END children
        let from_part: Vec<_> = self
            .connector_part()
            .into_iter()
            .flat_map(|cp| cp.ends().collect::<Vec<_>>())
            .collect();

        let direct: Vec<_> = if from_part.is_empty() {
            self.0.children().filter_map(ConnectorEnd::cast).collect()
        } else {
            Vec::new()
        };

        from_part.into_iter().chain(direct)
    }

    first_child_method!(body, NamespaceBody);
}

// ============================================================================
// Connect Usage
// ============================================================================

ast_node!(ConnectUsage, CONNECT_USAGE);

impl ConnectUsage {
    first_child_method!(connector_part, ConnectorPart);
}

ast_node!(ConnectorPart, CONNECTOR_PART);

impl ConnectorPart {
    children_method!(ends, ConnectorEnd);
    source_target_pair!(source, target, ends, ConnectorEnd);
}

// ConnectorEnd can be either CONNECTION_END (KerML) or CONNECTOR_END (SysML)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConnectorEnd(SyntaxNode);

impl AstNode for ConnectorEnd {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::CONNECTION_END || kind == SyntaxKind::CONNECTOR_END
    }

    fn cast(node: SyntaxNode) -> Option<Self> {
        if Self::can_cast(node.kind()) {
            Some(Self(node))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl ConnectorEnd {
    /// Find the CONNECTOR_END_REFERENCE child and check if it has a ::> or references keyword.
    fn end_reference_info(&self) -> Option<(SyntaxNode, bool)> {
        let ref_node = self
            .0
            .children()
            .find(|n| n.kind() == SyntaxKind::CONNECTOR_END_REFERENCE)?;
        let has_references = ref_node.children_with_tokens().any(|n| {
            n.kind() == SyntaxKind::COLON_COLON_GT || n.kind() == SyntaxKind::REFERENCES_KW
        });
        Some((ref_node, has_references))
    }

    /// Get the qualified name target reference.
    /// For patterns like `p ::> comp.lugNutPort`, returns `comp.lugNutPort`.
    /// For simple patterns like `comp.lugNutPort`, returns `comp.lugNutPort`.
    pub fn target(&self) -> Option<QualifiedName> {
        if let Some((ref_node, has_references)) = self.end_reference_info() {
            let qns: Vec<_> = ref_node
                .children()
                .filter_map(QualifiedName::cast)
                .collect();
            // If there's a ::> or references keyword, return the second QN (the target)
            // Otherwise return the first/only QN
            if has_references && qns.len() > 1 {
                return Some(qns[1].clone());
            } else {
                return qns.into_iter().next();
            }
        }
        // Direct child lookup as fallback
        self.0.children().find_map(QualifiedName::cast)
    }

    /// Get the endpoint name (LHS of ::> if present).
    /// For patterns like `cause1 ::> a`, returns `cause1`.
    /// For simple patterns like `comp.lugNutPort`, returns None.
    pub fn endpoint_name(&self) -> Option<QualifiedName> {
        if let Some((ref_node, has_references)) = self.end_reference_info() {
            if has_references {
                // Return the first QN (endpoint name before ::>)
                return ref_node.children().filter_map(QualifiedName::cast).next();
            }
        }
        None
    }
}

// ============================================================================
// Binding Connector
// ============================================================================

ast_node!(BindingConnector, BINDING_CONNECTOR);

impl BindingConnector {
    children_method!(qualified_names, QualifiedName);
    source_target_pair!(source, target, qualified_names, QualifiedName);
}

// ============================================================================
// Succession
// ============================================================================

ast_node!(Succession, SUCCESSION);

impl Succession {
    children_method!(items, SuccessionItem);
    source_target_pair!(source, target, items, SuccessionItem);
    children_method!(inline_usages, Usage);
}

ast_node!(SuccessionItem, SUCCESSION_ITEM);

impl SuccessionItem {
    first_child_method!(target, QualifiedName);
    first_child_method!(usage, Usage);
}

// ============================================================================
// Constraint Body
// ============================================================================

ast_node!(ConstraintBody, CONSTRAINT_BODY);

impl ConstraintBody {
    first_child_method!(expression, Expression);
    children_method!(members, NamespaceMember);
}

// ============================================================================
// Expression
// ============================================================================

ast_node!(Expression, EXPRESSION);

/// A feature chain like `fuelTank.mass` with individual part ranges
#[derive(Debug, Clone)]
pub struct FeatureChainRef {
    /// The parts of the chain (e.g., ["fuelTank", "mass"])
    pub parts: Vec<(String, rowan::TextRange)>,
    /// The full range of the chain
    pub full_range: rowan::TextRange,
}

impl Expression {
    /// Extract all identifier references from this expression
    /// Returns pairs of (identifier_name, text_range)
    pub fn references(&self) -> Vec<(String, rowan::TextRange)> {
        let mut refs = Vec::new();
        self.collect_references(&self.0, &mut refs);
        refs
    }

    /// Extract feature chains from this expression.
    /// A feature chain is a sequence of identifiers separated by `.` (e.g., `fuelTank.mass`).
    /// Returns each chain with its parts and their individual ranges.
    pub fn feature_chains(&self) -> Vec<FeatureChainRef> {
        let mut chains = Vec::new();
        self.collect_feature_chains(&self.0, &mut chains);
        chains
    }

    /// Extract named constructor arguments from `new Type(argName = value)` patterns.
    /// Returns tuples of (type_name, arg_name, arg_name_range).
    /// The arg_name should resolve as Type.argName (a feature of the constructed type).
    pub fn named_constructor_args(&self) -> Vec<(String, String, rowan::TextRange)> {
        let mut results = Vec::new();
        self.collect_named_constructor_args(&self.0, &mut results);
        results
    }

    fn collect_named_constructor_args(
        &self,
        node: &SyntaxNode,
        results: &mut Vec<(String, String, rowan::TextRange)>,
    ) {
        // Look for pattern: NEW_KW followed by QUALIFIED_NAME then ARGUMENT_LIST
        let children: Vec<_> = node.children_with_tokens().collect();

        for (i, child) in children.iter().enumerate() {
            if child.as_token().map(|t| t.kind()) == Some(SyntaxKind::NEW_KW) {
                // Find the type name and argument list after NEW_KW
                let rest = &children[i + 1..];
                let type_name = rest
                    .iter()
                    .filter_map(|c| c.as_node())
                    .find(|n| n.kind() == SyntaxKind::QUALIFIED_NAME)
                    .map(|n| n.text().to_string());

                if let Some(type_name) = type_name {
                    for arg_list in rest
                        .iter()
                        .filter_map(|c| c.as_node())
                        .filter(|n| n.kind() == SyntaxKind::ARGUMENT_LIST)
                    {
                        self.extract_named_args_from_list(arg_list, &type_name, results);
                    }
                }
            }
        }

        // Recurse into child nodes
        for child in node.children() {
            self.collect_named_constructor_args(&child, results);
        }
    }

    fn extract_named_args_from_list(
        &self,
        arg_list: &SyntaxNode,
        type_name: &str,
        results: &mut Vec<(String, String, rowan::TextRange)>,
    ) {
        for child in arg_list
            .children()
            .filter(|c| c.kind() == SyntaxKind::ARGUMENT_LIST)
        {
            // Look for IDENT followed by EQ (named argument pattern)
            let tokens: Vec<_> = child.children_with_tokens().collect();

            for (idx, elem) in tokens.iter().enumerate() {
                if let Some(token) = elem.as_token().filter(|t| t.kind() == SyntaxKind::IDENT) {
                    // Check if next non-whitespace is EQ
                    let has_eq = tokens[idx + 1..]
                        .iter()
                        .filter_map(|e| e.as_token())
                        .find(|t| t.kind() != SyntaxKind::WHITESPACE)
                        .map(|t| t.kind() == SyntaxKind::EQ)
                        .unwrap_or(false);

                    if has_eq {
                        results.push((
                            type_name.to_string(),
                            token.text().to_string(),
                            token.text_range(),
                        ));
                    }
                }
            }

            // Recurse into nested argument lists
            self.extract_named_args_from_list(&child, type_name, results);
        }
    }

    fn collect_feature_chains(&self, node: &SyntaxNode, chains: &mut Vec<FeatureChainRef>) {
        if node.kind() == SyntaxKind::QUALIFIED_NAME {
            let parts: Vec<_> = node
                .children_with_tokens()
                .filter_map(|c| c.into_token())
                .filter(|t| t.kind() == SyntaxKind::IDENT)
                .map(|t| (t.text().to_string(), t.text_range()))
                .collect();

            if !parts.is_empty() {
                chains.push(FeatureChainRef {
                    parts,
                    full_range: node.text_range(),
                });
            }
            return;
        }

        for child in node.children_with_tokens() {
            match child {
                rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::IDENT => {
                    chains.push(FeatureChainRef {
                        parts: vec![(t.text().to_string(), t.text_range())],
                        full_range: t.text_range(),
                    });
                }
                rowan::NodeOrToken::Node(n) => self.collect_feature_chains(&n, chains),
                _ => {}
            }
        }
    }

    fn collect_references(&self, node: &SyntaxNode, refs: &mut Vec<(String, rowan::TextRange)>) {
        for child in node.children_with_tokens() {
            match child {
                rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::IDENT => {
                    refs.push((t.text().to_string(), t.text_range()));
                }
                rowan::NodeOrToken::Node(n) => self.collect_references(&n, refs),
                _ => {}
            }
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_ast_package() {
        let parsed = parse_sysml("package Test;");
        let root = SourceFile::cast(parsed.syntax()).unwrap();

        let members: Vec<_> = root.members().collect();
        assert_eq!(members.len(), 1);

        if let NamespaceMember::Package(pkg) = &members[0] {
            let name = pkg.name().unwrap();
            assert_eq!(name.text(), Some("Test".to_string()));
        } else {
            panic!("expected Package");
        }
    }

    #[test]
    fn test_ast_import() {
        let parsed = parse_sysml("import ISQ::*;");
        let root = SourceFile::cast(parsed.syntax()).unwrap();

        let members: Vec<_> = root.members().collect();
        assert_eq!(members.len(), 1);

        if let NamespaceMember::Import(imp) = &members[0] {
            assert!(!imp.is_all());
            assert!(imp.is_wildcard());
            assert!(!imp.is_recursive());
            let target = imp.target().unwrap();
            assert_eq!(target.segments(), vec!["ISQ"]);
        } else {
            panic!("expected Import");
        }
    }

    #[test]
    fn test_ast_import_recursive() {
        let parsed = parse_sysml("import all Library::**;");
        assert!(parsed.ok(), "errors: {:?}", parsed.errors);

        let root = SourceFile::cast(parsed.syntax()).unwrap();

        let members: Vec<_> = root.members().collect();
        if let NamespaceMember::Import(imp) = &members[0] {
            assert!(imp.is_all());
            assert!(imp.is_recursive());
        } else {
            panic!("expected Import");
        }
    }

    #[test]
    fn test_ast_definition() {
        let parsed = parse_sysml("abstract part def Vehicle :> Base;");
        let root = SourceFile::cast(parsed.syntax()).unwrap();

        let members: Vec<_> = root.members().collect();
        if let NamespaceMember::Definition(def) = &members[0] {
            assert!(def.is_abstract());
            assert_eq!(def.definition_kind(), Some(DefinitionKind::Part));
            let name = def.name().unwrap();
            assert_eq!(name.text(), Some("Vehicle".to_string()));

            let specializations: Vec<_> = def.specializations().collect();
            assert_eq!(specializations.len(), 1);
            assert_eq!(
                specializations[0].kind(),
                Some(SpecializationKind::Specializes)
            );
        } else {
            panic!("expected Definition");
        }
    }

    #[test]
    fn test_ast_usage() {
        let parsed = parse_sysml("ref part engine : Engine;");
        let root = SourceFile::cast(parsed.syntax()).unwrap();

        let members: Vec<_> = root.members().collect();
        if let NamespaceMember::Usage(usage) = &members[0] {
            assert!(usage.is_ref());
            let name = usage.name().unwrap();
            assert_eq!(name.text(), Some("engine".to_string()));

            let typing = usage.typing().unwrap();
            let target = typing.target().unwrap();
            assert_eq!(target.segments(), vec!["Engine"]);
        } else {
            panic!("expected Usage");
        }
    }

    #[test]
    fn test_message_usage_name() {
        // Test that message usages extract names correctly
        // Message usages need to be inside a package/part body
        let parsed = parse_sysml("part p { message of ignitionCmd : IgnitionCmd; }");
        let root = SourceFile::cast(parsed.syntax()).unwrap();

        let members: Vec<_> = root.members().collect();

        // Get the usage inside the part
        if let NamespaceMember::Usage(part_usage) = &members[0] {
            if let Some(body) = part_usage.body() {
                let inner_members: Vec<_> = body.members().collect();
                if let NamespaceMember::Usage(usage) = &inner_members[0] {
                    let name = usage.name();
                    assert!(name.is_some(), "message usage should have a name");
                    assert_eq!(name.unwrap().text(), Some("ignitionCmd".to_string()));
                    return;
                }
            }
        }
        panic!("expected Usage for part p with message inside");
    }
}