cpp_parser 0.2.0

A lossless C++ parser over the preprocessed text: the tree every layer above it reads.
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
//! Declaration, type and module nodes.

use crate::{
    CppSyntaxNode,
    kind::{CppKind, CppSyntaxKind, CppTokenKind},
    syntax::traits::{CppAstChildren, CppAstNode, CppAstToken},
};

use super::{CppKeywordToken, CppNameToken, CppPunctuationToken, CppStat};

mod expr;
mod modules;
mod stat;

pub use expr::*;
pub use modules::*;
pub use stat::*;

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

/// The root of a parsed file.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTranslationUnit {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTranslationUnit {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TranslationUnit
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTranslationUnit {
    /// Every top-level declaration and directive, in order.
    ///
    /// Namespaces are *not* included: `namespace ns { ... }` is a [`CppNamespaceDecl`], a different
    /// node kind, so iterate [`CppTranslationUnit::get_namespaces`] for those.
    pub fn get_declarations(&self) -> CppAstChildren<CppDeclaration> {
        self.children()
    }

    /// Every top-level namespace definition, in order.
    pub fn get_namespaces(&self) -> CppAstChildren<CppNamespaceDecl> {
        self.children()
    }

    pub fn get_module_decl(&self) -> Option<CppModuleDecl> {
        self.child()
    }
}

// ============================================================================
// Declarations
// ============================================================================

/// One declaration: `specifiers declarators ;`, a function definition, a class, a namespace, ...
///
/// A single type rather than one per declaration form, because the forms differ only in which child
/// nodes are present. Use the `get_*` accessors — or [`CppDeclaration::kind_name`] — to see which.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDeclaration {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppDeclaration {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    /// Narrow on purpose, unlike [`CppDeclaration::cast`].
    ///
    /// `can_cast` is what [`CppAstChildren`](crate::syntax::traits::CppAstChildren) uses on every step
    /// of an iteration, so widening it would put every `using` directive — including
    /// `using namespace std;`, which declares nothing — into
    /// [`CppTranslationUnit::get_declarations`].
    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::Declaration
    }

    /// Wider than [`CppDeclaration::can_cast`]: it also accepts a `using` alias, which declares a name
    /// but has a shape that is not `specifiers declarators` and therefore its own node kind.
    ///
    /// This is the same asymmetry [`CppEnumDef`] has — a deliberate cast target that is not reachable
    /// by iterating children — and it exists because the two questions differ. "List this file's
    /// declarations" should not be polluted by directives; "what declaration does this comment
    /// document?" must not miss `/// Doc.` in front of `using Point = shapes::Point;`.
    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        // **A `typedef` is a declaration too**: it declares a name, and its declarator layer is the same as any other's. It was
        // excluded for one reason — a `descendants::<CppDeclaration>` walk would then visit it — and the walk uses `can_cast`,
        // which stays narrow, so the exclusion never bought anything.
        matches!(
            CppSyntaxKind::from(syntax.kind()),
            CppSyntaxKind::Declaration | CppSyntaxKind::UsingDecl | CppSyntaxKind::TypedefDecl
        )
        .then_some(Self { syntax })
    }
}

impl CppDeclaration {
    /// The `decl-specifier-seq`: the type and the specifiers.
    pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
        self.child()
    }

    /// **Is this the `typedef` form of a declaration?** — `typedef struct { … } Object;`.
    ///
    /// The parser produces two spellings of it: a `TypedefDecl` node of its own, and a general `Declaration` whose specifiers
    /// begin with the keyword. Both declare the same name, and this is the one question that answers for both.
    pub fn is_a_typedef(&self) -> bool {
        CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::TypedefDecl
            || self
                .get_decl_specifiers()
                .is_some_and(|specifiers| specifiers.has_keyword(CppTokenKind::TypedefKeyword))
    }

    /// Every `init-declarator`. A declaration of several entities has several of these.
    pub fn get_init_declarators(&self) -> CppAstChildren<CppInitDeclarator> {
        self.children()
    }

    /// The first `init-declarator`, which is the one every declaration has.
    pub fn get_init_declarator(&self) -> Option<CppInitDeclarator> {
        self.child()
    }

    /// **The type this declaration writes for the declarator named `name`** — `int*` for the `a` of `int* a, b;`, and `int`
    /// for its `b`.
    ///
    /// A declaration carries one specifier sequence and one or more declarators, and each declarator has its own pointer,
    /// reference and array parts. Answering "what type does this declaration give this name" without slicing the
    /// declaration's text is what this accessor exists for; it is the question a `return` of a local asks.
    pub fn get_type_text_of(&self, name: &str) -> Option<String> {
        let base = self
            .get_decl_specifiers()
            .map(|specifiers| specifiers.get_type_text())
            .unwrap_or_default();
        for declarator in self.get_init_declarators() {
            let declares_it = declarator
                .get_name()
                .is_some_and(|written| written.get_name_text() == name);
            if !declares_it {
                continue;
            }
            let mut the_type = base.clone();
            if let Some(declarator) = declarator.get_declarator() {
                the_type.push_str(&declarator.get_type_suffix());
            }
            let the_type = the_type.trim().to_string();
            if !the_type.is_empty() {
                return Some(the_type);
            }
        }
        None
    }

    /// The name this declaration introduces, if it has one.
    ///
    /// Four places a name can live, and they are tried in order:
    ///
    /// * a class, struct, union or enum definition — the name is on the definition node;
    /// * a namespace — same;
    /// * everything else — the name is the first declarator's;
    /// * a **forward declaration** — `class Widget;` — has no declarator at all, and the name is the type
    ///   written beside the class-like keyword. See [`CppDeclaration::elaborated_type_name`].
    ///
    /// Taken from the first declarator, which is what almost every caller wants. A declaration of
    /// several entities (`int a, b;`) has more — use `get_init_declarators` for those.
    pub fn get_name(&self) -> Option<CppNameToken> {
        // A `using` alias: the name comes before the `=`, so it is the first `NameExpr` child. The
        // target is a second one, nested inside a `TypeId`, which is why this is the *child* search
        // rather than a descendant one.
        if CppSyntaxKind::from(self.syntax.kind()) == CppSyntaxKind::UsingDecl {
            return crate::syntax::node::traits::first_child_of_kind(
                self.syntax(),
                &[CppSyntaxKind::NameExpr],
            )
            .and_then(CppNameExpr::cast)
            .and_then(|name| name.get_name_token());
        }

        if let Some(class) = self.get_class_def()
            && let Some(name) = class.get_name()
        {
            return Some(name);
        }

        if let Some(enum_def) = self.get_enum_def()
            && let Some(name) = enum_def.get_name()
        {
            return Some(name);
        }

        // A forward declaration — `class Widget;` — names the class through its *specifier*: there is no
        // declarator, and the keyword and the name are all the declaration has. It is the elaborated-type-
        // specifier spelling, so the name to report is the type written after the keyword.
        //
        // Checked after the declarator, not before: `class Widget x;` declares the *variable* `x` and mentions
        // `Widget` as its type, and the declarator is the answer there.
        if let Some(declarator) = self.get_init_declarator()
            && let Some(name) = declarator.get_name()
        {
            return Some(name);
        }

        // **A constructor is a bare `Declarator`, not an `InitDeclarator`.** Its declaration has no
        // `decl-specifier-seq` — there is no return type to write — so the grammar puts the name straight under the
        // declaration:
        //
        // ```text
        // Name(const int f);      Declaration > Declarator > NameExpr, ParameterList
        // void set(const int v);  Declaration > DeclSpecifierSeq, InitDeclarator > Declarator
        // ```
        //
        // Without this arm the name is not found and `get_name_text` answers `None` for a declaration that plainly
        // has one — which `sema::scopes`' `is_unnamed_declaration` reads as *"this is a call statement, not a
        // declaration"* and skips entirely. Measured on the pair above: the constructor's parameters were bound
        // **nowhere**, so they were missing from completion and uncoloured by semantic tokens, while the member
        // function's beside them were both right.
        if let Some(declarator) = self.child::<CppDeclarator>()
            && let Some(name) = declarator.get_name()
            && !name.get_text().is_empty()
        {
            return Some(name);
        }

        // **A constructor's declaration wraps a declaration.** The grammar reads the name, the parameter list and the
        // member-initializer list as one declaration, then reopens a declaration around the body with
        // `CompleteMarker::precede` — so the node this is asked about has no declarator of its own and the name lives
        // one level down:
        //
        // ```text
        // Declaration            ← the wrapper, which this is asked about
        //   Declaration          ← the declaration proper: Declarator, MemberInitializer
        //   CompoundStat         ← the body `precede` wrapped it with
        // ```
        //
        // Without this the wrapper has no name, `get_name_text` answers `None`, and `sema::scopes`'
        // `is_unnamed_declaration` reads that as *"this is a call statement, not a declaration"* and skips the whole
        // thing: measured, the tree held only `TranslationUnit` and `Class` — no function scope at all — so a
        // constructor's parameters were bound nowhere and neither its member-initializer list nor its body could see
        // them.
        if let Some(wrapped) = self.child::<CppDeclaration>()
            && let Some(name) = wrapped.get_name()
            && !name.get_text().is_empty()
        {
            return Some(name);
        }

        // **A constructor whose name the specifier sequence holds.** `explicit A(int x) : x_(x) {}` parses
        // `explicit A` as the specifiers — the declarator is `(int x)` and names nothing — so every arm above answers
        // `None` for a declaration that plainly has a name: no fact was made for it (`inspect facts` on
        // `struct A { explicit A(int x); }` listed none), and `missing-return` read it as a function with a return type
        // and reported "declared to return `` and its body has no `return`".
        //
        // The name is the sequence's **last** name, and it is the declaration's own when nothing in the sequence is a
        // type: `explicit`, `inline`, `constexpr`, `virtual` and `friend` are specifiers. Guarded by the parameter
        // list, because only a function-shaped declaration names itself this way (`A A;` writes its name in the
        // declarator and never reaches here).
        if self.get_param_list().is_some()
            && let Some(specifiers) = self.get_decl_specifiers()
            && specifiers.get_builtin_type().is_none()
            && let Some(name) = specifiers
                .descendants::<CppNameExpr>()
                .last()
                .and_then(|name| name.get_name_token())
        {
            return Some(name);
        }

        self.elaborated_type_name()
    }

    /// The class name of an elaborated type specifier: the `Widget` of `class Widget;`.
    ///
    /// `None` for every declaration whose specifiers are not a class-like keyword followed by a name, which is
    /// what keeps this from answering for `class { ... } x;` — an unnamed class with a declarator — or for
    /// `int x;`.
    fn elaborated_type_name(&self) -> Option<CppNameToken> {
        let specifiers = self.get_decl_specifiers()?;

        let builtin = specifiers.get_builtin_type();
        let has_class_keyword = builtin
            .as_ref()
            .is_some_and(|builtin| builtin.is_class_like());
        if !has_class_keyword {
            return None;
        }

        specifiers
            .get_type_name()
            .and_then(|name| name.get_name_token())
    }

    /// The text of the declared name.
    pub fn get_name_text(&self) -> Option<String> {
        self.get_name().map(|it| it.get_name_text().to_string())
    }

    /// A class name without its template arguments — `Box<T>` is `Box`.
    ///
    /// For comparing a constructor's last segment with its class's name: `Box<T>::Box` and `Box` are the same class,
    /// and a comparison of the spellings would say otherwise.
    fn without_template_arguments(written: &str) -> &str {
        match written.find('<') {
            Some(at) => written[..at].trim_end(),
            None => written,
        }
    }

    /// **Is this declaration a constructor or a destructor** — the two functions that promise no return?
    ///
    /// Asked of the **name**, not of the specifier sequence. `explicit A(int x) : x_(x) {}`, `virtual ~A() {}` and
    /// `constexpr C(int x) : x_(x) {}` all carry specifiers (`explicit`, `virtual`, `constexpr` — and the first and
    /// third keep the constructor's own name there), so a rule that asked "does this declaration write a specifier
    /// sequence" answered *"yes: a function returning"* for every one of them. Measured: `missing-return` reported all
    /// three as *"this function is declared to return `` and its body has no `return`"*.
    pub fn promises_no_return(&self) -> bool {
        // **A destructor writes `~` before its name**, wherever the parser kept the name — so the tokens before the
        // first `(` of the declaration are what say it. A `~` inside the body (`p->~T()`) is after that paren and
        // cannot be read here.
        let tilde = self
            .syntax()
            .descendants_with_tokens()
            .filter_map(|element| element.into_token())
            .take_while(|token| CppTokenKind::from(token.kind()) != CppTokenKind::LeftParen)
            .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Tilde);
        if tilde {
            return true;
        }

        // **A constructor's last segment is its class's name** — `A::A`, `ns::A::A`, `Box<T>::Box`. The *qualified*
        // spelling is the declarator's name node when the declaration writes one (an out-of-class definition), and the
        // declared name otherwise (an in-class `explicit A(int)`).
        let written = self
            .get_declarator()
            .or_else(|| self.child::<CppDeclarator>())
            .and_then(|declarator| declarator.child::<CppNameExpr>())
            .map(|name| name.get_qualified_name())
            .filter(|name| !name.trim().is_empty())
            .or_else(|| self.get_name_text());
        let Some(written) = written else {
            return false;
        };
        let written = written.trim();
        let segments: Vec<&str> = written
            .split("::")
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .collect();
        let last = segments
            .last()
            .map(|part| Self::without_template_arguments(part));
        let before = segments
            .len()
            .checked_sub(2)
            .map(|at| Self::without_template_arguments(segments[at]));
        if let (Some(last), Some(before)) = (last, before)
            && last == before
        {
            return true;
        }

        // Inside a class, its own name is the constructor's.
        let enclosing = crate::syntax::node::traits::typed_ancestors::<CppClassDef>(self.syntax())
            .next()
            .and_then(|class| class.get_name_text());
        match (enclosing, last) {
            (Some(class), Some(last)) => Self::without_template_arguments(class.trim()) == last,
            _ => false,
        }
    }

    /// The declarator of the first `init-declarator`.
    pub fn get_declarator(&self) -> Option<CppDeclarator> {
        self.get_init_declarator()?.get_declarator()
    }

    /// The initializer of the first `init-declarator`, if it has one.
    pub fn get_initializer(&self) -> Option<CppInitializer> {
        self.get_init_declarator()?.get_initializer()
    }

    /// The function body, if this declaration is a function definition.
    ///
    /// The body is a direct child of the declaration, not of the declarator: `int f() { ... }` is one
    /// declaration whose last init-declarator is followed by a block.
    pub fn get_body(&self) -> Option<CppCompoundStat> {
        self.child()
    }

    /// **The parameter list this declaration writes**, when it declares a function.
    ///
    /// Asked of the **declarator**, not of the declaration's subtree: a function's body is a child of the declaration, so
    /// `descendants()` over the declaration reaches every lambda in that body and answers *their* parameters as well — measured,
    /// `auto f(int a) { auto g = [](int b) { … }; }` answered two parameters for `f`. A constructor writes its declarator
    /// directly (`S(std::string s)`), which is the second branch.
    pub fn get_param_list(&self) -> Option<CppParamList> {
        self.get_init_declarator()
            .and_then(|init| init.get_declarator())
            .and_then(|declarator| declarator.get_param_list())
            .or_else(|| {
                self.children::<CppDeclarator>()
                    .find_map(|declarator| declarator.get_param_list())
            })
    }

    /// The class, struct, union or enum this declaration defines, if any.
    pub fn get_class_def(&self) -> Option<CppClassDef> {
        self.get_decl_specifiers()?.get_class_def()
    }

    /// The enum this declaration defines, if any.
    ///
    /// A scoped enum (`enum class E`) is parsed as a single `BuiltinType` specifier rather than as an
    /// `EnumDef`, because `class` belongs to the same specifier as `enum` — so the search has to be
    /// by *shape* rather than by direct child. [`CppEnumDef::can_cast`] accepts both node kinds, and
    /// only a node that actually has a body counts as a definition; an elaborated type specifier
    /// (`enum E x;`) has no body and yields `None`.
    pub fn get_enum_def(&self) -> Option<CppEnumDef> {
        self.get_decl_specifiers()?
            .syntax()
            .descendants()
            .filter_map(CppEnumDef::cast)
            .find(|it| it.get_body().is_some())
    }

    pub fn get_namespace_decl(&self) -> Option<CppNamespaceDecl> {
        self.child()
    }

    /// The template head, if this declaration is templated.
    pub fn get_template_decl(&self) -> Option<CppTemplateDecl> {
        self.child()
    }

    /// Is this a function definition (a declarator with a parameter list plus a body)?
    pub fn is_function_def(&self) -> bool {
        self.get_body().is_some() && self.get_declarator().is_some_and(|it| it.is_function())
    }

    /// Is this declaration exported? (`export` is a token, so this is a token test, not a node test.)
    pub fn is_exported(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::ExportKeyword))
    }

    /// Which of the declaration forms this is, for diagnostics and tests.
    ///
    /// A namespace is not one of the answers: `namespace ns { ... }` is a `NamespaceDecl` node, not
    /// a `Declaration`, so it never reaches here — ask the translation unit for namespaces.
    pub fn kind_name(&self) -> &'static str {
        // A `using` alias is its own node kind, reached through `CppDeclaration::cast` for consumers
        // that ask "what does this document?" rather than by iterating declarations. It is an alias
        // for the same reason `using A = B;` is, so it reports the same word.
        if CppSyntaxKind::from(self.syntax.kind()) == CppSyntaxKind::UsingDecl {
            "alias"
        } else if self.get_enum_def().is_some() {
            "enum"
        } else if self.get_class_def().is_some() {
            "class"
        } else if self.get_declarator().is_some_and(|it| it.is_function()) {
            // A parameter list is what makes a declaration a function — a body is only what makes it
            // a *definition*, and `void reset();` is a function declaration.
            "function"
        } else if self.get_decl_specifiers().is_some_and(|it| it.is_alias()) {
            "alias"
        } else {
            "variable"
        }
    }
}

/// The `decl-specifier-seq` of a declaration.
///
/// Deliberately flat: C++ allows the specifiers in almost any order and repeats them freely
/// (`long long unsigned int`), so anything more structured would invent an order the language does
/// not have. Consumers ask for what they want — the base type, the qualifiers, whether it is
/// `static` — through the accessors here.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDeclSpecifierSeq {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppDeclSpecifierSeq {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::DeclSpecifierSeq
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppDeclSpecifierSeq {
    /// **Is the type `void`** — `void f()`, `(void)x`?
    pub fn is_void(&self) -> bool {
        self.has_keyword(CppTokenKind::VoidKeyword)
    }

    /// **Is the type deduced from the initialiser or the returns?** — `auto`, `auto&`, `decltype(auto)`.
    ///
    /// A function declared with one of these promises nothing about what it returns, which is why `missing-return` asks this
    /// rather than comparing a spelling against `"auto"`.
    pub fn is_deduced_return_type(&self) -> bool {
        self.has_keyword(CppTokenKind::AutoKeyword)
            || self.has_keyword(CppTokenKind::DecltypeKeyword)
    }

    /// The built-in type specifier, if the type is a fundamental one (`int`, `const char`, ...).
    pub fn get_builtin_type(&self) -> Option<CppBuiltinType> {
        self.child()
    }

    /// The user-written type name, if the type is a name (`Foo`, `std::vector<int>`).
    ///
    /// Two spellings reach here: a **plain** name is a `NameExpr` child, while a **template-id**
    /// (`std::vector<int>`) is wrapped — in a `NamedType` when it is a plain name and a `TemplateType` when it
    /// carries template arguments. Both are "the name the user wrote", so both are accepted, and the wrapper is
    /// read for either kind: this reader's question is the name, not whether the type was a template-id.
    pub fn get_type_name(&self) -> Option<CppNameExpr> {
        if let Some(name) = self.child::<CppNameExpr>() {
            return Some(name);
        }

        let wrapped = crate::syntax::node::traits::first_child_of_kind(
            self.syntax(),
            &[CppSyntaxKind::TemplateType, CppSyntaxKind::NamedType],
        )?;
        wrapped.children().find_map(CppNameExpr::cast)
    }

    /// The class-like definition this specifier sequence defines, if any.
    pub fn get_class_def(&self) -> Option<CppClassDef> {
        self.child()
    }

    pub fn get_enum_def(&self) -> Option<CppEnumDef> {
        self.child()
    }

    /// The `=` of a `using Alias = type;`.
    pub fn is_alias(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::Assign))
    }

    /// Is one of these keywords present in the specifier sequence?
    /// **The attribute lists written in this specifier sequence** — `[[maybe_unused]] int x;` inside a class body puts the
    /// list here (measured), while at file scope it is a sibling of the declaration.
    pub fn get_attribute_lists(&self) -> CppAstChildren<CppAttributeList> {
        self.children()
    }

    /// Does this declaration say the attribute named `name` — `maybe_unused`, `nodiscard`?
    pub fn has_attribute(&self, name: &str) -> bool {
        self.get_attribute_lists().any(|list| list.has_a_name(name))
    }

    pub fn has_keyword(&self, kind: CppTokenKind) -> bool {
        // **The keyword may sit in a specifier node of its own.** Measured: `static int x` is
        // `DeclSpecifierSeq > [StaticSpec > Token(StaticKeyword), BuiltinType > Token(IntKeyword)]`, so a question about the
        // *sequence's* keywords has to mean its subtree, not its direct children — a direct scan answered `false` for every
        // `static` (which made a static local look automatic) and for `auto` inside a builtin type.
        self.syntax()
            .descendants_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == kind.into())
    }

    pub fn is_const(&self) -> bool {
        self.has_keyword(CppTokenKind::ConstKeyword)
    }

    pub fn is_static(&self) -> bool {
        self.has_keyword(CppTokenKind::StaticKeyword)
    }

    pub fn is_virtual(&self) -> bool {
        self.has_keyword(CppTokenKind::VirtualKeyword)
    }

    /// The text of the whole specifier sequence, trivia removed.
    ///
    /// Useful for presenting a type to a user without building a type model first. Walks the whole
    /// subtree, because the type itself is a child node (`BuiltinType`, `TemplateType`), not a token
    /// of this node.
    pub fn get_type_text(&self) -> String {
        crate::syntax::node::traits::subtree_text_spaced(self.syntax())
    }
}

/// A built-in type specifier: `int`, `const char`, `decltype(x)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppBuiltinType {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppBuiltinType {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::BuiltinType
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppBuiltinType {
    /// The keyword, if the specifier is a single keyword.
    pub fn get_keyword(&self) -> Option<CppKeywordToken> {
        self.token()
    }

    pub fn get_type_text(&self) -> String {
        crate::syntax::node::traits::subtree_text_spaced(self.syntax())
    }

    /// Is this specifier a class-like keyword — `class`, `struct`, `union` or `enum`?
    ///
    /// Asked by callers that need to tell an **elaborated type specifier** — `class Widget;`, where the keyword
    /// names a kind of type and the name after it is the type — from every other use of those keywords, where a
    /// body or a base clause follows and the keyword is the head of a definition.
    pub fn is_class_like(&self) -> bool {
        matches!(
            self.syntax()
                .children_with_tokens()
                .next()
                .and_then(|element| element.into_token())
                .map(|token| token.kind()),
            Some(CppKind::Token(CppTokenKind::ClassKeyword))
                | Some(CppKind::Token(CppTokenKind::StructKeyword))
                | Some(CppKind::Token(CppTokenKind::UnionKeyword))
                | Some(CppKind::Token(CppTokenKind::EnumKeyword))
        )
    }
}

/// The `type-id` of a cast, `sizeof`, parameter or template argument.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTypeId {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTypeId {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::TypeId | CppSyntaxKind::TrailingReturnType
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTypeId {
    /// **Is this type spelled `void`** — `(void)expr`, the cast that discards its operand?
    pub fn is_void(&self) -> bool {
        self.get_decl_specifiers()
            .is_some_and(|specifiers| specifiers.has_keyword(CppTokenKind::VoidKeyword))
    }

    pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
        self.child()
    }

    pub fn get_type_text(&self) -> String {
        let text = self.syntax().text().to_string();
        text.split_whitespace().collect::<Vec<_>>().join(" ")
    }
}

/// A `declarator`: the part that names the entity, possibly wrapped in pointers, references, arrays,
/// function parameter lists and template argument lists.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDeclarator {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppDeclarator {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::Declarator
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppDeclarator {
    /// The declared name.
    ///
    /// Found among the child nodes rather than the direct tokens: a qualified or templated name
    /// (`ns::Foo<int>`) is itself a node, so the identifier is one level down.
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.token().or_else(|| {
            self.child::<CppNameExpr>()
                .and_then(|it| it.get_name_token())
        })
    }

    pub fn get_name_text(&self) -> Option<String> {
        self.get_name().map(|it| it.get_name_text().to_string())
    }

    /// **The pointer and reference types this declarator writes**, its nested declarators' included.
    ///
    /// `int* p` is `Declarator > Declarator > PointerType` (measured), so a one-level search finds nothing; a declaration's own
    /// type parts are the chain of `PointerType`/`ReferenceType`/`RValueReferenceType` nodes under it.
    pub fn get_pointer_types(&self) -> Vec<CppPointerType> {
        let mut found = Vec::new();
        let mut current = Some(self.clone());
        while let Some(declarator) = current {
            for child in declarator.syntax().children() {
                if let Some(pointer) = CppPointerType::cast(child) {
                    found.push(pointer);
                }
            }
            current = declarator.child::<CppDeclarator>();
        }
        found
    }

    /// Is this the declarator of a **reference** — `int& r`, `int&& rr`?
    pub fn is_a_reference(&self) -> bool {
        self.get_pointer_types()
            .iter()
            .any(|pointer| pointer.is_reference())
    }

    /// Is this the declarator of a **pointer** — `int* p`? A pointer-to-a-reference is not a C++ type, so the two answers
    /// cannot both be true for one declarator in practice; the reference is checked first by the callers that care.
    pub fn is_a_pointer(&self) -> bool {
        self.get_pointer_types()
            .iter()
            .any(|pointer| !pointer.is_reference())
    }

    /// **The declarator's type parts, without its name**: `*`, `&`, `&&`, `[3]`, in source order.
    ///
    /// What a type spelling needs from a declarator. The name is the declarator's own and not part of the type, and the
    /// parameter list of a function declarator is a signature rather than a type.
    pub fn get_type_suffix(&self) -> String {
        let mut out = String::new();
        for element in self.syntax().children_with_tokens() {
            match element {
                rowan::NodeOrToken::Node(child) => match CppSyntaxKind::from(child.kind()) {
                    // `CppPointerType` covers all three of `*`, `&` and `&&`.
                    CppSyntaxKind::PointerType
                    | CppSyntaxKind::ReferenceType
                    | CppSyntaxKind::RValueReferenceType => {
                        if let Some(pointer) = CppPointerType::cast(child) {
                            out.push_str(&pointer.get_operator_text());
                        }
                    }
                    CppSyntaxKind::ArrayType => {
                        if let Some(array) = CppArrayType::cast(child) {
                            out.push_str(&array.get_type_text());
                        }
                    }
                    // **A nested declarator is where a pointer lives**: `int* p` is `Declarator > Declarator > PointerType`,
                    // measured, so the outer level has to hand the question down rather than answer nothing.
                    CppSyntaxKind::Declarator => {
                        if let Some(inner) = CppDeclarator::cast(child) {
                            out.push_str(&inner.get_type_suffix());
                        }
                    }
                    _ => {}
                },
                rowan::NodeOrToken::Token(token) => match token.kind() {
                    CppKind::Token(CppTokenKind::Star)
                    | CppKind::Token(CppTokenKind::Ampersand)
                    | CppKind::Token(CppTokenKind::LogicalAnd) => {
                        out.push_str(token.text());
                    }
                    _ => {}
                },
            }
        }
        out
    }

    /// The full spelling of this declarator including the name, trivia removed.
    pub fn get_declarator_text(&self) -> String {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| !crate::syntax::node::traits::is_trivia(token.kind().into()))
            .map(|token| token.text().to_string())
            .collect::<Vec<_>>()
            .join("")
            .chars()
            .filter(|it| !it.is_whitespace())
            .collect()
    }

    /// The parameter list, if this declarator declares a function.
    pub fn get_param_list(&self) -> Option<CppParamList> {
        self.child()
    }

    /// The trailing return type after `->`, if this declarator has one.
    ///
    /// The returned node is the `TypeId` inside the `TrailingReturnType` wrapper, so its text is the
    /// type as written (`int*`) and does not include the `->`.
    pub fn get_trailing_return_type(&self) -> Option<CppTypeId> {
        let wrapper = crate::syntax::node::traits::first_child_of_kind(
            self.syntax(),
            &[CppSyntaxKind::TrailingReturnType],
        );

        match wrapper {
            Some(wrapper) => wrapper.children().find_map(CppTypeId::cast),
            // A grammar that puts the `TypeId` directly under the declarator is still understood.
            None => crate::syntax::node::traits::first_child_of_kind(
                self.syntax(),
                &[CppSyntaxKind::TypeId],
            )
            .and_then(CppTypeId::cast),
        }
    }

    /// The first pointer/reference operator, if any.
    pub fn get_pointer_type(&self) -> Option<CppPointerType> {
        self.child()
    }

    /// Is this a function declarator?
    ///
    /// True when there is a parameter list or a trailing return type. This is the test that decides
    /// whether a following `{` is a function body or a brace initializer.
    pub fn is_function(&self) -> bool {
        self.get_param_list().is_some() || self.get_trailing_return_type().is_some()
    }

    /// Is this an array declarator?
    pub fn is_array(&self) -> bool {
        self.get_array_type().is_some()
    }

    pub fn get_array_type(&self) -> Option<CppArrayType> {
        self.child()
    }

    /// The structured binding this declarator introduces, if it is one: the `[a, b]` of
    /// `auto [a, b] = pair;`.
    ///
    /// Two shapes reach here, because the `&` of `auto& [k, v]` is an abstract declarator and the
    /// pattern comes after it: the `StructuredBinding` is either a child of this declarator or a
    /// child of the `InitDeclarator` beside it. Both are searched, so a caller asking "is this a
    /// binding?" gets one answer rather than having to know which spelling produced the node.
    pub fn get_structured_binding(&self) -> Option<CppStructuredBinding> {
        if let Some(binding) = self.child::<CppStructuredBinding>() {
            return Some(binding);
        }

        self.syntax()
            .parent()
            .and_then(|parent| {
                crate::syntax::node::traits::first_child_of_kind(
                    &parent,
                    &[CppSyntaxKind::StructuredBinding],
                )
            })
            .and_then(CppStructuredBinding::cast)
    }

    /// Is this a structured binding declarator?
    pub fn is_structured_binding(&self) -> bool {
        self.get_structured_binding().is_some()
    }

    /// The names a structured binding introduces. Empty for an ordinary declarator.
    pub fn get_binding_names(&self) -> Vec<CppNameToken> {
        self.get_structured_binding()
            .map(|binding| binding.get_names().collect())
            .unwrap_or_default()
    }
}

/// A structured binding's name list: the `[a, b]` of `auto [a, b] = pair;`.
///
/// The names are `NameExpr` children rather than declarators, because that is the node a name
/// reference gets — so "which names does this declaration introduce?" is one query over one kind.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppStructuredBinding {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppStructuredBinding {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::StructuredBinding
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppStructuredBinding {
    /// The identifiers bound, in order.
    ///
    /// A pack expansion (`[... xs]`) contributes the names it names and nothing for the `...`: what it
    /// expands to is a semantic question, and a syntactic layer that guessed would be wrong for every
    /// pack whose size is not yet known.
    pub fn get_names(&self) -> impl Iterator<Item = CppNameToken> {
        self.syntax()
            .descendants()
            .filter_map(CppNameExpr::cast)
            .filter_map(|name| name.get_name_token())
    }

    /// The names as text.
    pub fn get_name_texts(&self) -> Vec<String> {
        self.get_names()
            .map(|name| name.get_name_text().to_string())
            .collect()
    }

    /// How many names the pattern binds.
    pub fn len(&self) -> usize {
        self.get_names().count()
    }

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

    /// Is any of the names a pack expansion (`...`)?
    pub fn is_pack_expansion(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::Ellipsis))
    }
}

/// An `init-declarator`: a declarator plus an optional initializer.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppInitDeclarator {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppInitDeclarator {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::InitDeclarator
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppInitDeclarator {
    pub fn get_declarator(&self) -> Option<CppDeclarator> {
        self.child()
    }

    pub fn get_name(&self) -> Option<CppNameToken> {
        // A structured binding has no single name: `auto [a, b] = pair;` declares two. The declarator
        // is where the pattern lives, so this answers with the first of them rather than with the
        // rendered pattern, and [`CppDeclarator::get_binding_names`] is the accessor for all of them.
        if let Some(binding) = self.get_structured_binding() {
            return binding.get_names().next();
        }

        self.get_declarator()?.get_name()
    }

    /// **The `requires`-clause written after the declarator**, when the declaration has one.
    ///
    /// `void constrained(int x) const requires (x > 0) {}` is an `InitDeclarator` holding the declarator (with its
    /// `const`) and a `RequiresClause` after it, so the clause is this node's sibling rather than part of the declarator.
    pub fn get_requires_clause(&self) -> Option<CppRequiresClause> {
        self.child()
    }

    pub fn get_initializer(&self) -> Option<CppInitializer> {
        self.child()
    }

    /// The structured binding this init-declarator introduces, in either spelling.
    ///
    /// `auto [a, b] = pair;` puts the pattern directly under the init-declarator, while
    /// `auto& [k, v] = map;` puts it inside the declarator, after the `&`. This is the one place that
    /// knows both, so a caller asking "is this a binding?" gets one answer.
    pub fn get_structured_binding(&self) -> Option<CppStructuredBinding> {
        if let Some(binding) = self.child::<CppStructuredBinding>() {
            return Some(binding);
        }

        self.get_declarator()?.get_structured_binding()
    }

    pub fn is_structured_binding(&self) -> bool {
        self.get_structured_binding().is_some()
    }
}

/// What follows `=`, or a brace-or-equal initializer.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppInitializer {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppInitializer {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::Initializer
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppInitializer {
    /// The initializing expression, if it is an expression rather than a braced list.
    pub fn get_expr(&self) -> Option<CppExpr> {
        self.child()
    }

    /// The braced initializer list, if this is `{...}`.
    pub fn get_init_list(&self) -> Option<CppInitListExpr> {
        self.child()
    }
}

/// A pointer or reference operator in a declarator.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppPointerType {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppPointerType {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::PointerType
                | CppSyntaxKind::ReferenceType
                | CppSyntaxKind::RValueReferenceType
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppPointerType {
    pub fn is_rvalue_reference(&self) -> bool {
        CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::RValueReferenceType
    }

    pub fn is_reference(&self) -> bool {
        matches!(
            CppSyntaxKind::from(self.syntax().kind()),
            CppSyntaxKind::ReferenceType | CppSyntaxKind::RValueReferenceType
        )
    }

    /// The `*`, `&` or `&&` this pointer type is written with.
    ///
    /// Asked by **token kind**, which is what the grammar guarantees: the token *class* is a lexer's classification, and a
    /// `*` is an operator rather than punctuation — a `CppPunctuationToken` cast of it answers `None`.
    pub fn get_operator_text(&self) -> String {
        for kind in [
            CppTokenKind::Star,
            CppTokenKind::Ampersand,
            CppTokenKind::LogicalAnd,
        ] {
            if let Some(token) = self.token_by_kind(kind) {
                return token.get_text().to_string();
            }
        }
        String::new()
    }

    pub fn get_operator_token(&self) -> Option<CppPunctuationToken> {
        self.token()
    }
}

/// An array declarator: `arr[10]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppArrayType {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppArrayType {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::ArrayType
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppArrayType {
    /// The array bound, if it is written. `int a[]` has none.
    pub fn get_size_expr(&self) -> Option<CppExpr> {
        self.child()
    }

    /// The array part of a spelling — `[3]`, `[]`, `[N + 1]` — with trivia dropped, so a type reads `int[3]`.
    pub fn get_type_text(&self) -> String {
        crate::syntax::node::traits::subtree_text(self.syntax())
    }
}

/// **Append a spelling to a type being composed**, with a space only where two word-like tokens would otherwise merge.
///
/// The one rule a token walk needs to produce `const std::string&` and `int*` from the same code: `unsigned` `char` keeps the
/// space, `int` `*` does not, and `std` `::` does not either.
fn push_a_spelling(out: &mut String, spelling: &str) {
    let word_like = |character: char| character.is_alphanumeric() || character == '_';
    if out.chars().next_back().is_some_and(word_like)
        && spelling.chars().next().is_some_and(word_like)
    {
        out.push(' ');
    }
    out.push_str(spelling);
}

/// A trailing return type: the `-> Widget` of `auto make() -> Widget`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTrailingReturnType {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTrailingReturnType {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TrailingReturnType
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTrailingReturnType {
    /// The type after the arrow.
    pub fn get_type_id(&self) -> Option<CppTypeId> {
        self.child()
    }
}

/// A `friend` declaration: `friend class B;`, `friend void f();`, `friend std::ostream& operator<<(…);`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppFriendDecl {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppFriendDecl {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::FriendDecl
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppFriendDecl {
    /// The declaration the `friend` introduces — `friend class B;` wraps `class B;`.
    pub fn get_declaration(&self) -> Option<CppDeclaration> {
        self.child()
    }

    /// **The name this friendship grants** — `B` for `friend class B;`, `f` for `friend void f();`.
    pub fn get_name_text(&self) -> Option<String> {
        self.get_declaration()?.get_name_text()
    }
}

/// One entry of a constructor's member-initializer list: `: v(s)`, `: v{s}`, `: Base(args)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppMemberInitializer {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppMemberInitializer {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::MemberInitializer
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppMemberInitializer {
    /// The member (or base) this initialises.
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.child::<CppNameExpr>()?.get_name_token()
    }

    pub fn get_name_text(&self) -> Option<String> {
        self.get_name().map(|name| name.get_name_text().to_string())
    }

    /// **The expression it initialises with** — `s` in `: v(s)`, and the braced element in `: v{s}`.
    pub fn get_argument(&self) -> Option<CppExpr> {
        if let Some(list) = self.child::<CppArgList>() {
            return list.get_args().next();
        }
        if let Some(braced) = self.child::<CppInitListExpr>() {
            return braced.get_elements().next();
        }
        self.children::<CppExpr>().next()
    }
}

/// A requires-expression: `requires (T value) { value.size(); }` — a **question** about a type, not a definition.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppRequiresExpr {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppRequiresExpr {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::RequiresExpr
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

/// A `requires`-clause: `requires (x > 0)`, `requires std::integral<T>`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppRequiresClause {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppRequiresClause {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::RequiresClause
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppRequiresClause {
    /// The clause **as the file spells it**, keyword included — what a card prints after a signature.
    pub fn get_clause_text(&self) -> String {
        crate::syntax::node::traits::subtree_text_spaced(self.syntax())
    }
}

/// An attribute list: `[[maybe_unused]]`, `[[nodiscard("why")]]`, `[[gnu::always_inline]]`.
///
/// The layer names it so that a caller can ask **whether a declaration says an attribute** instead of searching the text in
/// front of it — and so that the walk over several lists (`[[a]] [[b]] int x;`) is a sibling walk rather than a string scan.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppAttributeList {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppAttributeList {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::AttributeList
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppAttributeList {
    /// Every name the list writes — `maybe_unused` for `[[maybe_unused]]`, and both halves of `[[gnu::always_inline]]`.
    ///
    /// The identifiers are the list's own tokens; a namespace prefix (`gnu::`) is a name of its own, which is what a caller
    /// matching a whole attribute spelling needs to see.
    pub fn get_names(&self) -> Vec<String> {
        self.syntax()
            .descendants_with_tokens()
            .filter_map(|element| element.into_token())
            .filter(|token| token.kind() == CppKind::Token(CppTokenKind::Identifier))
            .map(|token| token.text().to_string())
            .collect()
    }

    /// Does the list name this attribute?
    pub fn has_a_name(&self, name: &str) -> bool {
        self.get_names().iter().any(|known| known == name)
    }
}

/// A function parameter list, including its parentheses.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppParamList {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppParamList {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::ParameterList
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppParamList {
    pub fn get_params(&self) -> CppAstChildren<CppParam> {
        self.children()
    }

    /// Is the list `(...)` — an old-style variadic function?
    pub fn is_variadic(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::Ellipsis))
    }
}

/// One function parameter.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppParam {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppParam {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::Parameter
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppParam {
    pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
        self.child()
    }

    pub fn get_declarator(&self) -> Option<CppDeclarator> {
        self.child()
    }

    /// The parameter name. Unnamed parameters (`void f(int)`) have none.
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.get_declarator()?.get_name()
    }

    /// The parameter's name as text, for comparing one name against another.
    pub fn get_name_text(&self) -> Option<String> {
        self.get_name().map(|name| name.get_name_text().to_string())
    }

    /// **Is this parameter written `auto`** — the placeholder of a generic lambda (`[](auto v) { … }`)?
    ///
    /// Asked by **token kind**, and of the tokens written **before the declarator**, because that is where a type goes: the
    /// parameter's own `auto` is a token beside the declarator rather than inside a specifier node (measured:
    /// `Parameter "auto v" > [Declarator "v"]`, with `auto` a token child), so a `DeclSpecifierSeq` search alone would miss
    /// it.
    pub fn is_auto(&self) -> bool {
        // **The keyword lives inside the builtin type**, not as a direct token of the specifier sequence: measured,
        // `Parameter > [DeclSpecifierSeq > BuiltinType > Token(AutoKeyword), Declarator]`. `has_keyword` asks the specifier's
        // own children and therefore misses it, which is why this asks the builtin type's keyword.
        self.get_decl_specifiers()
            .and_then(|specifiers| specifiers.get_builtin_type())
            .and_then(|builtin| builtin.get_keyword())
            .is_some_and(|keyword| {
                keyword.get_keyword_kind() == CppKind::Token(CppTokenKind::AutoKeyword)
            })
    }

    /// **The type this parameter is written with**, as the file spells it: `const std::string&` for
    /// `const std::string& name`, `int*` for `int* p`, `int` for `int`.
    ///
    /// Composed from the tree — the specifier sequence's own type text and the declarator's pointer, reference and array
    /// parts — rather than by cutting the parameter's text at its name. The cut is wrong for a name that occurs in the type as
    /// well (`int int_`), and it has to decide what to do with a default value and a pack expansion.
    pub fn get_type_text(&self) -> String {
        let mut the_type = String::new();
        for element in self.syntax().children_with_tokens() {
            match element {
                rowan::NodeOrToken::Node(child) => {
                    // **The declarator's type parts and then nothing**: what follows a declarator is a default value or a
                    // trailing qualifier, neither of which is the type.
                    if let Some(declarator) = CppDeclarator::cast(child.clone()) {
                        the_type.push_str(&declarator.get_type_suffix());
                        break;
                    }
                    if let Some(specifiers) = CppDeclSpecifierSeq::cast(child) {
                        push_a_spelling(&mut the_type, &specifiers.get_type_text());
                    }
                }
                rowan::NodeOrToken::Token(token) => {
                    if !crate::syntax::node::traits::is_trivia(token.kind().into()) {
                        push_a_spelling(&mut the_type, token.text());
                    }
                }
            }
        }
        the_type.trim().to_string()
    }

    pub fn get_default_value(&self) -> Option<CppInitializer> {
        self.child()
    }
}

// ============================================================================
// Class-like definitions
// ============================================================================

/// A class, struct or union definition: `class Foo : public Bar { ... };`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppClassDef {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppClassDef {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::ClassDef | CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppClassDef {
    /// The class name. Anonymous classes have none.
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.child::<CppNameExpr>()
            .and_then(|it| it.get_name_token())
    }

    pub fn get_name_text(&self) -> Option<String> {
        self.get_name().map(|it| it.get_name_text().to_string())
    }

    pub fn is_struct(&self) -> bool {
        CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::StructDef
    }

    pub fn is_union(&self) -> bool {
        CppSyntaxKind::from(self.syntax().kind()) == CppSyntaxKind::UnionDef
    }

    /// The body, including its access specifier sections.
    pub fn get_body(&self) -> Option<CppClassBody> {
        self.child()
    }

    /// The base classes.
    pub fn get_base_specifiers(&self) -> CppAstChildren<CppBaseSpecifier> {
        self.children()
    }
}

/// The `{ ... }` of a class definition.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppClassBody {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppClassBody {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::ClassBody
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppClassBody {
    /// The member declarations of the class.
    pub fn get_members(&self) -> CppAstChildren<CppDeclaration> {
        self.children()
    }

    /// The access specifier sections: `public:`, `private:`, `protected:`.
    pub fn get_access_specifiers(&self) -> Vec<CppAccessSpecifier> {
        self.syntax()
            .children()
            .filter_map(CppAccessSpecifier::cast)
            .collect()
    }
}

/// An access specifier section header: `public:`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppAccessSpecifier {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppAccessSpecifier {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::PublicAccess
                | CppSyntaxKind::PrivateAccess
                | CppSyntaxKind::ProtectedAccess
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppAccessSpecifier {
    pub fn get_keyword(&self) -> Option<CppKeywordToken> {
        self.token()
    }
}

/// A base class in a class definition's base clause.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppBaseSpecifier {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppBaseSpecifier {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::BaseSpecifier
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppBaseSpecifier {
    pub fn get_name(&self) -> Option<CppNameExpr> {
        self.child()
    }

    pub fn is_virtual(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::VirtualKeyword))
    }

    pub fn get_access(&self) -> Option<CppAccessSpecifier> {
        self.child()
    }
}

/// An enum definition: `enum class Color : int { Red, Green };`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppEnumDef {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppEnumDef {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        matches!(
            kind,
            CppSyntaxKind::EnumDef | CppSyntaxKind::EnumClassDef | CppSyntaxKind::BuiltinType
        )
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppEnumDef {
    /// The `{ ... }` body holding the enumerators, if this really is an enum definition.
    ///
    /// This is what separates `enum class E { ... }` from an elaborated type specifier such as
    /// `enum E x;`: both are `BuiltinType` nodes, and only one of them defines anything.
    pub fn get_body(&self) -> Option<CppSyntaxNode> {
        self.syntax()
            .children()
            .find(|it| CppSyntaxKind::from(it.kind()) == CppSyntaxKind::CompoundStat)
    }

    /// The `enum` keyword, if this node really is an enum.
    pub fn get_enum_keyword(&self) -> Option<CppKeywordToken> {
        self.syntax()
            .descendants_with_tokens()
            .filter_map(|it| it.into_token())
            .filter_map(CppKeywordToken::cast)
            .find(|it| it.get_keyword_kind() == CppKind::Token(CppTokenKind::EnumKeyword))
    }

    /// The enum's name.
    ///
    /// Searched as a subtree: `enum class E` is parsed as one `BuiltinType` specifier (the `class`
    /// belongs to the same specifier as `enum`), so the name sits one level down.
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.get_enum_keyword()?;
        self.syntax()
            .descendants()
            .find_map(CppNameExpr::cast)
            .and_then(|it| it.get_name_token())
    }

    /// Is this a scoped enum (`enum class` / `enum struct`)?
    pub fn is_scoped(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| {
                matches!(
                    token.kind(),
                    CppKind::Token(CppTokenKind::ClassKeyword)
                        | CppKind::Token(CppTokenKind::StructKeyword)
                )
            })
    }

    /// Every enumerator, in order.
    ///
    /// The enumerators live inside the body node rather than directly under the enum, so this walks
    /// one level down instead of using `children()` — which is why it needs `first_child_of_kind`
    /// rather than `child::<N>()`: the body is a `CompoundStat`, the same kind a block statement
    /// uses, so there is no distinct type to ask for.
    pub fn get_enumerators(&self) -> impl Iterator<Item = CppEnumerator> {
        crate::syntax::node::traits::first_child_of_kind(
            self.syntax(),
            &[CppSyntaxKind::CompoundStat],
        )
        .into_iter()
        .flat_map(|body| CppAstChildren::<CppEnumerator>::new(&body))
    }
}

/// One enumerator: `Red` or `Green = 2`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppEnumerator {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppEnumerator {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::EnumeratorDecl
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppEnumerator {
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.token()
    }

    pub fn get_value_expr(&self) -> Option<CppExpr> {
        self.child()
    }
}

// ============================================================================
// Namespaces and templates
// ============================================================================

/// A namespace definition or an alias: `namespace a { ... }`, `namespace fs = std::filesystem;`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppNamespaceDecl {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppNamespaceDecl {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::NamespaceDecl
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppNamespaceDecl {
    pub fn get_name(&self) -> Option<CppNameExpr> {
        self.child()
    }

    /// **The name this namespace declares** — `ns` for `namespace ns { … }`, the last segment for `namespace a::b { … }`.
    ///
    /// `None` for the unnamed namespace, which declares none.
    pub fn get_name_text(&self) -> Option<String> {
        let name = self.get_name()?;
        Some(name.syntax().text().to_string().trim().to_string())
    }

    /// Everything declared inside the namespace, in order.
    ///
    /// The sum type rather than [`CppDeclaration`], because a namespace body holds more than plain
    /// declarations: `template <...> class Grid { ... };` is a `TemplateDecl` at this level, and
    /// asking for `CppDeclaration` alone silently drops every template in the namespace.
    ///
    /// `namespace ns { ... }` holds a `CompoundStat` body, because a namespace body is
    /// grammatically a block and C++ makes declarations a kind of statement. This walks one level
    /// down so callers do not have to.
    pub fn get_declarations(&self) -> impl Iterator<Item = CppStat> {
        self.get_body()
            .into_iter()
            .flat_map(|body| body.get_stats())
    }

    /// The body block, if this is a definition rather than an alias.
    pub fn get_body(&self) -> Option<CppCompoundStat> {
        self.child()
    }

    /// Is this `namespace name = target;`?
    pub fn is_alias(&self) -> bool {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| token.kind() == CppKind::Token(CppTokenKind::Assign))
    }
}

/// A template head: `template <typename T, int N>`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTemplateDecl {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTemplateDecl {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TemplateDecl
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTemplateDecl {
    pub fn get_param_list(&self) -> Option<CppTemplateParamList> {
        self.child()
    }

    /// Is this `template <>` — an explicit specialization?
    pub fn is_explicit_specialization(&self) -> bool {
        self.get_param_list().is_none()
    }
}

/// A template parameter list, including its angle brackets.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTemplateParamList {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTemplateParamList {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TemplateParameterList
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTemplateParamList {
    pub fn get_params(&self) -> CppAstChildren<CppTemplateParam> {
        self.children()
    }
}

/// One template parameter.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTemplateParam {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTemplateParam {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TemplateParameter
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTemplateParam {
    pub fn get_decl_specifiers(&self) -> Option<CppDeclSpecifierSeq> {
        self.child()
    }

    /// The parameter's name — `T` in `typename T`, `N` in `int N`, `Args` in `class... Args`.
    ///
    /// **Two shapes, one question.** A non-type parameter is a declaration and names itself through its declarator
    /// (`int N`); a type parameter has no declarator at all — `typename T` is a specifier holding `T` as a name — so the
    /// declarator search answered `None` for every type parameter, and a hover rendered
    /// `template <typename T, typename Alloc = int>` as `template <typename, typename = int>`. The fallback is the
    /// **first** name in the subtree: the parameter's own name precedes its default's (`typename Alloc = std::allocator<T>`
    /// names `Alloc` first), and `T` in that default is a different question.
    pub fn get_name(&self) -> Option<CppNameToken> {
        self.get_declarator()
            .and_then(|declarator| declarator.get_name())
            .or_else(|| {
                self.syntax()
                    .descendants()
                    .find_map(CppNameExpr::cast)
                    .and_then(|name| name.get_name_token())
            })
    }

    pub fn get_declarator(&self) -> Option<CppDeclarator> {
        self.child()
    }

    /// Is this `typename T` / `class T`?
    ///
    /// **Searched as a subtree**: the keyword is inside the parameter's `DeclSpecifierSeq`
    /// (`TemplateParameter > DeclSpecifierSeq > TypenameType > TypenameKeyword`), not a direct token of it — so the
    /// child-token search answered `false` for every type parameter, and a hover that asked it rendered
    /// `template <typename T, typename Alloc = int>` as `template <T, Alloc = int>`. Measured with `inspect hover`
    /// on a fixture. `concept` is a type parameter's keyword too, in a constrained one.
    pub fn is_type_param(&self) -> bool {
        self.syntax()
            .descendants_with_tokens()
            .filter_map(|it| it.into_token())
            .any(|token| {
                matches!(
                    token.kind(),
                    CppKind::Token(CppTokenKind::TypenameKeyword)
                        | CppKind::Token(CppTokenKind::ClassKeyword)
                )
            })
    }
}

/// A template argument list, including its angle brackets.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTemplateArgList {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTemplateArgList {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TemplateArgumentList
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTemplateArgList {
    pub fn get_args(&self) -> CppAstChildren<CppTemplateArg> {
        self.children()
    }
}

/// One template argument: a type or a constant expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppTemplateArg {
    syntax: CppSyntaxNode,
}

impl CppAstNode for CppTemplateArg {
    fn syntax(&self) -> &CppSyntaxNode {
        &self.syntax
    }

    fn can_cast(kind: CppSyntaxKind) -> bool {
        kind == CppSyntaxKind::TemplateArgument
    }

    fn cast(syntax: CppSyntaxNode) -> Option<Self> {
        Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
    }
}

impl CppTemplateArg {
    pub fn get_type_id(&self) -> Option<CppTypeId> {
        self.child()
    }

    pub fn get_expr(&self) -> Option<CppExpr> {
        self.child()
    }
}