brink-syntax-native 0.0.16

Lexer and error-resilient CST for the .brink native surface (B0.5 grammar skeleton)
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
//! Typed AST node wrappers for every node kind in the native CST.
//!
//! Every struct is a zero-cost newtype generated by [`ast_node!`]. A
//! representative subset has hand-written accessors below its
//! `ast_node!` line — enough to prove the pattern end-to-end for B0.6+
//! without pre-building every accessor a later lowering pass might want
//! (that's additive, not a re-architecture, when it's actually needed).

use crate::SyntaxKind::{self, DOC_COMMENT_INNER, DOC_COMMENT_OUTER, HASH, IDENT, L_PAREN};
use crate::ast::AstNode as _;
use crate::ast::ast_node;
use crate::ast::support;
use crate::{SyntaxNode, SyntaxToken};

// ── Doc comments (B0.6b) ──────────────────────────────────────────────

ast_node!(DocComment, DOC_COMMENT);

// ── Top level & declarations ────────────────────────────────────────

ast_node!(SourceFile, SOURCE_FILE);
ast_node!(FlowDecl, FLOW_DECL);
ast_node!(FnDecl, FN_DECL);
ast_node!(ParamList, PARAM_LIST);
ast_node!(Param, PARAM);
ast_node!(VarDecl, VAR_DECL);
ast_node!(ConstDecl, CONST_DECL);
ast_node!(FlagsDecl, FLAGS_DECL);
ast_node!(FlagsMemberList, FLAGS_MEMBER_LIST);
ast_node!(FlagsMember, FLAGS_MEMBER);
ast_node!(StructDecl, STRUCT_DECL);
ast_node!(StructField, STRUCT_FIELD);
ast_node!(ExternDecl, EXTERN_DECL);
ast_node!(UseDecl, USE_DECL);
ast_node!(UseTree, USE_TREE);
ast_node!(UseTreeList, USE_TREE_LIST);
ast_node!(ImportDecl, IMPORT_DECL);
ast_node!(ModuleDecl, MODULE_DECL);

// ── Bodies & content ─────────────────────────────────────────────────

ast_node!(Block, BLOCK);
ast_node!(ContentLine, CONTENT_LINE);
ast_node!(LogicLine, LOGIC_LINE);
ast_node!(ProseLine, PROSE_LINE);
ast_node!(Text, TEXT);
ast_node!(Interpolation, INTERPOLATION);
ast_node!(GlueNode, GLUE_NODE);
ast_node!(TagLine, TAG_LINE);
ast_node!(Tag, TAG);

// ── Prose block elements (docs/prose-dialect-spec.md §8b/§8d) ────────

ast_node!(SceneStitch, SCENE_STITCH);
ast_node!(SceneHeading, SCENE_HEADING);
ast_node!(SceneTitle, SCENE_TITLE);
ast_node!(SceneSlug, SCENE_SLUG);
ast_node!(SceneBody, SCENE_BODY);
ast_node!(Cue, CUE);
ast_node!(CueName, CUE_NAME);
ast_node!(CompactCue, COMPACT_CUE);
ast_node!(Parenthetical, PARENTHETICAL);
ast_node!(BangDispatch, BANG_DISPATCH);
ast_node!(DispatchName, DISPATCH_NAME);

// ── Inline markup (docs/prose-dialect-spec.md §4, issue #1716) ──────
ast_node!(Span, SPAN);
ast_node!(SpanName, SPAN_NAME);
ast_node!(SpanAttr, SPAN_ATTR);
ast_node!(SpanAttrValue, SPAN_ATTR_VALUE);
ast_node!(Escape, ESCAPE);

// ── Choice points ────────────────────────────────────────────────────

ast_node!(ChoicePoint, CHOICE_POINT);
ast_node!(Choice, CHOICE);
ast_node!(ChoiceBullet, CHOICE_BULLET);
ast_node!(Label, LABEL);
ast_node!(ChoiceGuard, CHOICE_GUARD);
ast_node!(ChoiceStartContent, CHOICE_START_CONTENT);
ast_node!(ChoiceBracketContent, CHOICE_BRACKET_CONTENT);
ast_node!(ChoiceInnerContent, CHOICE_INNER_CONTENT);
ast_node!(ChoiceBody, CHOICE_BODY);
ast_node!(ElseBranch, ELSE_BRANCH);
ast_node!(Splice, SPLICE);

// ── The annotated-brace family: conditional / alternation ───────────

ast_node!(ConditionalBlock, CONDITIONAL_BLOCK);
ast_node!(IfArm, IF_ARM);
ast_node!(MatchArm, MATCH_ARM);
ast_node!(MatchPattern, MATCH_PATTERN);
ast_node!(AlternationBlock, ALTERNATION_BLOCK);
ast_node!(AlternationMarker, ALTERNATION_MARKER);
ast_node!(Entry, ENTRY);

// ── Annotations ──────────────────────────────────────────────────────

ast_node!(AnnotationLine, ANNOTATION_LINE);
ast_node!(AnnotationArgs, ANNOTATION_ARGS);
ast_node!(AnnotationArg, ANNOTATION_ARG);

// ── Diverts, tunnels, return ─────────────────────────────────────────

ast_node!(DivertStmt, DIVERT_STMT);
ast_node!(TunnelCall, TUNNEL_CALL);
ast_node!(DivertTarget, DIVERT_TARGET);
ast_node!(ReturnStmt, RETURN_STMT);
ast_node!(ReturnRedirect, RETURN_REDIRECT);

// ── Paths ────────────────────────────────────────────────────────────

ast_node!(Path, PATH);
ast_node!(PathSegment, PATH_SEGMENT);

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

ast_node!(IntegerLit, INTEGER_LIT);
ast_node!(FloatLit, FLOAT_LIT);
ast_node!(StringLit, STRING_LIT);
ast_node!(BooleanLit, BOOLEAN_LIT);
ast_node!(PathExpr, PATH_EXPR);
ast_node!(ParenExpr, PAREN_EXPR);
ast_node!(PrefixExpr, PREFIX_EXPR);
ast_node!(InfixExpr, INFIX_EXPR);
ast_node!(CallExpr, CALL_EXPR);
ast_node!(ArgList, ARG_LIST);
ast_node!(LambdaExpr, LAMBDA_EXPR);
ast_node!(LambdaParams, LAMBDA_PARAMS);

// ── The array/sequence literal (NG-D, issue #1490) ────────────────────

ast_node!(ArrayLiteral, ARRAY_LITERAL);

// ── The construction initializer (B5, issue #1464) ───────────────────

ast_node!(ConstructLiteral, CONSTRUCT_LITERAL);
ast_node!(ConstructEntry, CONSTRUCT_ENTRY);

// ── The code-ground statement layer (B0.8 Wave A) ────────────────────

ast_node!(StmtBlock, STMT_BLOCK);
ast_node!(LetStmt, LET_STMT);
ast_node!(AssignStmt, ASSIGN_STMT);
ast_node!(ExprStmt, EXPR_STMT);

// ── The code-ground control-flow layer (B0.8 Wave B) ─────────────────

ast_node!(IfStmt, IF_STMT);
ast_node!(ElseClause, ELSE_CLAUSE);
ast_node!(WhileStmt, WHILE_STMT);
ast_node!(ForStmt, FOR_STMT);
ast_node!(UntilStmt, UNTIL_STMT);

// ── The code-ground statement tail (B0.8 Wave B tail, issue #1322) ──

ast_node!(BreakStmt, BREAK_STMT);
ast_node!(ContinueStmt, CONTINUE_STMT);

// ── The type-annotation grammar (NG-A/B/C, #1487/#1488/#1489) ────────

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);

// ── The `as` binding (B1b, issue #1475) ──────────────────────────────

ast_node!(AsBinding, AS_BINDING);

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

ast_node!(Error, ERROR);

// ── Hand-written accessors ───────────────────────────────────────────

impl DocComment {
    /// `true` for the inner (`//!`) form — a run whose tokens are
    /// `DOC_COMMENT_INNER` rather than `DOC_COMMENT_OUTER`. One node shape
    /// covers both variants (`syntax_kind.rs`'s `DOC_COMMENT` doc); this is
    /// how callers tell them apart. A well-formed `DOC_COMMENT` node's
    /// comment tokens are always uniformly one kind or the other (the
    /// parser's `doc_comment::consume_doc_run` never mixes them within a
    /// single run), so checking the first one is sufficient.
    pub fn is_inner(&self) -> bool {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .any(|t| t.kind() == DOC_COMMENT_INNER)
    }

    /// Every doc-comment line in source order: the token's text with its
    /// `///`/`//!` marker stripped and a single leading space (if any)
    /// trimmed, paired with that token's source range — the same shape the
    /// OLD ink parser's `collect_doc_lines` produces, so both frontends
    /// feed the identical format-agnostic `hir::doc_block::parse_lines`
    /// tag parser.
    pub fn lines(&self) -> Vec<(String, rowan::TextRange)> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .filter(|t| matches!(t.kind(), DOC_COMMENT_OUTER | DOC_COMMENT_INNER))
            .map(|t| {
                let text = t.text();
                let body = text
                    .strip_prefix("///")
                    .or_else(|| text.strip_prefix("//!"))
                    .unwrap_or(text);
                (body.trim_start().to_string(), t.text_range())
            })
            .collect()
    }
}

impl SourceFile {
    /// Every top-level `flow`/`fn` declaration in the file (charter §4:
    /// "no one-flow-per-file constraint — files hold many declarations").
    pub fn flows(&self) -> impl Iterator<Item = FlowDecl> {
        support::children(&self.syntax)
    }

    /// Every top-level `fn` declaration in the file.
    pub fn fns(&self) -> impl Iterator<Item = FnDecl> {
        support::children(&self.syntax)
    }

    /// Every direct child node, typed as its own `SyntaxKind` where a
    /// wrapper exists — the generic escape hatch for callers that want to
    /// walk the whole item list without matching on every variant twice.
    pub fn syntax_children(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }

    /// The file-level inner `//!` doc comment, if the file opens with one
    /// (B0.6b: "documents the enclosing ... file"). CST-only for now — no
    /// native HIR type represents whole-file identity yet (`lower_native`'s
    /// module doc, judgment call #7), so nothing consumes this today; kept
    /// for the LSP/fmt/source-map consumers the ruling names.
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }
}

/// A `flow`/`fn` declaration's body — either the prose-ground [`Block`]
/// (`BLOCK`) or the code-ground [`StmtBlock`] (`STMT_BLOCK`), whichever the
/// body-dialect selector on the opening brace chose (charter §4, RULED
/// 2026-07-23: plain `{ }` = per-keyword default, `~{ }` = code-ground,
/// `>{ }` = prose-ground — see `parser::decl::decl_body`). One enum rather
/// than two separate `body()`/`code_body()` accessors, since a given
/// declaration's body is always exactly one or the other, never both.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Body {
    /// Prose-ground: content lines, choices, diverts (`fn`'s non-default
    /// spelling; `flow`'s default).
    Prose(Block),
    /// Code-ground: statements directly, no per-line `~` (`flow`'s
    /// non-default spelling — the "Compound guard"; `fn`'s default).
    Code(StmtBlock),
}

impl Body {
    /// The underlying syntax node, whichever variant this is.
    pub fn syntax(&self) -> &SyntaxNode {
        match self {
            Self::Prose(b) => b.syntax(),
            Self::Code(b) => b.syntax(),
        }
    }

    fn cast(node: SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::BLOCK => Block::cast(node).map(Self::Prose),
            SyntaxKind::STMT_BLOCK => StmtBlock::cast(node).map(Self::Code),
            _ => None,
        }
    }
}

impl FlowDecl {
    /// The declared name (the `IDENT` immediately after `flow`).
    pub fn name_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, IDENT)
    }

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

    /// The body-dialect selector chose either a prose [`Block`] (the
    /// `flow` default) or a code [`StmtBlock`] (the `~{ }` override, §3's
    /// "Compound guard") — see [`Body`].
    pub fn body(&self) -> Option<Body> {
        self.syntax.children().find_map(Body::cast)
    }

    /// Nested `flow` declarations directly inside this one's body — a
    /// stitch (charter §4: "stitches are nested `flow`s"). Only a
    /// prose-ground body can contain one (a code-ground `STMT_BLOCK`'s
    /// statement grammar has no declaration-dispatch arm — `parser/stmt.rs`
    /// never produces a `FLOW_DECL` child), so a `~{ }`-bodied flow simply
    /// yields none here, same as an empty body would.
    pub fn stitches(&self) -> impl Iterator<Item = FlowDecl> {
        match self.body() {
            Some(Body::Prose(b)) => support::children::<FlowDecl>(&b.syntax).collect::<Vec<_>>(),
            _ => Vec::new(),
        }
        .into_iter()
    }

    /// The header's `: type` return clause, if written (NG-C, #1489).
    /// Declaring one is the ruled coroutine-vs-state toggle: a flow *with*
    /// a return type must produce a value, and (unlike a plain flow) does
    /// not pick up the implicit `-> DONE` on fall-through.
    pub fn return_type(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// `true` if a `pub` keyword precedes this header (issue #1582, RULED
    /// 2026-08-03): opts the declaration into `VisibilityMark::Public`
    /// (`hir::lower_native::container::lower_top_level_container`/
    /// `lower_stitch` read this to populate `Knot`/`Stitch::visibility`).
    /// Absent, the declaration stays `Private` — the already-ratified
    /// 2026-07-23 default, unchanged by this accessor.
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

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

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

    /// The header's `: type` return clause, if written (NG-C, #1489) —
    /// `fn probability(g: Guest): float { … }`.
    pub fn return_type(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// The body-dialect selector chose either a code [`StmtBlock`] (the
    /// `fn` default) or a prose [`Block`] (the `>{ }` override) — see
    /// [`Body`].
    pub fn body(&self) -> Option<Body> {
        self.syntax.children().find_map(Body::cast)
    }

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// See [`FlowDecl::is_pub`].
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

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

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

    /// `true` if this parameter is `ref`-marked. Always `false` for a
    /// lambda parameter — `ref` captures don't exist (RULED 2026-07-23) and
    /// `parser/expr.rs::lambda_param` never accepts the keyword.
    pub fn is_ref(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_REF).is_some()
    }

    /// The parameter's `: type` annotation, if written (NG-A, #1487).
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }
}

impl Block {
    /// Every direct-child node in this block's body, in source order —
    /// the untyped escape hatch, since a `BLOCK`'s items span every
    /// declaration/body-line kind this crate defines. Includes a leading
    /// inner `DOC_COMMENT`, if present — callers that don't want it in
    /// their item stream (e.g. `hir::lower_native::body::lower_block`)
    /// filter it out themselves, same as they already skip other
    /// non-statement node kinds.
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }

    /// The inner `//!` doc comment, if this block opens with one (B0.6b):
    /// documents the enclosing knot/flow/stitch, not a following
    /// declaration. `None` for a `CHOICE_BODY`/`ELSE_BRANCH` — the parser
    /// never attaches an inner doc there (`parser::block::braced_item_list`
    /// only checks for one when building a real `BLOCK`).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }
}

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

    /// The initializer expression's root node, if the `=` clause was
    /// present. `var name = expr` always parses the initializer as exactly
    /// one child node (whatever expression-grammar kind it is) after the
    /// `IDENT`, so "the first child node that is neither the leading doc
    /// comment nor the `: type` annotation" is unambiguous.
    pub fn value(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| !is_binding_prefix(n.kind()))
    }

    /// The binding's `: type` annotation, if written (NG-B, #1488).
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// See [`FlowDecl::is_pub`].
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

/// Child-node kinds that precede a binding's initializer and must never be
/// mistaken for it: the leading `///` doc comment and the `: type`
/// annotation (NG-B, #1488). Shared by [`VarDecl::value`],
/// [`ConstDecl::value`] and [`LetStmt::value`] so a future prefix child
/// only has to be listed once.
fn is_binding_prefix(kind: SyntaxKind) -> bool {
    matches!(kind, SyntaxKind::DOC_COMMENT | SyntaxKind::TYPE_ANNOTATION)
}

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

    /// See [`VarDecl::value`].
    pub fn value(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| !is_binding_prefix(n.kind()))
    }

    /// See [`VarDecl::type_annotation`].
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// See [`FlowDecl::is_pub`].
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

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

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

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// See [`FlowDecl::is_pub`].
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

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

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

    /// `true` for a parenthesized member (`(name)`, the default-on entry).
    pub fn is_active(&self) -> bool {
        support::token(&self.syntax, L_PAREN).is_some()
    }
}

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

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

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// See [`FlowDecl::is_pub`].
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

// ── The type-annotation grammar (NG-A/B/C, #1487/#1488/#1489) ────────
//
// Shapes mirror the brink dialect's own TM-2 AST (`brink-syntax`'s
// `TypeAnnotation`/`TypeExpr`/`TypeName`/`TypeGeneric`/`TypeFn`) so both
// frontends can lower to the same `brink_ir::hir::TypeExpr`.

impl TypeAnnotation {
    /// The annotated type expression after the `:`.
    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 or depth-limited `TYPE_EXPR` — every
    /// well-formed one 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 name_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, IDENT)
    }

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

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

    /// The generic head name (e.g. `"list"`, `"map"`).
    pub fn name(&self) -> Option<String> {
        self.name_token().map(|t| t.text().to_string())
    }

    /// 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();
        exprs.pop(); // drop the return type (no-op when the list is empty)
        exprs
    }

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

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

    /// The field's `: type` annotation (NG-E, issue #1505) — a full
    /// `type_expr` (bare name, generic instantiation, or function type),
    /// the same production every other `: type` position in this grammar
    /// uses (`Param::type_annotation`, `VarDecl::type_annotation`, …).
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }
}

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

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

    /// The leading `///` doc comment, if one is attached (B0.6b).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }

    /// See [`FlowDecl::is_pub`].
    pub fn is_pub(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_PUB).is_some()
    }
}

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

    /// The leading `///` doc comment, if one is attached (B0.6b). No native
    /// HIR field consumes this yet (`Import` carries no `doc`, matching the
    /// OLD ink frontend's own `Import` shape) — CST-only for now, same
    /// status as [`SourceFile::doc`].
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }
}

impl UseDecl {
    pub fn tree(&self) -> Option<UseTree> {
        support::child(&self.syntax)
    }

    /// See [`ImportDecl::doc`].
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }
}

impl UseTree {
    /// The leading dotted/`::`-separated path segments, in order —
    /// `use_tree`'s grammar lays these out as bare `IDENT` tokens
    /// interspersed with `::` directly inside `USE_TREE` (no nested `PATH`
    /// node, unlike `import`'s path), so this walks direct-child tokens up
    /// to (not including) an `as`-alias or a nested `{ … }` list.
    pub fn path_segments(&self) -> impl Iterator<Item = SyntaxToken> + '_ {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .take_while(|t| t.kind() != SyntaxKind::KW_AS)
            .filter(|t| t.kind() == IDENT)
    }

    /// The `as alias` name, if this tree ends in one.
    pub fn alias_token(&self) -> Option<SyntaxToken> {
        let mut saw_as = false;
        for el in self.syntax.children_with_tokens() {
            let Some(tok) = el.into_token() else {
                continue;
            };
            if tok.kind().is_trivia() {
                continue;
            }
            if saw_as {
                return if tok.kind() == IDENT { Some(tok) } else { None };
            }
            if tok.kind() == SyntaxKind::KW_AS {
                saw_as = true;
            }
        }
        None
    }

    /// The nested `{ a, b as c, … }` group, if this tree has one.
    pub fn nested_list(&self) -> Option<UseTreeList> {
        support::child(&self.syntax)
    }
}

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

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

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

    /// See [`ImportDecl::doc`] — no native HIR "module container" node
    /// exists yet either (`lower_native`'s module doc, judgment call #4).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }
}

impl Path {
    /// Every `PATH_SEGMENT`'s `IDENT`, in order.
    pub fn segments(&self) -> impl Iterator<Item = SyntaxToken> {
        support::children::<PathSegment>(&self.syntax)
            .filter_map(|seg| support::token(&seg.syntax, IDENT))
    }

    /// `true` if any separator is `::` (crosses a module wall, charter
    /// §13.2) rather than only `.`.
    pub fn crosses_module_wall(&self) -> bool {
        support::tokens(&self.syntax, SyntaxKind::COLON_COLON)
            .next()
            .is_some()
    }
}

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

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

impl Choice {
    /// `true` for a sticky (`+`) choice, `false` for a once-only (`*`) one.
    ///
    /// B0.7 fix (`docs/b0-sequencing.md` §B0.7, issue #1176): the bullet
    /// token is wrapped in a nested `CHOICE_BULLET` node
    /// (`choice.rs::choice`: `p.start_node(CHOICE_BULLET); p.bump(); …`),
    /// never a direct token of `CHOICE` itself — `support::token` only
    /// looks at direct children, so the original B0.5/B0.6 implementation
    /// (`support::token(&self.syntax, PLUS)`) always returned `false`. Every
    /// choice line in the corpus was silently lowering as once-only; caught
    /// by B0.7's `choice_point_lowers_to_choice_set_with_sticky_and_once`
    /// test, the first real exercise of a sticky (`+`) choice line.
    pub fn is_sticky(&self) -> bool {
        support::child::<ChoiceBullet>(&self.syntax)
            .is_some_and(|b| support::token(&b.syntax, SyntaxKind::PLUS).is_some())
    }

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

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

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

impl AnnotationLine {
    /// The directive/annotation name (`effects`, …).
    pub fn name_token(&self) -> Option<SyntaxToken> {
        support::token(&self.syntax, IDENT)
    }

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

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

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

    /// The nested paren-clause (`reads(gold, hp)` inside `effects(…)`), if
    /// this argument has one.
    pub fn nested_args(&self) -> Option<AnnotationArgs> {
        support::child(&self.syntax)
    }

    /// The unquoted `::`-separated module `PATH` (`story::old::path`), if
    /// this argument is one (issue #1349, `@[was(story::old::path)]`'s
    /// arg form). `name_token` is `None` for this shape — the arg's direct
    /// child is a `PATH` node, not a bare `IDENT` token.
    pub fn path(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

    /// The `= "value"` clause's string-literal value (issue #1719,
    /// `@[element(args = "…")]` / `@[style(chan = "…")]`), if this argument
    /// has one. `None` for the bare-`IDENT`, nested-clause, path, and
    /// numeric-literal shapes — only the key/value form parses a
    /// `STRING_LIT` as a **sibling** of the key `IDENT` rather than the
    /// arg's sole child.
    pub fn eq_value(&self) -> Option<StringLit> {
        support::child(&self.syntax)
    }

    /// The `= <integer>` clause's integer-literal value (issue #2164,
    /// `@[convention(…, order = 30)]` — the ordering key is a bare integer,
    /// RULED). `None` for every other clause shape, including the string
    /// key/value form [`Self::eq_value`] reads — a clause carries at most
    /// one of the two, never both.
    pub fn eq_int_value(&self) -> Option<IntegerLit> {
        support::child(&self.syntax)
    }

    /// The `= <ident>` clause's bare-identifier value (issue #2178,
    /// `@[convention(…, attach = Cue)]` — the attached schema names a
    /// declared `struct`, so this clause is a bare identifier, not a
    /// quoted string or integer literal). `None` for every other clause
    /// shape.
    ///
    /// Unlike [`Self::eq_value`]/[`Self::eq_int_value`], this is not a
    /// distinct child *node* kind — the value is bumped as a second bare
    /// `IDENT` token, a sibling of the key's own `IDENT` token (see
    /// `parser::annotation::annotation_arg`'s `IDENT` arm). So this reads
    /// the **second** direct-child `IDENT` token, not the first (which
    /// [`Self::name_token`] already owns).
    pub fn eq_ident_value(&self) -> Option<SyntaxToken> {
        support::tokens(&self.syntax, IDENT).nth(1)
    }
}

impl CallExpr {
    /// The callee path. Fixed for B0.6 (`docs/b0-sequencing.md` §B0.6):
    /// `expr::path_or_call` wraps a bare `PATH` node directly (not a nested
    /// `PATH_EXPR`) when it commits to `CALL_EXPR` — the previous
    /// `Option<PathExpr>` signature could never cast successfully against
    /// the real grammar shape and always returned `None` for every call
    /// expression. No test exercised it before B0.6's lowering needed it.
    pub fn callee(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

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

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

impl ArrayLiteral {
    /// The literal's element expressions, in source order. Empty for `[]`.
    /// Raw `SyntaxNode` children, same idiom `CallExpr::arg_list`'s callers
    /// use for `ARG_LIST` — this crate has no `ast::Expr` union type to cast
    /// into (unlike `brink-syntax`'s own `ArrayLiteral::elements`).
    pub fn elements(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }
}

impl ConstructLiteral {
    /// The constructed type's name path — `Map`, `Flags`, `Weighted`, a
    /// declared struct's name, or a `::`-qualified spelling of any of them.
    /// Which of those it *is* is dispatch, not grammar: `brink-ir`'s
    /// `construct` registry resolves it (`docs/stdlib-spec.md` §9.6).
    pub fn type_path(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

    /// The literal's entries, in source order. Empty for `TypeName { }`.
    pub fn entries(&self) -> impl Iterator<Item = ConstructEntry> {
        support::children(&self.syntax)
    }
}

impl ConstructEntry {
    /// `true` for the pair/field form (`k: v`), `false` for the element
    /// form (`v`) — read off the `COLON` token the parser emits between the
    /// two expressions, so it never depends on child-count guessing.
    pub fn is_pair(&self) -> bool {
        support::token(&self.syntax, crate::SyntaxKind::COLON).is_some()
    }

    /// The left-hand expression of a pair/field entry (`k` in `k: v`), or
    /// `None` for the element form.
    pub fn key(&self) -> Option<SyntaxNode> {
        if self.is_pair() {
            self.syntax.children().next()
        } else {
            None
        }
    }

    /// The entry's value expression: the right-hand side of a pair/field
    /// entry, or the single expression of an element entry.
    pub fn value(&self) -> Option<SyntaxNode> {
        let mut children = self.syntax.children();
        let first = children.next();
        if self.is_pair() {
            children.next()
        } else {
            first
        }
    }
}

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

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

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

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

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

impl ParenExpr {
    /// The parenthesized inner expression's root node.
    pub fn inner(&self) -> Option<SyntaxNode> {
        self.syntax.children().next()
    }
}

impl LambdaExpr {
    /// The `|…|` parameter row (issue #1685). `None` only for a malformed
    /// node — `parser/expr.rs::lambda_expr` always opens with one, even for
    /// the zero-arg `||` form (whose row is simply empty).
    pub fn params(&self) -> Option<LambdaParams> {
        support::child(&self.syntax)
    }

    /// The `: type` **return** annotation (`|g|: bool { … }`), if written.
    ///
    /// Unambiguous as a direct child: a *parameter's* own annotation lives
    /// inside that parameter's `PARAM` node, itself inside `LAMBDA_PARAMS`,
    /// so the only `TYPE_ANNOTATION` directly under `LAMBDA_EXPR` is the
    /// return one.
    pub fn return_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }

    /// The body's root node — the single expression (`|g| g.awake`) or the
    /// braced `STMT_BLOCK` (`|g|: bool { … }`). The last child, since the
    /// parser emits params, then the optional return annotation, then the
    /// body.
    pub fn body(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .filter(|n| {
                !matches!(
                    n.kind(),
                    SyntaxKind::LAMBDA_PARAMS | SyntaxKind::TYPE_ANNOTATION
                )
            })
            .last()
    }
}

impl LambdaParams {
    /// The parameters, in source order — the same `PARAM` node the
    /// declaration grammar uses, so `Param`'s accessors read a lambda
    /// parameter exactly as they read a `fn` one. Empty for `||`.
    pub fn params(&self) -> impl Iterator<Item = Param> {
        support::children(&self.syntax)
    }
}

impl PrefixExpr {
    /// The prefix operator token (`-` or `!`).
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|t| matches!(t.kind(), SyntaxKind::MINUS | SyntaxKind::BANG))
    }

    /// The operand's root node.
    pub fn operand(&self) -> Option<SyntaxNode> {
        self.syntax.children().next()
    }
}

impl InfixExpr {
    /// The left-hand operand's root node (the first child node).
    pub fn lhs(&self) -> Option<SyntaxNode> {
        self.syntax.children().next()
    }

    /// The right-hand operand's root node (the last child node).
    pub fn rhs(&self) -> Option<SyntaxNode> {
        self.syntax.children().last()
    }

    /// The operator token. Two adjacent `PIPE`s (`||`) are represented as
    /// two tokens (see `expr::infix_binding_power`'s doc) — this returns
    /// the *first* one; callers that need to distinguish `|` from `||`
    /// check [`Self::is_double_pipe`].
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|t| {
                matches!(
                    t.kind(),
                    SyntaxKind::AMP_AMP
                        | SyntaxKind::EQ_EQ
                        | SyntaxKind::BANG_EQ
                        | SyntaxKind::LT
                        | SyntaxKind::GT
                        | SyntaxKind::LT_EQ
                        | SyntaxKind::GT_EQ
                        | SyntaxKind::PLUS
                        | SyntaxKind::MINUS
                        | SyntaxKind::STAR
                        | SyntaxKind::SLASH
                        | SyntaxKind::PERCENT
                        | SyntaxKind::PIPE
                        | SyntaxKind::KW_OR
                )
            })
    }

    /// `true` if the operator is `||` (two adjacent `PIPE` tokens) rather
    /// than a single-token operator.
    pub fn is_double_pipe(&self) -> bool {
        let mut pipes = self
            .syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .filter(|t| t.kind() == SyntaxKind::PIPE);
        pipes.next().is_some() && pipes.next().is_some()
    }
}

impl ArgList {
    /// `true` if this arg list opens with `(` at all (always true for a
    /// well-formed parse — exposed for error-recovery callers that walk a
    /// possibly-malformed tree).
    pub fn is_open(&self) -> bool {
        support::token(&self.syntax, L_PAREN).is_some()
    }
}

impl DivertTarget {
    pub fn is_end(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_END).is_some()
    }

    pub fn is_done(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_DONE).is_some()
    }

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

    /// The `(args)` in `-> knot(args)`, if any (charter §11: diverts keep
    /// call-style args verbatim from ink). A direct `ARG_LIST` sibling of
    /// `path()` under `DIVERT_TARGET`, not wrapped in a `CALL_EXPR` — a
    /// divert target is not an expression.
    pub fn call_args(&self) -> Option<ArgList> {
        support::child(&self.syntax)
    }
}

// ── B0.7 additions: body-dialect accessors ──────────────────────────
//
// Everything below was added for `hir::lower_native`'s body lowering
// (`docs/b0-sequencing.md` §B0.7). B0.5/B0.6 hand-wrote a representative
// subset of accessors "enough to prove the pattern end-to-end ... not
// pre-building every accessor a later lowering pass might want" (this
// file's module doc) — B0.7 is exactly that later pass.

impl ContentLine {
    /// The leading `(name)` label, if this line opens with one (G-1).
    pub fn label(&self) -> Option<Label> {
        support::child(&self.syntax)
    }
}

impl LogicLine {
    /// The wrapped `~ let name = expr`, when this logic line is a temp
    /// declaration (`parser/stmt.rs::logic_line`'s `KW_LET` branch, issue
    /// #1972).
    pub fn let_stmt(&self) -> Option<LetStmt> {
        support::child(&self.syntax)
    }

    /// The wrapped `~ x = expr` / `~ x += expr`, when this logic line is an
    /// assignment (`parser/stmt.rs::logic_line`'s `at_assignment` branch).
    pub fn assign_stmt(&self) -> Option<AssignStmt> {
        support::child(&self.syntax)
    }

    /// The wrapped `~ expr` — an expression evaluated for its side effect
    /// (e.g. a function call) — when this logic line is neither a temp
    /// declaration nor an assignment.
    pub fn expr_stmt(&self) -> Option<ExprStmt> {
        support::child(&self.syntax)
    }

    /// The wrapped `~ until cond`, when this logic line is a condition-park
    /// escape — native's sole `await` spelling (issue #1972,
    /// `parser/stmt.rs::logic_line`'s `KW_UNTIL` branch).
    pub fn until_stmt(&self) -> Option<UntilStmt> {
        support::child(&self.syntax)
    }

    /// The wrapped `~{ … }` multi-statement logic block, when this logic
    /// line is a T1b-style block escape (issue #1972,
    /// `parser/stmt.rs::logic_line`'s `L_BRACE` branch). Reuses
    /// [`StmtBlock`]'s grammar unmodified — the same node kind a `fn`'s
    /// default body or a `flow`'s whole-body `~{ }` override use.
    pub fn stmt_block(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }
}

impl ProseLine {
    /// The wrapped `> text` content line — the mirror image of
    /// [`LogicLine`]'s own wrapped children (`parser/stmt.rs::prose_line`),
    /// reusing [`ContentLine`]'s grammar unmodified.
    pub fn content_line(&self) -> Option<ContentLine> {
        support::child(&self.syntax)
    }
}

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

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

impl TunnelCall {
    /// The one divert target between the opening and closing `->` (native's
    /// `-> place ->` shape carries exactly one target, unlike ink's chained
    /// `-> a -> b ->`).
    pub fn target(&self) -> Option<DivertTarget> {
        support::child(&self.syntax)
    }
}

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

impl ReturnStmt {
    /// The value expression, if any — `RETURN_STMT`'s only child node.
    /// `Some`/`None` for both grammars now: the content-ground bare
    /// `return`/`return <expr>`/`return -> x` (`parser/divert.rs::
    /// return_stmt` — the value is optional, and `-> x` is a distinct
    /// `RETURN_REDIRECT` node, never this accessor's concern; issue #1973
    /// added the value case, previously always `None` here) and the
    /// code-ground `return e?;` (B0.8 Wave B tail, issue #1322,
    /// `parser/stmt.rs::return_stmt` — the initializer was already
    /// optional there). See `syntax_kind.rs`'s `RETURN_STMT` doc for why
    /// one node shape serves both grammars.
    pub fn value(&self) -> Option<SyntaxNode> {
        self.syntax.children().next()
    }
}

impl Choice {
    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)
    }
}

impl ChoiceGuard {
    /// The guard's condition expression — `CHOICE_GUARD`'s first child node
    /// (`L_BRACE KW_IF expression (AS_BINDING)? R_BRACE`; the braces/keyword
    /// are tokens).
    pub fn expr(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| n.kind() != SyntaxKind::AS_BINDING)
    }

    /// The `as NAME` binding, when the author wrote one. Implemented
    /// (issue #1508): `brink-ir`'s choice lowering (`hir::Choice::binding`)
    /// captures at presentation time via the same `OptionBind`
    /// frame-slot machinery the statement/template forms already use
    /// (`parser/choice.rs::choice_guard`'s doc). `E146` is retired.
    pub fn as_binding(&self) -> Option<AsBinding> {
        support::child(&self.syntax)
    }
}

impl ChoiceBody {
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }
}

impl ElseBranch {
    /// The nested `CHOICE_BODY`, when this `else` belongs to a choice point
    /// (`choice.rs::else_branch` — always braced, no colon form).
    pub fn choice_body(&self) -> Option<ChoiceBody> {
        support::child(&self.syntax)
    }

    /// The nested `BLOCK`, when this `else` belongs to the conditional
    /// family's braced-arm form (`{if cond {…} else {…}}`).
    pub fn block(&self) -> Option<Block> {
        support::child(&self.syntax)
    }

    /// Every direct-child item, for the conditional family's colon-body
    /// form (`{if cond: … else: …}`), where body items are direct children
    /// with no wrapper node (`family.rs::colon_body`).
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }
}

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

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

impl ConditionalBlock {
    pub fn is_if(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_IF).is_some()
    }

    pub fn is_match(&self) -> bool {
        support::token(&self.syntax, SyntaxKind::KW_MATCH).is_some()
    }

    /// The head expression: the `if` condition or the `match` subject —
    /// `CONDITIONAL_BLOCK`'s only child node that isn't an arm/else
    /// (`family.rs::conditional_block`: the expression is parsed directly
    /// into this node before the arm(s)).
    pub fn condition(&self) -> Option<SyntaxNode> {
        self.syntax.children().find(|n| {
            !matches!(
                n.kind(),
                SyntaxKind::IF_ARM
                    | SyntaxKind::ELSE_BRANCH
                    | SyntaxKind::MATCH_ARM
                    | SyntaxKind::AS_BINDING
            )
        })
    }

    /// The `as NAME` binding (B1b, issue #1475) of the template condition
    /// form `{if EXPR as NAME: … else: …}`, when present. Never set for
    /// `match` — a `match` head is a subject, not a condition.
    pub fn as_binding(&self) -> Option<AsBinding> {
        support::child(&self.syntax)
    }

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

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

    /// `match`'s arms — direct children of `CONDITIONAL_BLOCK` itself
    /// (`family.rs::match_arm_list` opens no wrapper node of its own).
    pub fn match_arms(&self) -> impl Iterator<Item = MatchArm> {
        support::children(&self.syntax)
    }
}

impl IfArm {
    /// The nested `BLOCK`, for the braced-arm form.
    pub fn block(&self) -> Option<Block> {
        support::child(&self.syntax)
    }

    /// Direct-child items, for the colon-body form (see `ElseBranch::items`).
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }
}

impl MatchArm {
    /// The pattern's expression — `MATCH_PATTERN`'s only child node.
    pub fn pattern_expr(&self) -> Option<SyntaxNode> {
        support::child::<MatchPattern>(&self.syntax).and_then(|p| p.syntax.children().next())
    }

    /// The nested `BLOCK`, for a braced arm body (`pattern => { … }`).
    pub fn block(&self) -> Option<Block> {
        support::child(&self.syntax)
    }

    /// The bare expression, for an unbraced arm body (`pattern => expr`) —
    /// the one child node that is neither `MATCH_PATTERN` nor `BLOCK`.
    pub fn bare_expr(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| !matches!(n.kind(), SyntaxKind::MATCH_PATTERN | SyntaxKind::BLOCK))
    }
}

impl AlternationBlock {
    /// The `~`/`&`/`!`/`|` marker token.
    pub fn marker_token(&self) -> Option<SyntaxToken> {
        support::child::<AlternationMarker>(&self.syntax).and_then(|m| {
            m.syntax
                .children_with_tokens()
                .filter_map(rowan::NodeOrToken::into_token)
                .find(|t| {
                    matches!(
                        t.kind(),
                        SyntaxKind::TILDE | SyntaxKind::AMP | SyntaxKind::BANG | SyntaxKind::PIPE
                    )
                })
        })
    }

    /// The multiline `-`-prefixed entries, if this block used that form
    /// (`family.rs::multiline_entries`). Empty for the single-line
    /// pipe-separated form — see [`Self::syntax`] for the raw child walk
    /// callers need for that form instead (no per-alternative wrapper node
    /// exists for it, `family.rs::inline_alternatives`).
    pub fn entries(&self) -> impl Iterator<Item = Entry> {
        support::children(&self.syntax)
    }
}

impl Entry {
    /// Every direct-child item inside this `-`-prefixed entry (the leading
    /// `MINUS` is a token, filtered out by `.children()`).
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }
}

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

impl Tag {
    /// The tag's own text: the leading `#` sigil dropped, surrounding
    /// source whitespace trimmed, and a *recognized* inline escape's
    /// backslash stripped (§8d.6, issue #2045) — parity with
    /// `markup::escape`'s stripping in ordinary content. `tag()`'s raw
    /// free-text scan (`parser::content::tag`) never builds an `ESCAPE`
    /// sub-node the way the shared content engine does, so there is no
    /// node-level place to skip the backslash the way `push_escape` does
    /// downstream; this accessor is that place instead — the single
    /// materialization point every consumer of "the tag's text" should go
    /// through, mirroring [`SceneTitle::text`]/[`CueName::text`].
    pub fn text(&self) -> String {
        let mut skipped_leading_hash = false;
        let mut raw = String::new();
        for tok in self
            .syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
        {
            if !skipped_leading_hash && tok.kind() == HASH {
                skipped_leading_hash = true;
                continue;
            }
            raw.push_str(tok.text());
        }
        strip_recognized_escape_backslashes(raw.trim())
    }
}

/// Strip the backslash from a *recognized* inline escape (`\< \{ \# \\`,
/// §8d.6 — the set is final) inside already-assembled raw text, achieving
/// parity with `markup::escape`'s stripping behavior for ordinary content
/// (issue #2045). `tag()`/`cue_name()`/`scene_title()` are raw free-text
/// scanners with no `ESCAPE` sub-node to strip at build time (unlike the
/// shared content engine); this is the one shared place their `text()`
/// accessors funnel through instead, so the three stay self-consistent
/// rather than drifting into three near-identical hand-rolled copies.
///
/// This is the *same* greedy left-to-right consumption `markup::escape`
/// itself performs: scanning forward, a lone `\` immediately followed by
/// one of `< { # \` consumes both and emits the escaped char literally;
/// any other `\` (followed by something else, or by nothing) is emitted
/// as itself and only that one character is consumed before continuing.
/// This is provably identical to the parser's own odd/even run-parity
/// reading these scanners use for structural purposes (#1852/#1738: `N`
/// consecutive backslashes before `<`/`{`/`#` only escape it when `N` is
/// odd, because greedily consuming pairs left-to-right leaves exactly one
/// unpaired backslash when `N` is odd and none when `N` is even) — so no
/// parser change is needed here, and no structural test moves. Unlike the
/// prior run-parity-only reading, this also collapses a bare `\\` pair
/// with nothing recognized following it (`a\\b` -> `a\b`), because that is
/// exactly what `markup::escape`'s greedy consumption does too: the first
/// backslash of the pair escapes the second, regardless of what follows.
fn strip_recognized_escape_backslashes(text: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '\\' && matches!(chars.get(i + 1), Some('<' | '{' | '#' | '\\')) {
            let escaped = chars[i + 1];
            out.push(escaped);
            i += 2;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

// ── B0.8 Wave A additions: the code-ground statement layer ──────────
//
// `docs/decision-log.md` 2026-07-23 "Code-ground sitting" — parser only,
// no lowering yet (`parser/stmt.rs`'s module doc).

impl StmtBlock {
    /// Every direct-child statement (`LET_STMT`/`ASSIGN_STMT`/`EXPR_STMT`)
    /// AND the tail expression if present, in source order — the untyped
    /// escape hatch, same shape as [`Block::items`].
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }

    /// The block's unterminated trailing expression (blocks-as-values), if
    /// one is present — the last child, when its kind is none of the
    /// statement-wrapper kinds this grammar can produce as a genuine
    /// statement (`parser/stmt.rs::stmt_block` never emits any node after
    /// the tail, so the last child is *always* the tail when it isn't one
    /// of those). B0.8 Wave B's four control-flow kinds
    /// (`IF_STMT`/`WHILE_STMT`/`FOR_STMT`/`UNTIL_STMT`) never produce a
    /// value and are always fully delimited by their own body/`;` — same
    /// non-tail treatment as the three Wave A kinds, not new behavior.
    /// B0.8 Wave B tail (issue #1322) adds `RETURN_STMT`/`BREAK_STMT`/
    /// `CONTINUE_STMT` to this same non-tail set — all three are always
    /// `;`-terminated in code-ground position (`parser/stmt.rs`'s
    /// `return_stmt`/`break_stmt`/`continue_stmt`), never a bare tail
    /// value. The `> text` prose-line escape (issue #1992) adds
    /// `PROSE_LINE` to the set for the same reason: it never produces a
    /// value (`parser/stmt.rs::statement`'s doc), so a `STMT_BLOCK` ending
    /// in one has no tail expression, not a prose line masquerading as one
    /// (review finding F2 — `lower_native/lambda.rs`'s `block.tail()` call
    /// would otherwise lower it as a lambda's return value instead of
    /// reaching `lower_block_item`'s loud `E129` arm).
    pub fn tail(&self) -> Option<SyntaxNode> {
        let last = self.syntax.children().last()?;
        (!matches!(
            last.kind(),
            SyntaxKind::LET_STMT
                | SyntaxKind::ASSIGN_STMT
                | SyntaxKind::EXPR_STMT
                | SyntaxKind::IF_STMT
                | SyntaxKind::WHILE_STMT
                | SyntaxKind::FOR_STMT
                | SyntaxKind::UNTIL_STMT
                | SyntaxKind::RETURN_STMT
                | SyntaxKind::BREAK_STMT
                | SyntaxKind::CONTINUE_STMT
                | SyntaxKind::PROSE_LINE
        ))
        .then_some(last)
    }
}

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

    /// The initializer expression's root node, if the `=` clause was
    /// present (optional, see `parser/stmt.rs::let_stmt`'s doc comment).
    pub fn value(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| !is_binding_prefix(n.kind()))
    }

    /// The binding's `: type` annotation, if written (NG-B, #1488).
    pub fn type_annotation(&self) -> Option<TypeAnnotation> {
        support::child(&self.syntax)
    }
}

impl AssignStmt {
    /// The assignment's place path (`x` / `x.field`).
    pub fn place(&self) -> Option<Path> {
        support::child(&self.syntax)
    }

    /// The right-hand-side expression's root node (the last child node,
    /// same convention as [`InfixExpr::rhs`]).
    pub fn value(&self) -> Option<SyntaxNode> {
        self.syntax.children().last()
    }

    /// The assignment operator token (`=`, `+=`, or `-=` — B0.8 Wave B
    /// tail, issue #1322, decision-log 2026-07-23 "Code-ground sitting":
    /// "compound/RMW assignment"). Mirrors the brink-dialect's own
    /// `Assignment::op_token` (`brink-syntax`) exactly, including which
    /// operators exist — `AssignOp` (`brink-ir`) only has `Set`/`Add`/`Sub`,
    /// so `*=`/`/=` (lexed as `STAR_EQ`/`SLASH_EQ` but never produced by
    /// `parser/stmt.rs::assign_stmt`) have no lowering target and aren't
    /// looked for here either.
    pub fn op_token(&self) -> Option<SyntaxToken> {
        self.syntax
            .children_with_tokens()
            .filter_map(rowan::NodeOrToken::into_token)
            .find(|tok| {
                matches!(
                    tok.kind(),
                    SyntaxKind::EQ | SyntaxKind::PLUS_EQ | SyntaxKind::MINUS_EQ
                )
            })
    }
}

impl ExprStmt {
    /// The wrapped expression's root node.
    pub fn expr(&self) -> Option<SyntaxNode> {
        self.syntax.children().next()
    }
}

// ── B0.8 Wave B additions: the code-ground control-flow layer ───────
//
// `docs/decision-log.md` 2026-07-23 "Code-ground sitting", issue #1177.
// `parser/control_flow.rs`'s module doc has the full grammar shape.

impl IfStmt {
    /// The head condition — `IF_STMT`'s only child node that isn't the
    /// `STMT_BLOCK` body, the trailing `ELSE_CLAUSE`, or the `AS_BINDING`
    /// suffix (mirrors `ConditionalBlock::condition`'s same-shaped lookup).
    pub fn condition(&self) -> Option<SyntaxNode> {
        self.syntax.children().find(|n| {
            !matches!(
                n.kind(),
                SyntaxKind::STMT_BLOCK | SyntaxKind::ELSE_CLAUSE | SyntaxKind::AS_BINDING
            )
        })
    }

    /// The `as NAME` binding (B1b, issue #1475), when the condition carries
    /// one.
    pub fn as_binding(&self) -> Option<AsBinding> {
        support::child(&self.syntax)
    }

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

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

impl AsBinding {
    /// The bound name (`as NAME`). `None` only for a malformed binding the
    /// parser already diagnosed (`as` with no identifier after it).
    pub fn name_token(&self) -> Option<SyntaxToken> {
        support::tokens(&self.syntax, IDENT).next()
    }
}

impl ElseClause {
    /// `else if cond { … }` — the arm's entire body is a nested `IF_STMT`,
    /// with no `STMT_BLOCK` wrapper of its own (`control_flow.rs::
    /// else_clause`'s flat-chain shape).
    pub fn if_stmt(&self) -> Option<IfStmt> {
        support::child(&self.syntax)
    }

    /// `else { … }` — the plain form.
    pub fn body(&self) -> Option<StmtBlock> {
        support::child(&self.syntax)
    }
}

impl WhileStmt {
    /// The loop condition — `WHILE_STMT`'s only child node that isn't the
    /// `STMT_BLOCK` body or the `AS_BINDING` suffix.
    pub fn condition(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| !matches!(n.kind(), SyntaxKind::STMT_BLOCK | SyntaxKind::AS_BINDING))
    }

    /// The `as NAME` binding (B1b, issue #1475), when the condition carries
    /// one. Rebinds on every iteration — the condition (and with it this
    /// binding) is re-evaluated per pass.
    pub fn as_binding(&self) -> Option<AsBinding> {
        support::child(&self.syntax)
    }

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

impl ForStmt {
    /// The loop-binding identifier (`for NAME in …`) — the key binding for
    /// the two-binding form (`for NAME, val_name in …`).
    pub fn name_token(&self) -> Option<SyntaxToken> {
        support::tokens(&self.syntax, IDENT).next()
    }

    /// The second loop-binding identifier (`for key, VAL in …`), when
    /// present — two-binding map iteration (B2, issue #1461,
    /// docs/stdlib-spec.md §5/§9's F10 ruling). `None` for the
    /// single-binding form. Both binding idents are direct `FOR_STMT`
    /// tokens (the iterable and body are nested nodes, never direct
    /// `IDENT` children), so the second direct `IDENT` token is
    /// unambiguously this binding.
    pub fn val_name_token(&self) -> Option<SyntaxToken> {
        support::tokens(&self.syntax, IDENT).nth(1)
    }

    /// The iterable expression — `FOR_STMT`'s only child node that isn't
    /// the `STMT_BLOCK` body.
    pub fn iterable(&self) -> Option<SyntaxNode> {
        self.syntax
            .children()
            .find(|n| n.kind() != SyntaxKind::STMT_BLOCK)
    }

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

impl UntilStmt {
    /// The park condition — `UNTIL_STMT`'s only child node.
    pub fn condition(&self) -> Option<SyntaxNode> {
        self.syntax.children().next()
    }
}

// ── Prose block elements (#1715; docs/prose-dialect-spec.md §8b/§8d) ──
//
// Accessors for the ruled screenplay-preset shapes. Nothing here lowers —
// `hir::lower_native` meets these nodes at its loud-`E129` arm until the
// attachment/`lower:` slice (issue #1717) lands; these exist so that slice,
// the formatter and the editor read the shapes through one typed surface
// rather than each re-deriving them from raw `SyntaxKind`s.

impl SceneStitch {
    /// The heading line that opens this header-scoped stitch.
    pub fn heading(&self) -> Option<SceneHeading> {
        support::child(&self.syntax)
    }

    /// The braceless body the heading scopes — every item up to the next
    /// heading or the enclosing close (§8b.2).
    pub fn body(&self) -> Option<SceneBody> {
        support::child(&self.syntax)
    }

    /// The leading `///` run documenting this stitch, if any (B0.6b — a
    /// heading declares a stitch, so it documents like one).
    pub fn doc(&self) -> Option<DocComment> {
        support::child(&self.syntax)
    }
}

impl SceneHeading {
    /// The title run — the scene's **display name** (§3.3).
    pub fn title(&self) -> Option<SceneTitle> {
        support::child(&self.syntax)
    }

    /// The explicit `[slug]`, if the heading spells its address (§8b.3).
    /// `None` means the address is inferred from the title, which makes
    /// the title load-bearing for `DefinitionId` (§3.3's save-key note).
    pub fn slug(&self) -> Option<SceneSlug> {
        support::child(&self.syntax)
    }

    /// Trailing `#tag`s — container-level per-flow tags (§8b.4).
    pub fn tags(&self) -> impl Iterator<Item = Tag> {
        support::children(&self.syntax)
    }
}

impl SceneTitle {
    /// The title text, with the surrounding source whitespace trimmed and
    /// a *recognized* inline escape's backslash stripped (§8d.6, issue
    /// #2045) — parity with `markup::escape`'s stripping in ordinary
    /// content. See [`Tag::text`] for the shared rationale.
    pub fn text(&self) -> String {
        strip_recognized_escape_backslashes(self.syntax.text().to_string().trim())
    }
}

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

impl SceneBody {
    /// The body's items, in source order.
    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> {
        self.syntax.children()
    }
}

impl Cue {
    /// The speaker name after the `@` sigil.
    pub fn name(&self) -> Option<CueName> {
        support::child(&self.syntax)
    }

    /// The cue's trailing tags — the ruled home for cue *extensions*
    /// (§8d.4: `@VENDOR #(v.o.)`, no parsed `ext` capture).
    pub fn tags(&self) -> impl Iterator<Item = Tag> {
        support::children(&self.syntax)
    }
}

impl CueName {
    /// The speaker name, with the surrounding source whitespace trimmed
    /// and a *recognized* inline escape's backslash stripped (§8d.6,
    /// issue #2045) — parity with `markup::escape`'s stripping in
    /// ordinary content. See [`Tag::text`] for the shared rationale.
    pub fn text(&self) -> String {
        strip_recognized_escape_backslashes(self.syntax.text().to_string().trim())
    }
}

impl CompactCue {
    /// The speaker name before the `:`.
    pub fn name(&self) -> Option<CueName> {
        support::child(&self.syntax)
    }

    /// The fused dialogue line after the `:` (§8b.9).
    pub fn line(&self) -> Option<ContentLine> {
        support::child(&self.syntax)
    }
}

impl BangDispatch {
    /// The dispatching name after the `!` sigil.
    pub fn name(&self) -> Option<DispatchName> {
        support::child(&self.syntax)
    }

    /// The remainder after the name — a fused content line, the same way
    /// [`CompactCue::line`] fuses its dialogue line.
    pub fn line(&self) -> Option<ContentLine> {
        support::child(&self.syntax)
    }
}

impl DispatchName {
    /// The dispatching name, with the surrounding source whitespace
    /// trimmed.
    pub fn text(&self) -> String {
        self.syntax.text().to_string().trim().to_owned()
    }
}

impl Parenthetical {
    /// The delivery text between the parentheses, trimmed.
    pub fn text(&self) -> String {
        support::child::<Text>(&self.syntax)
            .map(|t| t.syntax().text().to_string().trim().to_owned())
            .unwrap_or_default()
    }

    /// Trailing `#tag`s on the parenthetical line, if any.
    pub fn tags(&self) -> impl Iterator<Item = Tag> {
        support::children(&self.syntax)
    }
}

impl FlowDecl {
    /// Trailing `#tag`s on the `flow` header line — container-level
    /// per-flow tags (§8b.4, the authoring surface issue #474's per-flow
    /// tag APIs were iceboxed waiting for). Parsed here; the runtime-side
    /// API is #474's own work, so `hir::lower_native` reports them as
    /// not-yet-lowered rather than dropping them.
    pub fn tags(&self) -> impl Iterator<Item = Tag> {
        support::children(&self.syntax)
    }
}