brink-syntax 0.0.16

Syntax types and parser for inkle's ink narrative scripting language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
//! Typed AST node wrappers for every node kind in the ink CST.
//!
//! Each struct is a zero-cost newtype around [`SyntaxNode`] generated by
//! [`ast_node!`]. Structs with hand-written accessors have `impl` blocks
//! below their definition.

use crate::SyntaxKind::{
    self, AMP, AMP_AMP, BANG, BANG_EQ, BANG_QUESTION, CARET, COLON, DIVERT, DOLLAR, EQ, EQ_EQ,
    FLOAT, GT, GT_EQ, HASH, IDENT, INTEGER, KW_AND, KW_CYCLE, KW_DONE, KW_ELSE, KW_END, KW_FALSE,
    KW_FUNCTION, KW_HAS, KW_HASNT, KW_MOD, KW_NOT, KW_ONCE, KW_OR, KW_REF, KW_SHUFFLE, KW_STOPPING,
    KW_TODO, KW_TRUE, L_PAREN, LT, LT_EQ, MINUS, MINUS_EQ, NEWLINE, PERCENT, PIPE, PLUS, PLUS_EQ,
    QUESTION, R_PAREN, SLASH, STAR, TILDE,
};
use crate::ast::AstNode as _;
use crate::ast::ast_node;
use crate::ast::support;
use crate::{SyntaxNode, SyntaxToken};

// ── Top-level ────────────────────────────────────────────────────────

ast_node!(SourceFile, SOURCE_FILE);
ast_node!(IncludeStmt, INCLUDE_STMT);
ast_node!(ImportStmt, IMPORT_STMT);
ast_node!(ImportList, IMPORT_LIST);
ast_node!(ImportItem, IMPORT_ITEM);
ast_node!(ImportModule, IMPORT_MODULE);
ast_node!(FilePath, FILE_PATH);
ast_node!(ExternalDecl, EXTERNAL_DECL);

// ── Knots & stitches ─────────────────────────────────────────────────

ast_node!(KnotDef, KNOT_DEF);
ast_node!(KnotHeader, KNOT_HEADER);
ast_node!(KnotBody, KNOT_BODY);
ast_node!(KnotParams, KNOT_PARAMS);
ast_node!(KnotParamDecl, KNOT_PARAM_DECL);
ast_node!(StitchDef, STITCH_DEF);
ast_node!(StitchHeader, STITCH_HEADER);
ast_node!(StitchBody, STITCH_BODY);

// ── Lines ────────────────────────────────────────────────────────────

ast_node!(EmptyLine, EMPTY_LINE);
ast_node!(AuthorWarning, AUTHOR_WARNING);
ast_node!(LogicLine, LOGIC_LINE);
ast_node!(ContentLine, CONTENT_LINE);
ast_node!(TagLine, TAG_LINE);
ast_node!(AnnotationLine, ANNOTATION_LINE);
ast_node!(StrayClosingBrace, STRAY_CLOSING_BRACE);

// ── Logic ────────────────────────────────────────────────────────────

ast_node!(ReturnStmt, RETURN_STMT);
ast_node!(TempDecl, TEMP_DECL);
ast_node!(Assignment, ASSIGNMENT);
ast_node!(AwaitStmt, AWAIT_STMT);

// ── Content ──────────────────────────────────────────────────────────

ast_node!(MixedContent, MIXED_CONTENT);
ast_node!(Text, TEXT);
ast_node!(Escape, ESCAPE);
ast_node!(GlueNode, GLUE_NODE);

// ── Choices ──────────────────────────────────────────────────────────

ast_node!(Choice, CHOICE);
ast_node!(ChoiceBullets, CHOICE_BULLETS);
ast_node!(Label, LABEL);
ast_node!(ChoiceCondition, CHOICE_CONDITION);
ast_node!(ChoiceStartContent, CHOICE_START_CONTENT);
ast_node!(ChoiceBracketContent, CHOICE_BRACKET_CONTENT);
ast_node!(ChoiceInnerContent, CHOICE_INNER_CONTENT);

// ── Gathers ──────────────────────────────────────────────────────────

ast_node!(Gather, GATHER);
ast_node!(GatherDashes, GATHER_DASHES);

// ── Tags ─────────────────────────────────────────────────────────────

ast_node!(Tags, TAGS);
ast_node!(Tag, TAG);

// ── Inline logic ─────────────────────────────────────────────────────

ast_node!(InlineLogic, INLINE_LOGIC);
ast_node!(MultilineBlock, MULTILINE_BLOCK);
ast_node!(SequenceWithAnnotation, SEQUENCE_WITH_ANNOTATION);
ast_node!(SequenceSymbolAnnotation, SEQUENCE_SYMBOL_ANNOTATION);
ast_node!(SequenceWordAnnotation, SEQUENCE_WORD_ANNOTATION);
ast_node!(InlineBranchesSeq, INLINE_BRANCHES_SEQ);
ast_node!(MultilineBranchesSeq, MULTILINE_BRANCHES_SEQ);
ast_node!(MultilineBranchSeq, MULTILINE_BRANCH_SEQ);
ast_node!(BranchContent, BRANCH_CONTENT);

// ── Conditionals ─────────────────────────────────────────────────────

ast_node!(ConditionalWithExpr, CONDITIONAL_WITH_EXPR);
ast_node!(BranchlessCondBody, BRANCHLESS_COND_BODY);
ast_node!(ElseBranch, ELSE_BRANCH);
ast_node!(InlineBranchesCond, INLINE_BRANCHES_COND);
ast_node!(MultilineBranchesCond, MULTILINE_BRANCHES_COND);
ast_node!(MultilineConditional, MULTILINE_CONDITIONAL);
ast_node!(MultilineBranchCond, MULTILINE_BRANCH_COND);
ast_node!(MultilineBranchBody, MULTILINE_BRANCH_BODY);
ast_node!(ImplicitSequence, IMPLICIT_SEQUENCE);

// ── Expressions ──────────────────────────────────────────────────────

ast_node!(InnerExpression, INNER_EXPRESSION);
ast_node!(PrefixExpr, PREFIX_EXPR);
ast_node!(PostfixExpr, POSTFIX_EXPR);
ast_node!(InfixExpr, INFIX_EXPR);
ast_node!(ParenExpr, PAREN_EXPR);
ast_node!(FunctionCall, FUNCTION_CALL);
ast_node!(ArgList, ARG_LIST);
ast_node!(DivertTargetExpr, DIVERT_TARGET_EXPR);
ast_node!(ListExpr, LIST_EXPR);

// ── T1b superset: sigil literals + indexing (docs/t1b-surface-spec.md §3-4) ──

ast_node!(ArrayLiteral, ARRAY_LITERAL);
ast_node!(MapLiteral, MAP_LITERAL);
ast_node!(MapEntry, MAP_ENTRY);
ast_node!(IndexExpr, INDEX_EXPR);
ast_node!(RangeExpr, RANGE_EXPR);

// ── T1b superset: multi-line `~ { … }` blocks (docs/t1b-surface-spec.md §2) ──

ast_node!(StmtBlock, STMT_BLOCK);
ast_node!(IfStmt, IF_STMT);
ast_node!(ElseClause, ELSE_CLAUSE);
ast_node!(WhileStmt, WHILE_STMT);
ast_node!(ForStmt, FOR_STMT);
ast_node!(BreakStmt, BREAK_STMT);
ast_node!(ContinueStmt, CONTINUE_STMT);
ast_node!(ExprStmt, EXPR_STMT);

// ── TM-2 inline type annotations (docs/typed-mode-spec.md §3) ────────

ast_node!(TypeAnnotation, TYPE_ANNOTATION);
ast_node!(TypeExpr, TYPE_EXPR);
ast_node!(TypeName, TYPE_NAME);
ast_node!(TypeGeneric, TYPE_GENERIC);
ast_node!(TypeFn, TYPE_FN);

// ── TM-4b structs (docs/typed-mode-spec.md §6) ────────────────────────

ast_node!(StructDecl, STRUCT_DECL);
ast_node!(StructFieldDecl, STRUCT_FIELD_DECL);
ast_node!(StructLiteral, STRUCT_LITERAL);
ast_node!(StructFieldInit, STRUCT_FIELD_INIT);
ast_node!(FieldAccessExpr, FIELD_ACCESS_EXPR);

// ── T1c function values (docs/t1c-spec.md §2) ─────────────────────────

ast_node!(FnLiteral, FN_LITERAL);

// ── T1e path projections (docs/t1e-spec.md §2) ────────────────────────

ast_node!(RefExpr, REF_EXPR);

// ── Computed-callee call attempt (docs/t1c-spec.md §3/§10, issue #869) ──

ast_node!(CallExpr, CALL_EXPR);

// ── Diverts ──────────────────────────────────────────────────────────

ast_node!(DivertNode, DIVERT_NODE);
ast_node!(SimpleDivert, SIMPLE_DIVERT);
ast_node!(DivertTargetWithArgs, DIVERT_TARGET_WITH_ARGS);
ast_node!(ThreadStart, THREAD_START);
ast_node!(TunnelOnwardsNode, TUNNEL_ONWARDS_NODE);
ast_node!(TunnelCallNode, TUNNEL_CALL_NODE);

// ── TM-2 inline type annotations (docs/typed-mode-spec.md §3) ────────

impl TypeAnnotation {
    /// The annotated type expression after `:`.
    pub fn type_expr(&self) -> Option<TypeExpr> {
        support::child(&self.syntax)
    }
}

/// What a [`TypeExpr`] wraps — exactly one of these per node.
pub enum TypeExprKind {
    Name(TypeName),
    Generic(TypeGeneric),
    Fn(TypeFn),
}

impl TypeExpr {
    /// The single child this type expression wraps.
    ///
    /// `None` only for a malformed/error-recovered `TYPE_EXPR` (e.g. an
    /// empty annotation at the parser's nesting depth limit) — every
    /// well-formed one always has exactly one of these.
    pub fn kind(&self) -> Option<TypeExprKind> {
        if let Some(n) = support::child::<TypeName>(&self.syntax) {
            Some(TypeExprKind::Name(n))
        } else if let Some(g) = support::child::<TypeGeneric>(&self.syntax) {
            Some(TypeExprKind::Generic(g))
        } else {
            support::child::<TypeFn>(&self.syntax).map(TypeExprKind::Fn)
        }
    }
}

impl TypeName {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    /// The bare type name text (e.g. `"int"`, `"void"`, or an unrecognized
    /// name — grammar accepts any identifier; validity is a semantic check).
    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }
}

impl TypeGeneric {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    /// The generic head name (e.g. `"list"`, `"array"`, `"map"`).
    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The type arguments in source order (e.g. `[K, V]` for `Map<K, V>`).
    pub fn args(&self) -> impl Iterator<Item = TypeExpr> {
        support::children(&self.syntax)
    }
}

impl TypeFn {
    /// Every `TYPE_EXPR` child in source order: the last is the return type,
    /// every earlier one is a parameter type.
    fn type_exprs(&self) -> Vec<TypeExpr> {
        support::children(&self.syntax).collect()
    }

    /// Parameter types, in declaration order.
    pub fn params(&self) -> Vec<TypeExpr> {
        let mut exprs = self.type_exprs();
        if exprs.is_empty() {
            return exprs;
        }
        exprs.pop(); // drop the return type
        exprs
    }

    /// The return type after `:`.
    pub fn return_type(&self) -> Option<TypeExpr> {
        self.type_exprs().pop()
    }
}

// ── Identifiers ──────────────────────────────────────────────────────

ast_node!(Identifier, IDENTIFIER);
ast_node!(Path, PATH);

// ── Declarations ─────────────────────────────────────────────────────

ast_node!(VarDecl, VAR_DECL);
ast_node!(ConstDecl, CONST_DECL);
ast_node!(ListDecl, LIST_DECL);
ast_node!(ListDef, LIST_DEF);
ast_node!(ListMember, LIST_MEMBER);
ast_node!(ListMemberOn, LIST_MEMBER_ON);
ast_node!(ListMemberOff, LIST_MEMBER_OFF);
ast_node!(FunctionParamList, FUNCTION_PARAM_LIST);

// ── Literals ─────────────────────────────────────────────────────────

ast_node!(IntegerLit, INTEGER_LIT);
ast_node!(FloatLit, FLOAT_LIT);
ast_node!(StringLit, STRING_LIT);
ast_node!(BooleanLit, BOOLEAN_LIT);

// ── Error recovery ───────────────────────────────────────────────────

ast_node!(Error, ERROR);

// ── Expression enum ──────────────────────────────────────────────────

/// A typed expression node.
///
/// Covers every node kind the Pratt expression parser can produce.
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Expr {
    Prefix(PrefixExpr),
    Postfix(PostfixExpr),
    Infix(InfixExpr),
    Paren(ParenExpr),
    FunctionCall(FunctionCall),
    IntegerLit(IntegerLit),
    FloatLit(FloatLit),
    StringLit(StringLit),
    BooleanLit(BooleanLit),
    Path(Path),
    ListExpr(ListExpr),
    DivertTarget(DivertTargetExpr),
    /// `#[expr, …]` — array sigil literal (T1b §3, brink extension).
    ArrayLiteral(ArrayLiteral),
    /// `#{key: expr, …}` — map sigil literal (T1b §3, brink extension).
    MapLiteral(MapLiteral),
    /// `base[index]` — postfix indexing (T1b §4, brink extension).
    Index(IndexExpr),
    /// `Name#{field: expr, …}` — struct construction literal (TM-4b,
    /// docs/typed-mode-spec.md §6, brink extension).
    StructLiteral(StructLiteral),
    /// `base.field` — postfix field access (TM-4b, docs/typed-mode-spec.md
    /// §6, brink extension). Only produced where the dotted-`PATH` grammar
    /// doesn't already cover the shape — see `FIELD_ACCESS_EXPR`'s doc.
    FieldAccess(FieldAccessExpr),
    /// `#fn(target, args…)` — function-value creation (T1c,
    /// docs/t1c-spec.md §2, brink extension).
    FnLiteral(FnLiteral),
    /// `ref lvalue-path` — path-projection creation (T1e,
    /// docs/t1e-spec.md §2, brink extension). Legal only in ref-argument
    /// position (calls, `#fn(…)`, `bind(…)`) — a `brink-analyzer` concern,
    /// not a grammar one.
    RefExpr(RefExpr),
    /// `expr(args…)` where `expr` isn't a bare identifier immediately
    /// followed by `(` (that shape is `FunctionCall`) — a computed callee
    /// (indexed, field access, call-result, parenthesized, …). Parses so
    /// the call syntax and its args aren't silently reinterpreted as
    /// trailing prose text; always rejected at HIR lowering (E104,
    /// docs/t1c-spec.md §3/§10, issue #869) since Direct-call syntax is
    /// RULED to a bare variable/temp/param callee only.
    ComputedCall(CallExpr),
    /// `a..b` / `a..=b` — range literal (NS-A5, docs/stdlib-spec.md §7,
    /// brink extension).
    Range(RangeExpr),
}

impl std::fmt::Debug for Expr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self.syntax(), f)
    }
}

impl std::fmt::Display for Expr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.syntax().text(), f)
    }
}

impl crate::ast::AstNode for Expr {
    fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::PREFIX_EXPR
                | SyntaxKind::POSTFIX_EXPR
                | SyntaxKind::INFIX_EXPR
                | SyntaxKind::PAREN_EXPR
                | SyntaxKind::FUNCTION_CALL
                | SyntaxKind::INTEGER_LIT
                | SyntaxKind::FLOAT_LIT
                | SyntaxKind::STRING_LIT
                | SyntaxKind::BOOLEAN_LIT
                | SyntaxKind::PATH
                | SyntaxKind::LIST_EXPR
                | SyntaxKind::DIVERT_TARGET_EXPR
                | SyntaxKind::ARRAY_LITERAL
                | SyntaxKind::MAP_LITERAL
                | SyntaxKind::INDEX_EXPR
                | SyntaxKind::STRUCT_LITERAL
                | SyntaxKind::FIELD_ACCESS_EXPR
                | SyntaxKind::FN_LITERAL
                | SyntaxKind::REF_EXPR
                | SyntaxKind::CALL_EXPR
                | SyntaxKind::RANGE_EXPR
        )
    }

    fn cast(node: SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::PREFIX_EXPR => PrefixExpr::cast(node).map(Expr::Prefix),
            SyntaxKind::POSTFIX_EXPR => PostfixExpr::cast(node).map(Expr::Postfix),
            SyntaxKind::INFIX_EXPR => InfixExpr::cast(node).map(Expr::Infix),
            SyntaxKind::PAREN_EXPR => ParenExpr::cast(node).map(Expr::Paren),
            SyntaxKind::FUNCTION_CALL => FunctionCall::cast(node).map(Expr::FunctionCall),
            SyntaxKind::INTEGER_LIT => IntegerLit::cast(node).map(Expr::IntegerLit),
            SyntaxKind::FLOAT_LIT => FloatLit::cast(node).map(Expr::FloatLit),
            SyntaxKind::STRING_LIT => StringLit::cast(node).map(Expr::StringLit),
            SyntaxKind::BOOLEAN_LIT => BooleanLit::cast(node).map(Expr::BooleanLit),
            SyntaxKind::PATH => Path::cast(node).map(Expr::Path),
            SyntaxKind::LIST_EXPR => ListExpr::cast(node).map(Expr::ListExpr),
            SyntaxKind::DIVERT_TARGET_EXPR => DivertTargetExpr::cast(node).map(Expr::DivertTarget),
            SyntaxKind::ARRAY_LITERAL => ArrayLiteral::cast(node).map(Expr::ArrayLiteral),
            SyntaxKind::MAP_LITERAL => MapLiteral::cast(node).map(Expr::MapLiteral),
            SyntaxKind::INDEX_EXPR => IndexExpr::cast(node).map(Expr::Index),
            SyntaxKind::STRUCT_LITERAL => StructLiteral::cast(node).map(Expr::StructLiteral),
            SyntaxKind::FIELD_ACCESS_EXPR => FieldAccessExpr::cast(node).map(Expr::FieldAccess),
            SyntaxKind::FN_LITERAL => FnLiteral::cast(node).map(Expr::FnLiteral),
            SyntaxKind::REF_EXPR => RefExpr::cast(node).map(Expr::RefExpr),
            SyntaxKind::CALL_EXPR => CallExpr::cast(node).map(Expr::ComputedCall),
            SyntaxKind::RANGE_EXPR => RangeExpr::cast(node).map(Expr::Range),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        match self {
            Expr::Prefix(n) => n.syntax(),
            Expr::Postfix(n) => n.syntax(),
            Expr::Infix(n) => n.syntax(),
            Expr::Paren(n) => n.syntax(),
            Expr::FunctionCall(n) => n.syntax(),
            Expr::IntegerLit(n) => n.syntax(),
            Expr::FloatLit(n) => n.syntax(),
            Expr::StringLit(n) => n.syntax(),
            Expr::BooleanLit(n) => n.syntax(),
            Expr::Path(n) => n.syntax(),
            Expr::ListExpr(n) => n.syntax(),
            Expr::DivertTarget(n) => n.syntax(),
            Expr::ArrayLiteral(n) => n.syntax(),
            Expr::MapLiteral(n) => n.syntax(),
            Expr::Index(n) => n.syntax(),
            Expr::StructLiteral(n) => n.syntax(),
            Expr::FieldAccess(n) => n.syntax(),
            Expr::FnLiteral(n) => n.syntax(),
            Expr::RefExpr(n) => n.syntax(),
            Expr::ComputedCall(n) => n.syntax(),
            Expr::Range(n) => n.syntax(),
        }
    }
}

// ── Content node accessor macro ─────────────────────────────────────

/// Generates shared content-element accessors for nodes that contain
/// mixed inline content (`TEXT`, `INLINE_LOGIC`, `GLUE_NODE`, `ESCAPE`).
macro_rules! content_node_accessors {
    ($name:ident) => {
        impl $name {
            pub fn texts(&self) -> impl Iterator<Item = Text> {
                support::children(&self.syntax)
            }

            pub fn inline_logics(&self) -> impl Iterator<Item = InlineLogic> {
                support::children(&self.syntax)
            }

            pub fn glue_nodes(&self) -> impl Iterator<Item = GlueNode> {
                support::children(&self.syntax)
            }

            pub fn escapes(&self) -> impl Iterator<Item = Escape> {
                support::children(&self.syntax)
            }
        }
    };
}

content_node_accessors!(ChoiceStartContent);
content_node_accessors!(ChoiceBracketContent);
content_node_accessors!(ChoiceInnerContent);
content_node_accessors!(BranchContent);

// ═══════════════════════════════════════════════════════════════════════
// Accessors
// ═══════════════════════════════════════════════════════════════════════

// ── SourceFile ───────────────────────────────────────────────────────

impl SourceFile {
    pub fn knots(&self) -> impl Iterator<Item = KnotDef> {
        support::children(&self.syntax)
    }

    pub fn includes(&self) -> impl Iterator<Item = IncludeStmt> {
        support::children(&self.syntax)
    }

    /// `IMPORT` statements (M-2, docs/modules-spec.md §2). Top-level only.
    pub fn imports(&self) -> impl Iterator<Item = ImportStmt> {
        support::children(&self.syntax)
    }

    pub fn externals(&self) -> impl Iterator<Item = ExternalDecl> {
        support::children(&self.syntax)
    }

    pub fn stitches(&self) -> impl Iterator<Item = StitchDef> {
        support::children(&self.syntax)
    }

    pub fn var_decls(&self) -> impl Iterator<Item = VarDecl> {
        support::children(&self.syntax)
    }

    pub fn const_decls(&self) -> impl Iterator<Item = ConstDecl> {
        support::children(&self.syntax)
    }

    pub fn list_decls(&self) -> impl Iterator<Item = ListDecl> {
        support::children(&self.syntax)
    }

    /// `STRUCT` declarations (TM-4b, docs/typed-mode-spec.md §6) — unlike
    /// `VAR`/`CONST`/`LIST` (which C# allows at any statement level, so
    /// callers walk `.descendants()` for those), a struct shape is
    /// top-level only, so a direct-children scan is exact.
    pub fn struct_decls(&self) -> impl Iterator<Item = StructDecl> {
        support::children(&self.syntax)
    }

    pub fn content_lines(&self) -> impl Iterator<Item = ContentLine> {
        support::children(&self.syntax)
    }

    pub fn logic_lines(&self) -> impl Iterator<Item = LogicLine> {
        support::children(&self.syntax)
    }

    pub fn choices(&self) -> impl Iterator<Item = Choice> {
        support::children(&self.syntax)
    }

    pub fn gathers(&self) -> impl Iterator<Item = Gather> {
        support::children(&self.syntax)
    }
}

// ── IncludeStmt ──────────────────────────────────────────────────────

impl IncludeStmt {
    pub fn file_path(&self) -> Option<FilePath> {
        support::child(&self.syntax)
    }
}

// ── ImportStmt (M-2, docs/modules-spec.md §2) ────────────────────────

impl ImportStmt {
    /// The `{ … }` name list, present only for the bare form
    /// (`IMPORT { a } FROM mod`). Absent for the qualified form
    /// (`IMPORT mod`).
    pub fn list(&self) -> Option<ImportList> {
        support::child(&self.syntax)
    }

    /// The imported module name node (present in both forms).
    pub fn module(&self) -> Option<ImportModule> {
        support::child(&self.syntax)
    }
}

impl ImportList {
    pub fn items(&self) -> impl Iterator<Item = ImportItem> {
        support::children(&self.syntax)
    }
}

impl ImportItem {
    /// The imported name (first identifier) and its optional alias (the
    /// identifier after `AS`). The list has one entry with no alias, or two
    /// with `[name, alias]`.
    fn identifiers(&self) -> impl Iterator<Item = Identifier> {
        support::children(&self.syntax)
    }

    /// The imported definition's own name.
    pub fn name(&self) -> Option<String> {
        self.identifiers().next().and_then(|id| id.name())
    }

    /// The local alias (`AS gt`), if any.
    pub fn alias(&self) -> Option<String> {
        self.identifiers().nth(1).and_then(|id| id.name())
    }
}

impl ImportModule {
    pub fn name(&self) -> Option<String> {
        support::child::<Identifier>(&self.syntax).and_then(|id| id.name())
    }
}

// ── FilePath ─────────────────────────────────────────────────────────

impl FilePath {
    /// Returns the raw text of the file path (concatenation of all child tokens).
    pub fn text(&self) -> String {
        self.syntax.text().to_string()
    }
}

// ── ExternalDecl ─────────────────────────────────────────────────────

impl ExternalDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    pub fn param_list(&self) -> Option<FunctionParamList> {
        support::child(&self.syntax)
    }
}

// ── KnotDef ──────────────────────────────────────────────────────────

impl KnotDef {
    pub fn header(&self) -> Option<KnotHeader> {
        support::child(&self.syntax)
    }

    pub fn body(&self) -> Option<KnotBody> {
        support::child(&self.syntax)
    }
}

// ── KnotHeader ───────────────────────────────────────────────────────

impl KnotHeader {
    pub fn function_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_FUNCTION)
    }

    pub fn is_function(&self) -> bool {
        self.function_kw().is_some()
    }

    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    pub fn params(&self) -> Option<KnotParams> {
        support::child(&self.syntax)
    }

    /// The return type annotation after the params (TM-2, docs/typed-mode-spec.md
    /// §3: `): type ===`), if present.
    pub fn return_type(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }
}

// ── KnotBody ─────────────────────────────────────────────────────────

impl KnotBody {
    pub fn stitches(&self) -> impl Iterator<Item = StitchDef> {
        support::children(&self.syntax)
    }

    pub fn content_lines(&self) -> impl Iterator<Item = ContentLine> {
        support::children(&self.syntax)
    }

    pub fn logic_lines(&self) -> impl Iterator<Item = LogicLine> {
        support::children(&self.syntax)
    }

    pub fn choices(&self) -> impl Iterator<Item = Choice> {
        support::children(&self.syntax)
    }

    pub fn gathers(&self) -> impl Iterator<Item = Gather> {
        support::children(&self.syntax)
    }
}

// ── KnotParams ───────────────────────────────────────────────────────

impl KnotParams {
    pub fn params(&self) -> impl Iterator<Item = KnotParamDecl> {
        support::children(&self.syntax)
    }
}

// ── KnotParamDecl ────────────────────────────────────────────────────

impl KnotParamDecl {
    pub fn divert_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, DIVERT)
    }

    pub fn is_divert(&self) -> bool {
        self.divert_token().is_some()
    }

    pub fn ref_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_REF)
    }

    pub fn is_ref(&self) -> bool {
        self.ref_kw().is_some()
    }

    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The parameter's type annotation (TM-2, docs/typed-mode-spec.md §3:
    /// `name: type`), if present.
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }
}

// ── StitchDef ────────────────────────────────────────────────────────

impl StitchDef {
    pub fn header(&self) -> Option<StitchHeader> {
        support::child(&self.syntax)
    }

    pub fn body(&self) -> Option<StitchBody> {
        support::child(&self.syntax)
    }
}

// ── StitchHeader ─────────────────────────────────────────────────────

impl StitchHeader {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    pub fn params(&self) -> Option<KnotParams> {
        support::child(&self.syntax)
    }

    /// The return type annotation after the params (NG-C, issue #1489,
    /// widened to stitches by #1509: `= name(params): type`), if present —
    /// the same TM-2 grammar position `KnotHeader::return_type` parses,
    /// minus the trailing `===` a stitch header never has.
    pub fn return_type(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }
}

// ── StitchBody ───────────────────────────────────────────────────────

impl StitchBody {
    pub fn content_lines(&self) -> impl Iterator<Item = ContentLine> {
        support::children(&self.syntax)
    }

    pub fn logic_lines(&self) -> impl Iterator<Item = LogicLine> {
        support::children(&self.syntax)
    }

    pub fn choices(&self) -> impl Iterator<Item = Choice> {
        support::children(&self.syntax)
    }

    pub fn gathers(&self) -> impl Iterator<Item = Gather> {
        support::children(&self.syntax)
    }
}

// ── ContentLine ──────────────────────────────────────────────────────

impl ContentLine {
    pub fn mixed_content(&self) -> Option<MixedContent> {
        support::child(&self.syntax)
    }

    pub fn divert(&self) -> Option<DivertNode> {
        support::child(&self.syntax)
    }

    pub fn tags(&self) -> Option<Tags> {
        support::child(&self.syntax)
    }
}

// ── LogicLine ────────────────────────────────────────────────────────

impl LogicLine {
    pub fn return_stmt(&self) -> Option<ReturnStmt> {
        support::child(&self.syntax)
    }

    pub fn temp_decl(&self) -> Option<TempDecl> {
        support::child(&self.syntax)
    }

    pub fn assignment(&self) -> Option<Assignment> {
        support::child(&self.syntax)
    }

    /// The `~ await <cond>` `FlowFrame` suspension point, if this logic line is
    /// one (docs/flow-suspension-spec.md §3).
    pub fn await_stmt(&self) -> Option<AwaitStmt> {
        support::child(&self.syntax)
    }

    /// The T1b `~ { … }` multi-line block body, if this logic line opens one
    /// (docs/t1b-surface-spec.md §2) rather than a single statement.
    pub fn stmt_block(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }
}

// ── TagLine ──────────────────────────────────────────────────────────

impl TagLine {
    pub fn tags(&self) -> Option<Tags> {
        support::child(&self.syntax)
    }
}

// ── AnnotationLine ───────────────────────────────────────────────────

impl AnnotationLine {
    /// The annotation's name token — the `IDENT` after `@[` (e.g. `effects`
    /// in `@[effects(pure)]`).
    pub fn name_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|t| t.kind() == IDENT)
    }

    /// The raw text between the annotation's balanced `( … )` argument
    /// parens, if present — `None` for a bare `@[name]`. Mirrors the
    /// directive channel's raw-string argument contract
    /// (`brink-ir`'s `ParsedDirective::arg`): the argument mini-grammar is
    /// parsed downstream, not here.
    pub fn arg_text(&self) -> Option<String> {
        let mut depth = 0usize;
        let mut collecting = false;
        let mut out = String::new();
        for el in self.syntax.children_with_tokens() {
            let rowan::NodeOrToken::Token(tok) = el else {
                continue;
            };
            match tok.kind() {
                L_PAREN => {
                    if collecting {
                        out.push_str(tok.text());
                    }
                    depth += 1;
                    collecting = true;
                }
                R_PAREN => {
                    depth = depth.saturating_sub(1);
                    if depth == 0 {
                        return Some(out);
                    }
                    out.push_str(tok.text());
                }
                _ if collecting => out.push_str(tok.text()),
                _ => {}
            }
        }
        collecting.then_some(out)
    }
}

// ── ReturnStmt ───────────────────────────────────────────────────────

impl ReturnStmt {
    /// Returns the value expression, if any.
    ///
    /// A bare `return` has no child expression node; `return expr` always
    /// wraps the expression in a typed node (the parser calls `expression()`).
    pub fn value(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }

    /// Returns `true` if the return has a value expression.
    pub fn has_value(&self) -> bool {
        self.value().is_some()
    }
}

// ── AwaitStmt ────────────────────────────────────────────────────────

impl AwaitStmt {
    /// The condition expression — the `<cond>` in `await <cond>`
    /// (docs/flow-suspension-spec.md §3). Absent only for a malformed bare
    /// `await` with no expression (the parser emits a diagnostic there).
    pub fn condition(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }
}

// ── TempDecl ─────────────────────────────────────────────────────────

impl TempDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The ascription's type annotation (TM-2, docs/typed-mode-spec.md §3:
    /// `~ temp name: type = expr`), if present.
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    pub fn eq_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, EQ)
    }

    /// Returns the initializer expression after `=`.
    pub fn value(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── Assignment ───────────────────────────────────────────────────────

impl Assignment {
    pub fn target(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    /// The assignment operator token (`=`, `+=`, or `-=`).
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| matches!(tok.kind(), EQ | PLUS_EQ | MINUS_EQ))
    }

    /// Returns the right-hand side value expression (the second `Expr` child).
    pub fn value(&self) -> Option<Expr> {
        self.syntax.children().filter_map(Expr::cast).nth(1)
    }
}

// ═══════════════════════════════════════════════════════════════════════
// T1b superset: multi-line `~ { … }` blocks (docs/t1b-surface-spec.md §2)
// ═══════════════════════════════════════════════════════════════════════

/// A single statement inside a `~ { … }` block body.
///
/// Deliberately excludes every weave concept (content, choices, diverts,
/// gathers, threads) — the seam rule from docs/t1b-surface-spec.md §2:
/// blocks compute, weave flows.
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum BlockStmt {
    TempDecl(TempDecl),
    Assignment(Assignment),
    Return(ReturnStmt),
    If(IfStmt),
    While(WhileStmt),
    For(ForStmt),
    Break(BreakStmt),
    Continue(ContinueStmt),
    ExprStmt(ExprStmt),
    /// `await <cond>` — a `FlowFrame` suspension point inside a `~ { … }` block
    /// (docs/flow-suspension-spec.md §3).
    Await(AwaitStmt),
}

impl std::fmt::Debug for BlockStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self.syntax(), f)
    }
}

impl crate::ast::AstNode for BlockStmt {
    fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::TEMP_DECL
                | SyntaxKind::ASSIGNMENT
                | SyntaxKind::RETURN_STMT
                | SyntaxKind::IF_STMT
                | SyntaxKind::WHILE_STMT
                | SyntaxKind::FOR_STMT
                | SyntaxKind::BREAK_STMT
                | SyntaxKind::CONTINUE_STMT
                | SyntaxKind::EXPR_STMT
                | SyntaxKind::AWAIT_STMT
        )
    }

    fn cast(node: SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::TEMP_DECL => TempDecl::cast(node).map(BlockStmt::TempDecl),
            SyntaxKind::ASSIGNMENT => Assignment::cast(node).map(BlockStmt::Assignment),
            SyntaxKind::RETURN_STMT => ReturnStmt::cast(node).map(BlockStmt::Return),
            SyntaxKind::IF_STMT => IfStmt::cast(node).map(BlockStmt::If),
            SyntaxKind::WHILE_STMT => WhileStmt::cast(node).map(BlockStmt::While),
            SyntaxKind::FOR_STMT => ForStmt::cast(node).map(BlockStmt::For),
            SyntaxKind::BREAK_STMT => BreakStmt::cast(node).map(BlockStmt::Break),
            SyntaxKind::CONTINUE_STMT => ContinueStmt::cast(node).map(BlockStmt::Continue),
            SyntaxKind::EXPR_STMT => ExprStmt::cast(node).map(BlockStmt::ExprStmt),
            SyntaxKind::AWAIT_STMT => AwaitStmt::cast(node).map(BlockStmt::Await),
            _ => None,
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        match self {
            BlockStmt::TempDecl(n) => n.syntax(),
            BlockStmt::Assignment(n) => n.syntax(),
            BlockStmt::Return(n) => n.syntax(),
            BlockStmt::If(n) => n.syntax(),
            BlockStmt::While(n) => n.syntax(),
            BlockStmt::For(n) => n.syntax(),
            BlockStmt::Break(n) => n.syntax(),
            BlockStmt::Continue(n) => n.syntax(),
            BlockStmt::ExprStmt(n) => n.syntax(),
            BlockStmt::Await(n) => n.syntax(),
        }
    }
}

// ── StmtBlock ────────────────────────────────────────────────────────

impl StmtBlock {
    /// The statements in this block, in source order.
    pub fn stmts(&self) -> impl Iterator<Item = BlockStmt> {
        support::children(&self.syntax)
    }
}

// ── IfStmt ───────────────────────────────────────────────────────────

impl IfStmt {
    /// The condition expression (the first `Expr` child).
    pub fn condition(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    /// The `{ … }` body executed when the condition holds.
    pub fn body(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }

    /// The `else` arm, if present.
    pub fn else_clause(&self) -> Option<ElseClause> {
        support::child(&self.syntax)
    }
}

// ── ElseClause ───────────────────────────────────────────────────────

impl ElseClause {
    /// The nested `if` for an `else if` chain, if this is one.
    pub fn if_stmt(&self) -> Option<IfStmt> {
        support::child(&self.syntax)
    }

    /// The `{ … }` body for a bare `else`, if this is one (mutually
    /// exclusive with [`ElseClause::if_stmt`]).
    pub fn body(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }
}

// ── WhileStmt ────────────────────────────────────────────────────────

impl WhileStmt {
    pub fn condition(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    pub fn body(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }

    /// Whether this is the persistent-await form `while await cond { … }`
    /// (docs/flow-suspension-spec.md §3) rather than a plain `while` loop. The
    /// parser bumps the marker `await` as a direct `IDENT` token child (the
    /// `while` keyword is the only other direct `IDENT` token; the condition
    /// lives inside an `Expr` node, never a bare token), so the presence of an
    /// `IDENT` token spelled `await` here is the unambiguous marker.
    pub fn is_await(&self) -> bool {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .any(|tok| tok.kind() == SyntaxKind::IDENT && tok.text() == "await")
    }
}

// ── ForStmt ──────────────────────────────────────────────────────────

impl ForStmt {
    /// The loop variable name.
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The iterable expression (after `in`).
    pub fn iterable(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    pub fn body(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }
}

// ── ExprStmt ─────────────────────────────────────────────────────────

impl ExprStmt {
    pub fn expr(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ═══════════════════════════════════════════════════════════════════════
// T1b superset: sigil literals + indexing (docs/t1b-surface-spec.md §3-4)
// ═══════════════════════════════════════════════════════════════════════

// ── ArrayLiteral ─────────────────────────────────────────────────────

impl ArrayLiteral {
    pub fn elements(&self) -> impl Iterator<Item = Expr> {
        support::children(&self.syntax)
    }
}

// ── MapLiteral ───────────────────────────────────────────────────────

impl MapLiteral {
    pub fn entries(&self) -> impl Iterator<Item = MapEntry> {
        support::children(&self.syntax)
    }
}

// ── MapEntry ─────────────────────────────────────────────────────────

impl MapEntry {
    /// The key expression (the first `Expr` child).
    pub fn key(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    /// The value expression (the second `Expr` child).
    pub fn value(&self) -> Option<Expr> {
        self.syntax.children().filter_map(Expr::cast).nth(1)
    }
}

// ── IndexExpr ────────────────────────────────────────────────────────

impl IndexExpr {
    /// The base being indexed (the first `Expr` child) — `a` in `a[i]`.
    pub fn base(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    /// The index expression (the second `Expr` child) — `i` in `a[i]`.
    pub fn index(&self) -> Option<Expr> {
        self.syntax.children().filter_map(Expr::cast).nth(1)
    }
}

// ── RangeExpr (NS-A5, docs/stdlib-spec.md §7) ────────────────────────

impl RangeExpr {
    /// The start bound (the first `Expr` child) — `a` in `a..b`.
    pub fn start(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    /// The end bound (the second `Expr` child) — `b` in `a..b`.
    pub fn end(&self) -> Option<Expr> {
        self.syntax.children().filter_map(Expr::cast).nth(1)
    }

    /// `true` for the inclusive `..=` form — detected by the `EQ` token the
    /// parser bumped between the dots and the end bound.
    pub fn is_inclusive(&self) -> bool {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .any(|t| t.kind() == SyntaxKind::EQ)
    }
}

// ═══════════════════════════════════════════════════════════════════════
// TM-4b structs (docs/typed-mode-spec.md §6)
// ═══════════════════════════════════════════════════════════════════════

// ── StructDecl ───────────────────────────────────────────────────────

impl StructDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The declared fields, in source order.
    pub fn fields(&self) -> impl Iterator<Item = StructFieldDecl> {
        support::children(&self.syntax)
    }
}

// ── StructFieldDecl ──────────────────────────────────────────────────

impl StructFieldDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The field's declared type (value position — mirrors the
    /// construction literal's field-init value position, §6).
    pub fn type_expr(&self) -> Option<TypeExpr> {
        support::child(&self.syntax)
    }
}

// ── StructLiteral ────────────────────────────────────────────────────

impl StructLiteral {
    /// The leading shape-name identifier (e.g. `Point` in `Point#{…}`).
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn shape_name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The field initializers, in source order.
    pub fn fields(&self) -> impl Iterator<Item = StructFieldInit> {
        support::children(&self.syntax)
    }
}

// ── StructFieldInit ──────────────────────────────────────────────────

impl StructFieldInit {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The initializer expression after `:`.
    pub fn value(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── FieldAccessExpr ──────────────────────────────────────────────────

impl FieldAccessExpr {
    /// The expression being accessed (the first, and only, `Expr` child) —
    /// `base` in `base.field`.
    pub fn base(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    /// The field name identifier after `.`.
    pub fn field(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn field_name(&self) -> Option<String> {
        self.field().and_then(|id| id.name())
    }
}

// ═══════════════════════════════════════════════════════════════════════
// T1c function values (docs/t1c-spec.md §2)
// ═══════════════════════════════════════════════════════════════════════

// ── FnLiteral ────────────────────────────────────────────────────────

impl FnLiteral {
    /// The static target path (the first `PATH` child) — `heal` in
    /// `#fn(heal, hp)`. `None` on malformed input (`#fn()`, `#fn(1)`).
    pub fn target(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

    /// The bound-argument expressions after the target, in source order.
    /// The target `PATH` is itself castable to `Expr::Path`, so this skips
    /// the first `Expr` child iff it is that target node.
    pub fn args(&self) -> impl Iterator<Item = Expr> {
        let target_node = self.target().map(|t| t.syntax().clone());
        self.syntax
            .children()
            .filter_map(Expr::cast)
            .filter(move |e| Some(e.syntax()) != target_node.as_ref())
    }
}

// ═══════════════════════════════════════════════════════════════════════
// T1e path projections (docs/t1e-spec.md §2)
// ═══════════════════════════════════════════════════════════════════════

// ── RefExpr ──────────────────────────────────────────────────────────

impl RefExpr {
    pub fn ref_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_REF)
    }

    /// The lvalue-shaped operand after `ref` — a plain path, a dotted field
    /// chain, `[…]` indexing, or a mix. `None` on malformed input (`ref` at
    /// end of input, or followed by a token that starts no expression).
    pub fn operand(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── MixedContent ─────────────────────────────────────────────────────

impl MixedContent {
    pub fn texts(&self) -> impl Iterator<Item = Text> {
        support::children(&self.syntax)
    }

    pub fn glue_nodes(&self) -> impl Iterator<Item = GlueNode> {
        support::children(&self.syntax)
    }

    pub fn inline_logics(&self) -> impl Iterator<Item = InlineLogic> {
        support::children(&self.syntax)
    }

    pub fn escapes(&self) -> impl Iterator<Item = Escape> {
        support::children(&self.syntax)
    }
}

// ── Choice ───────────────────────────────────────────────────────────

impl Choice {
    pub fn bullets(&self) -> Option<ChoiceBullets> {
        support::child(&self.syntax)
    }

    pub fn label(&self) -> Option<Label> {
        support::child(&self.syntax)
    }

    pub fn conditions(&self) -> impl Iterator<Item = ChoiceCondition> {
        support::children(&self.syntax)
    }

    pub fn start_content(&self) -> Option<ChoiceStartContent> {
        support::child(&self.syntax)
    }

    pub fn bracket_content(&self) -> Option<ChoiceBracketContent> {
        support::child(&self.syntax)
    }

    pub fn inner_content(&self) -> Option<ChoiceInnerContent> {
        support::child(&self.syntax)
    }

    pub fn divert(&self) -> Option<DivertNode> {
        support::child(&self.syntax)
    }

    pub fn tags(&self) -> Option<Tags> {
        support::child(&self.syntax)
    }

    /// Returns an iterator over all TAGS children (tags can appear on
    /// each content region within a choice line).
    pub fn all_tags(&self) -> impl Iterator<Item = Tags> {
        support::children(&self.syntax)
    }
}

// ── ChoiceBullets ────────────────────────────────────────────────────

impl ChoiceBullets {
    /// Number of bullet characters (nesting depth).
    pub fn depth(&self) -> usize {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .filter(|tok| matches!(tok.kind(), STAR | PLUS))
            .count()
    }

    /// Returns `true` if using `+` (sticky), `false` if using `*`.
    ///
    /// Determined by the first bullet token, matching the reference ink
    /// compiler's behavior for degenerate mixed-bullet cases.
    pub fn is_sticky(&self) -> bool {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| matches!(tok.kind(), STAR | PLUS))
            .is_some_and(|tok| tok.kind() == PLUS)
    }

    /// Returns `true` if bullets mix `*` and `+` (e.g. `*+`, `+*`).
    ///
    /// Mixed bullets are degenerate input — a diagnostic pass should flag them.
    pub fn is_mixed(&self) -> bool {
        let mut has_star = false;
        let mut has_plus = false;
        for tok in self
            .syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
        {
            match tok.kind() {
                STAR => has_star = true,
                PLUS => has_plus = true,
                _ => {}
            }
        }
        has_star && has_plus
    }
}

// ── Label ────────────────────────────────────────────────────────────

impl Label {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }
}

// ── Gather ───────────────────────────────────────────────────────────

impl Gather {
    pub fn dashes(&self) -> Option<GatherDashes> {
        support::child(&self.syntax)
    }

    pub fn label(&self) -> Option<Label> {
        support::child(&self.syntax)
    }

    pub fn mixed_content(&self) -> Option<MixedContent> {
        support::child(&self.syntax)
    }

    /// Inline choice on the same line as the gather (e.g. `- * hello`).
    pub fn choice(&self) -> Option<Choice> {
        support::child(&self.syntax)
    }

    pub fn divert(&self) -> Option<DivertNode> {
        support::child(&self.syntax)
    }

    pub fn tags(&self) -> Option<Tags> {
        support::child(&self.syntax)
    }
}

// ── GatherDashes ─────────────────────────────────────────────────────

impl GatherDashes {
    /// Number of dashes (nesting depth).
    pub fn depth(&self) -> usize {
        support::tokens(&self.syntax, MINUS).count()
    }
}

// ── Tags ─────────────────────────────────────────────────────────────

impl Tags {
    pub fn tags(&self) -> impl Iterator<Item = Tag> {
        support::children(&self.syntax)
    }
}

// ── Tag ──────────────────────────────────────────────────────────────

impl Tag {
    /// Returns the tag value with the leading `#` stripped.
    ///
    /// Walks tokens directly rather than string-manipulating the full node text.
    /// The parser guarantees a `HASH` token is always present.
    pub fn text(&self) -> String {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .filter(|tok| tok.kind() != HASH)
            .map(|tok| tok.text().to_string())
            .collect::<String>()
            .trim()
            .to_string()
    }
}

// ── InlineLogic ──────────────────────────────────────────────────────

impl InlineLogic {
    pub fn inner_expression(&self) -> Option<InnerExpression> {
        support::child(&self.syntax)
    }

    pub fn conditional(&self) -> Option<ConditionalWithExpr> {
        support::child(&self.syntax)
    }

    pub fn sequence(&self) -> Option<SequenceWithAnnotation> {
        support::child(&self.syntax)
    }

    pub fn implicit_sequence(&self) -> Option<ImplicitSequence> {
        support::child(&self.syntax)
    }

    pub fn multiline_conditional(&self) -> Option<MultilineConditional> {
        support::child(&self.syntax)
    }
}

// ── MultilineBlock ───────────────────────────────────────────────────

impl MultilineBlock {
    pub fn conditional(&self) -> Option<ConditionalWithExpr> {
        support::child(&self.syntax)
    }

    pub fn sequence(&self) -> Option<SequenceWithAnnotation> {
        support::child(&self.syntax)
    }

    pub fn branches_cond(&self) -> Option<MultilineBranchesCond> {
        support::child(&self.syntax)
    }
}

// ── SequenceWithAnnotation ───────────────────────────────────────────

impl SequenceWithAnnotation {
    pub fn symbol_annotation(&self) -> Option<SequenceSymbolAnnotation> {
        support::child(&self.syntax)
    }

    pub fn word_annotation(&self) -> Option<SequenceWordAnnotation> {
        support::child(&self.syntax)
    }

    pub fn inline_branches(&self) -> Option<InlineBranchesSeq> {
        support::child(&self.syntax)
    }

    pub fn multiline_branches(&self) -> Option<MultilineBranchesSeq> {
        support::child(&self.syntax)
    }
}

// ── SequenceSymbolAnnotation ──────────────────────────────────────────

impl SequenceSymbolAnnotation {
    pub fn amp_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, AMP)
    }

    pub fn bang_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, BANG)
    }

    pub fn tilde_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, TILDE)
    }

    pub fn dollar_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, DOLLAR)
    }
}

// ── SequenceWordAnnotation ───────────────────────────────────────────

impl SequenceWordAnnotation {
    pub fn stopping_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_STOPPING)
    }

    pub fn cycle_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_CYCLE)
    }

    pub fn shuffle_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_SHUFFLE)
    }

    pub fn once_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_ONCE)
    }
}

// ── InlineBranchesSeq ────────────────────────────────────────────────

impl InlineBranchesSeq {
    pub fn branches(&self) -> impl Iterator<Item = BranchContent> {
        support::children(&self.syntax)
    }
}

// ── InlineBranchesCond ───────────────────────────────────────────────

impl InlineBranchesCond {
    pub fn branches(&self) -> impl Iterator<Item = BranchContent> {
        support::children(&self.syntax)
    }
}

// ── MultilineBranchesSeq ─────────────────────────────────────────────

impl MultilineBranchesSeq {
    pub fn branches(&self) -> impl Iterator<Item = MultilineBranchSeq> {
        support::children(&self.syntax)
    }
}

// ── MultilineBranchesCond ────────────────────────────────────────────

impl MultilineBranchesCond {
    pub fn branches(&self) -> impl Iterator<Item = MultilineBranchCond> {
        support::children(&self.syntax)
    }
}

// ── MultilineBranchSeq ───────────────────────────────────────────────

impl MultilineBranchSeq {
    pub fn body(&self) -> Option<MultilineBranchBody> {
        support::child(&self.syntax)
    }
}

// ── MultilineBranchCond ──────────────────────────────────────────────

impl MultilineBranchCond {
    /// Returns the branch condition expression (if not an else branch).
    pub fn condition(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }

    pub fn body(&self) -> Option<MultilineBranchBody> {
        support::child(&self.syntax)
    }

    pub fn else_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_ELSE)
    }

    pub fn is_else(&self) -> bool {
        self.else_kw().is_some()
    }
}

// ── ConditionalWithExpr ──────────────────────────────────────────────

impl ConditionalWithExpr {
    /// Returns the condition expression.
    pub fn condition(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }

    pub fn inline_branches(&self) -> Option<InlineBranchesCond> {
        support::child(&self.syntax)
    }

    pub fn multiline_branches(&self) -> Option<MultilineBranchesCond> {
        support::child(&self.syntax)
    }

    pub fn branchless_body(&self) -> Option<BranchlessCondBody> {
        support::child(&self.syntax)
    }
}

// ── BranchlessCondBody ───────────────────────────────────────────────

impl BranchlessCondBody {
    pub fn texts(&self) -> impl Iterator<Item = Text> {
        support::children(&self.syntax)
    }

    pub fn inline_logics(&self) -> impl Iterator<Item = InlineLogic> {
        support::children(&self.syntax)
    }

    pub fn glue_nodes(&self) -> impl Iterator<Item = GlueNode> {
        support::children(&self.syntax)
    }

    pub fn escapes(&self) -> impl Iterator<Item = Escape> {
        support::children(&self.syntax)
    }

    pub fn logic_lines(&self) -> impl Iterator<Item = LogicLine> {
        support::children(&self.syntax)
    }

    pub fn divert(&self) -> Option<DivertNode> {
        support::child(&self.syntax)
    }

    pub fn content_lines(&self) -> impl Iterator<Item = ContentLine> {
        support::children(&self.syntax)
    }

    pub fn else_branch(&self) -> Option<ElseBranch> {
        support::child(&self.syntax)
    }
}

// ── ElseBranch ───────────────────────────────────────────────────────

impl ElseBranch {
    pub fn branch(&self) -> Option<MultilineBranchCond> {
        support::child(&self.syntax)
    }
}

// ── MultilineConditional ─────────────────────────────────────────────

impl MultilineConditional {
    pub fn branches(&self) -> impl Iterator<Item = MultilineBranchCond> {
        support::children(&self.syntax)
    }
}

// ── ImplicitSequence ─────────────────────────────────────────────────

impl ImplicitSequence {
    pub fn branches(&self) -> impl Iterator<Item = BranchContent> {
        support::children(&self.syntax)
    }
}

// ── PrefixExpr ───────────────────────────────────────────────────────

impl PrefixExpr {
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| matches!(tok.kind(), MINUS | BANG | KW_NOT))
    }

    /// Returns the operand expression.
    pub fn operand(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── PostfixExpr ──────────────────────────────────────────────────────

impl PostfixExpr {
    /// Returns the first operator token (`PLUS` for `++`, `MINUS` for `--`).
    /// Both operators are two adjacent tokens inside this node.
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| matches!(tok.kind(), PLUS | MINUS))
    }

    /// Returns the operand expression.
    pub fn operand(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── InfixExpr ────────────────────────────────────────────────────────

impl InfixExpr {
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| {
                matches!(
                    tok.kind(),
                    PLUS | MINUS
                        | STAR
                        | SLASH
                        | PERCENT
                        | CARET
                        | EQ_EQ
                        | BANG_EQ
                        | LT
                        | GT
                        | LT_EQ
                        | GT_EQ
                        | KW_AND
                        | AMP_AMP
                        | KW_OR
                        | PIPE
                        | KW_MOD
                        | KW_HAS
                        | KW_HASNT
                        | QUESTION
                        | BANG_QUESTION
                        | PLUS_EQ
                        | MINUS_EQ
                )
            })
    }

    pub fn lhs(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    pub fn rhs(&self) -> Option<Expr> {
        self.syntax.children().filter_map(Expr::cast).nth(1)
    }
}

// ── FunctionCall ─────────────────────────────────────────────────────

impl FunctionCall {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    pub fn arg_list(&self) -> Option<ArgList> {
        support::child(&self.syntax)
    }
}

// ── CallExpr (computed-callee call attempt, issue #869) ──────────────

impl CallExpr {
    /// The callee expression — the first (and only non-`ARG_LIST`) child.
    /// Always some non-identifier-immediately-followed-by-`(` shape
    /// (`FUNCTION_CALL`'s bare-name fast path never reaches this node).
    pub fn callee(&self) -> Option<Expr> {
        self.syntax.children().find_map(Expr::cast)
    }

    pub fn arg_list(&self) -> Option<ArgList> {
        support::child(&self.syntax)
    }
}

// ── ArgList ──────────────────────────────────────────────────────────

impl ArgList {
    /// Number of arguments (child expression nodes).
    pub fn arg_count(&self) -> usize {
        self.syntax
            .children()
            .filter(|child| child.kind() != SyntaxKind::ERROR)
            .count()
    }

    /// Iterator over the argument expressions.
    pub fn args(&self) -> impl Iterator<Item = Expr> {
        support::children(&self.syntax)
    }
}

// ── DivertTargetExpr ─────────────────────────────────────────────────

impl DivertTargetExpr {
    pub fn target(&self) -> Option<Path> {
        support::child(&self.syntax)
    }
}

// ── ListExpr ─────────────────────────────────────────────────────────

impl ListExpr {
    pub fn items(&self) -> impl Iterator<Item = Path> {
        support::children(&self.syntax)
    }
}

// ── DivertNode ───────────────────────────────────────────────────────

impl DivertNode {
    pub fn thread_start(&self) -> Option<ThreadStart> {
        support::child(&self.syntax)
    }

    pub fn tunnel_onwards(&self) -> Option<TunnelOnwardsNode> {
        support::child(&self.syntax)
    }

    pub fn tunnel_call(&self) -> Option<TunnelCallNode> {
        support::child(&self.syntax)
    }

    pub fn simple_divert(&self) -> Option<SimpleDivert> {
        support::child(&self.syntax)
    }
}

// ── SimpleDivert ─────────────────────────────────────────────────────

impl SimpleDivert {
    pub fn targets(&self) -> impl Iterator<Item = DivertTargetWithArgs> {
        support::children(&self.syntax)
    }
}

// ── DivertTargetWithArgs ─────────────────────────────────────────────

impl DivertTargetWithArgs {
    pub fn path(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

    pub fn done_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_DONE)
    }

    pub fn end_kw(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, KW_END)
    }

    pub fn arg_list(&self) -> Option<ArgList> {
        support::child(&self.syntax)
    }
}

// ── ThreadStart ──────────────────────────────────────────────────────

impl ThreadStart {
    /// Returns the target path.
    ///
    /// The parser produces a `PATH` child directly (not wrapped in
    /// `DivertTargetWithArgs`), so this returns `Option<Path>`.
    pub fn target(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

    pub fn arg_list(&self) -> Option<ArgList> {
        support::child(&self.syntax)
    }
}

// ── TunnelOnwardsNode ────────────────────────────────────────────────

impl TunnelOnwardsNode {
    pub fn targets(&self) -> impl Iterator<Item = DivertTargetWithArgs> {
        support::children(&self.syntax)
    }

    pub fn tunnel_call(&self) -> Option<TunnelCallNode> {
        support::child(&self.syntax)
    }
}

// ── TunnelCallNode ──────────────────────────────────────────────────

impl TunnelCallNode {
    pub fn targets(&self) -> impl Iterator<Item = DivertTargetWithArgs> {
        support::children(&self.syntax)
    }
}

// ── Identifier ───────────────────────────────────────────────────────

impl Identifier {
    pub fn ident_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, IDENT)
    }

    /// Returns the name text, accepting either `IDENT` or keyword tokens
    /// (ink keywords are contextual and may appear as identifiers).
    pub fn name(&self) -> Option<String> {
        self.ident_token()
            .or_else(|| {
                self.syntax
                    .children_with_tokens()
                    .filter_map(rowan::NodeOrToken::into_token)
                    .find(|t| t.kind().is_keyword())
            })
            .map(|t| t.text().to_string())
    }
}

// ── Path ─────────────────────────────────────────────────────────────

impl Path {
    /// Iterator over the segment tokens (`IDENT` or keyword tokens between dots).
    pub fn segments(&self) -> impl Iterator<Item = SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .filter(|t| t.kind() == IDENT || t.kind().is_keyword())
    }

    /// Full dotted name (e.g. `"knot.stitch"`).
    pub fn full_name(&self) -> String {
        self.segments()
            .map(|t| t.text().to_string())
            .collect::<Vec<_>>()
            .join(".")
    }
}

// ── VarDecl ──────────────────────────────────────────────────────────

impl VarDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The declared type annotation (TM-2, docs/typed-mode-spec.md §3:
    /// `VAR name: type = expr`), if present.
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// Returns the initializer expression after `=`.
    pub fn value(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── ConstDecl ────────────────────────────────────────────────────────

impl ConstDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    /// The declared type annotation (TM-2, docs/typed-mode-spec.md §3:
    /// `CONST name: type = expr`), if present.
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// Returns the initializer expression after `=`.
    pub fn value(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── ListDecl ─────────────────────────────────────────────────────────

impl ListDecl {
    pub fn identifier(&self) -> Option<Identifier> {
        support::child(&self.syntax)
    }

    pub fn name(&self) -> Option<String> {
        self.identifier().and_then(|id| id.name())
    }

    pub fn definition(&self) -> Option<ListDef> {
        support::child(&self.syntax)
    }
}

// ── ListDef ──────────────────────────────────────────────────────────

impl ListDef {
    pub fn members(&self) -> impl Iterator<Item = ListMember> {
        support::children(&self.syntax)
    }
}

// ── ListMember ───────────────────────────────────────────────────────

impl ListMember {
    pub fn on_member(&self) -> Option<ListMemberOn> {
        support::child(&self.syntax)
    }

    pub fn off_member(&self) -> Option<ListMemberOff> {
        support::child(&self.syntax)
    }
}

// ── ListMemberOn ─────────────────────────────────────────────────────

impl ListMemberOn {
    pub fn name_token(&self) -> Option<SyntaxToken> {
        // Ink keywords are contextual — accept IDENT or keywords as member names.
        support::ident_or_keyword_token(&self.syntax)
    }

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

    pub fn value_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, INTEGER)
    }

    /// Returns the explicit integer value assigned to this member, if any.
    pub fn value(&self) -> Option<i64> {
        self.value_token()
            .and_then(|t| t.text().parse::<i64>().ok())
    }
}

// ── ListMemberOff ────────────────────────────────────────────────────

impl ListMemberOff {
    pub fn name_token(&self) -> Option<SyntaxToken> {
        // Ink keywords are contextual — accept IDENT or keywords as member names.
        support::ident_or_keyword_token(&self.syntax)
    }

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

    pub fn value_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, INTEGER)
    }

    /// Returns the explicit integer value assigned to this member, if any.
    pub fn value(&self) -> Option<i64> {
        self.value_token()
            .and_then(|t| t.text().parse::<i64>().ok())
    }
}

// ── FunctionParamList ────────────────────────────────────────────────

impl FunctionParamList {
    /// Iterator over the `Identifier` nodes in the param list.
    pub fn params(&self) -> impl Iterator<Item = Identifier> {
        support::children(&self.syntax)
    }
}

// ── IntegerLit ───────────────────────────────────────────────────────

impl IntegerLit {
    pub fn value_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, INTEGER)
    }

    pub fn value(&self) -> Option<i64> {
        self.value_token()
            .and_then(|t| t.text().parse::<i64>().ok())
    }
}

// ── FloatLit ─────────────────────────────────────────────────────────

impl FloatLit {
    pub fn value_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, FLOAT)
    }

    pub fn value(&self) -> Option<f64> {
        self.value_token()
            .and_then(|t| t.text().parse::<f64>().ok())
    }
}

// ── StringLit ────────────────────────────────────────────────────────

impl StringLit {
    /// Returns the raw content between the quotes (excluding the quotes themselves).
    ///
    /// The opening quote is always present (the parser enters `string_literal`
    /// only on a `QUOTE` token). The closing quote may be absent if the string
    /// is unterminated — the parser emits an error and closes the node without
    /// consuming a trailing `QUOTE`. The `strip_suffix` fallback handles that
    /// error-recovery case.
    pub fn raw_text(&self) -> String {
        let full = self.syntax.text().to_string();
        let trimmed = full.strip_prefix('"').unwrap_or(&full);
        trimmed.strip_suffix('"').unwrap_or(trimmed).to_string()
    }
}

// ── BooleanLit ───────────────────────────────────────────────────────

impl BooleanLit {
    pub fn value(&self) -> Option<bool> {
        let tok = self
            .syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| matches!(tok.kind(), KW_TRUE | KW_FALSE))?;
        match tok.kind() {
            KW_TRUE => Some(true),
            KW_FALSE => Some(false),
            _ => None,
        }
    }
}

// ── AuthorWarning ────────────────────────────────────────────────────

impl AuthorWarning {
    /// Returns the warning text with the `TODO:` prefix stripped.
    ///
    /// Walks tokens directly — skips the `KW_TODO` token and the optional
    /// `COLON`, then collects remaining content until `NEWLINE`.
    pub fn text(&self) -> String {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .skip_while(|tok| matches!(tok.kind(), KW_TODO | COLON) || tok.kind().is_trivia())
            .take_while(|tok| tok.kind() != NEWLINE)
            .map(|tok| tok.text().to_string())
            .collect::<String>()
            .trim()
            .to_string()
    }
}

// ── ChoiceCondition ──────────────────────────────────────────────────

impl ChoiceCondition {
    /// Returns the condition expression inside `{ expr }`.
    pub fn expr(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── InnerExpression ──────────────────────────────────────────────────

impl InnerExpression {
    /// Returns the wrapped expression.
    pub fn expr(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── ParenExpr ────────────────────────────────────────────────────────

impl ParenExpr {
    /// Returns the inner expression inside `( expr )`.
    pub fn inner(&self) -> Option<Expr> {
        support::child(&self.syntax)
    }
}

// ── BranchContent (extra) ────────────────────────────────────────────

impl BranchContent {
    pub fn divert(&self) -> Option<DivertNode> {
        support::child(&self.syntax)
    }
}

// ── MultilineBranchBody ──────────────────────────────────────────────

impl MultilineBranchBody {
    pub fn texts(&self) -> impl Iterator<Item = Text> {
        support::children(&self.syntax)
    }

    pub fn inline_logics(&self) -> impl Iterator<Item = InlineLogic> {
        support::children(&self.syntax)
    }

    pub fn glue_nodes(&self) -> impl Iterator<Item = GlueNode> {
        support::children(&self.syntax)
    }

    pub fn escapes(&self) -> impl Iterator<Item = Escape> {
        support::children(&self.syntax)
    }

    pub fn logic_lines(&self) -> impl Iterator<Item = LogicLine> {
        support::children(&self.syntax)
    }

    pub fn divert(&self) -> Option<DivertNode> {
        support::child(&self.syntax)
    }

    pub fn content_lines(&self) -> impl Iterator<Item = ContentLine> {
        support::children(&self.syntax)
    }

    pub fn choices(&self) -> impl Iterator<Item = Choice> {
        support::children(&self.syntax)
    }
}