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
//! Natural-notation element dispatch (issue #1838) — the slice that makes
//! the prose grammar *mean* something.
//!
//! `docs/decision-log.md`'s 2026-07-31 ruling ("Conventions are annotated
//! handlers: the declarative element surface is subsumed by the annotation
//! surface") collapsed two element mechanisms into one: **a preset element
//! is literally an annotated handler.** A scene heading is a matched line,
//! captures bound to params by name, and *exactly one call* — the same
//! three steps `!radio` takes, minus the sigil. The `lower:` column, the
//! `Conventions` type and the chain-rule engine are dissolved by that same
//! ruling and are deliberately absent here.
//!
//! ```brink
//! @[convention(claims = "^INT\\. (?<place>.+)$", order = 10)]
//! fn interior(place) { return "— inside " + place + " —"; }
//!
//! flow main() {
//! INT. MARKET SQUARE
//! }
//! ```
//!
//! Issue #2164 (`docs/decision-log.md` 2026-08-03) split the annotation
//! this module was written against: `claims = "…"` moved from
//! `@[element(…)]` to its own `@[convention(…)]` name, gaining a required
//! `order` property that now drives the precedence this module's own
//! doc describes below — see [`super::annotation`]'s module doc for the
//! full split.
//!
//! The heading line no longer reaches `body::lower_one_item`'s loud-`E129`
//! arm: it is claimed, `place` binds to `MARKET SQUARE`, and the line
//! lowers to one call whose value *is* the line.
//!
//! # No invisible expansion
//!
//! Every claimed line is recorded as a [`crate::ElementMatch`] on the
//! `HirFile` — the claimed range, the prose shape it was written as, the
//! handler's name **and the annotation's own source range**, and each
//! capture as a span. The ruling is explicit that a rewritten line must
//! point at real source; that record is how the `LineContext`/IDE query
//! family answers "what happened to this line, and where is the code that
//! did it" without re-running the match.
//!
//! # What claims, and what does not
//!
//! - A pattern is a *claim* only when spelled `claims = "…"`. The
//! `args = "…"` form declares the `!name`-dispatched handler instead
//! ([`try_dispatch`], issue #2004) — see that function's own doc for what
//! it covers and what it still doesn't.
//! - Only a **top-level `fn`** may claim: the rewrite is an expression
//! call, and a `flow` is not callable as one. A `claims` annotation
//! anywhere else is `E112` (misplaced), enforced by
//! [`super::annotation::handle_line`]'s placement rule. "Top-level"
//! means a direct child of the file, matching exactly what [`collect`]
//! scans — a `fn` declared inside a `module { … }` block is *also*
//! misplaced (issue #1847), even though it is otherwise un-nested in
//! any `flow`/`fn`: `collect` never looks inside a `MODULE_DECL`, so a
//! claim admitted there would validate and then silently never
//! dispatch to anything.
//! - Only a **wholly literal** prose line is a candidate — one with no
//! interpolation, glue, markup, label or embedded divert. A line carrying
//! dynamic parts has no fixed text for a pattern to match, and capture
//! spans over it would not point at anything real. This restriction
//! applies identically to a `CUE`'s name and a `PARENTHETICAL`'s delivery
//! text (issue #1720 widens [`candidate`] to these two shapes, alongside
//! `CONTENT_LINE`/`SCENE_HEADING`).
//!
//! A trailing `#tag` run is the one exception to "wholly literal", and it
//! now applies uniformly across every claimed shape but `CONTENT_LINE`
//! (issue #2077, `docs/decision-log.md` 2026-08-06 "Slug-bearing
//! headings: strip structure, then match", widened by issue #2350's
//! 2026-08-07 "Cue/parenthetical tag extensions: strip-then-match,
//! uniformly"): a `SCENE_HEADING`'s optional `[slug]`/trailing `#tag`s,
//! and a `CUE`/`PARENTHETICAL`'s trailing tag extension (§8d.4, `@VENDOR
//! #(v.o.)`), are all structure, not payload, so they are stripped
//! before matching rather than causing a decline — see [`candidate`]'s
//! own doc and [`try_claim`]'s "Issues #2077/#2350" comment for what
//! happens to the stripped tags. A `CONTENT_LINE` carrying a tag still
//! declines outright — neither issue widened that arm.
//! - A claiming handler's **own body is not claimable** (the staging rule
//! §3.5 states for the conventions module: it cannot use the conventions
//! it defines). Without this, a handler whose body repeats the shape it
//! claims would rewrite into a call on itself. A `!name`-dispatched
//! handler carries no such restriction — the sigil already makes every
//! dispatched line self-announcing, so recursion (a handler's own body
//! containing a `!name` line naming itself) is not the silent risk
//! claiming guards against.
//!
//! # Block capture (issue #1839)
//!
//! `@[element(…, block)]` captures the **following run** into the
//! declaration's trailing `content`-typed parameter — the same
//! `BeginFragment`…`EndFragment` → `Value::FragmentRef` machinery an
//! ordinary call already composes through (`brink-codegen-inkb::content::
//! emit_slot_expr`), widened to hold an arbitrary captured statement run
//! rather than one call's own output (`docs/decision-log.md` 2026-08-01
//! "Content-as-value": the internal `hir::Expr::Fragment` / `lir::ExprKind::
//! Fragment` node this produces). Both [`try_claim`] and [`try_dispatch`]
//! support it identically — see either function's own "Block capture" doc
//! section — via the shared terminator search, [`capture_block`]. The
//! handler **wraps** the captured run (receives it, decides emission) and
//! does not tag it; interior lines are lowered through the ordinary
//! [`super::body::lower_items`] path, so a handler that would claim one of
//! them still claims it, with no special case needed.
//!
//! # Cross-file claiming reach (issue #2289)
//!
//! `docs/decision-log.md`'s 2026-08-05 ruling corrects a defect that
//! survived §9.1 item 4's confinement rule: *"it's never file local. you
//! configure conventions for a project, that's why they're conventions
//! and not 'local patterns'."* §9.1 item 4 restricted **declaring** a
//! claiming handler to the one module `brink.toml`'s `[project]
//! conventions` names (`E169`, `brink_analyzer::conventions_confinement`)
//! — but until this issue landed, nothing let a line in any *other* file
//! actually match against that module's handlers, which made a
//! correctly-declared conventions module claim nothing outside its own
//! file. [`collect`] now accepts an optional, already-ordered `external`
//! handler set — every `@[convention]` declared in the project's
//! configured conventions module, read off that file's own
//! `HirFile::claim_handlers` — and merges it with this file's local
//! declarations into one precedence-ordered dispatch table (see
//! [`Elements`]'s own doc for how `ClaimHandler::decl` tells the two
//! apart). The project-identity work (which file is the conventions
//! module, and reading its declared handlers) happens one layer up,
//! in `brink_db::queries::analysis::external_claim_handlers_query` — this
//! crate has no project database of its own, matching every other
//! project-identity-gated check here (`conventions_module_diagnostics`'s
//! `is_conventions_module` flag is the precedent this follows).
//!
//! Unlike the earlier #1863 design this replaces (deleted by issue #2165
//! alongside the dissolved `fn conventions()` comptime registration it was
//! built for), an injected handler now carries a **real** `order` and
//! `attach` — issue #2164 made `order` a required property of the
//! `@[convention]` declaration itself, so there is no separate
//! comptime-evaluated identity list to join against; `ClaimHandlerDecl` is
//! already the whole payload. Local and injected handlers are therefore
//! merged and sorted by `order` together, not chained as "local always
//! wins" — true project-wide precedence, not merely a last-resort fallback.
//!
//! `fn conventions()` registration itself stays dissolved machinery (issue
//! #2165, `docs/decision-log.md` 2026-08-03 "`fn conventions()` is
//! DISSOLVED — handler precedence is a property of the `@[element]`
//! annotation") — it never existed as anything but a design placeholder
//! and there is nothing left to build here. Dispatching to a `flow` target
//! (rather than a top-level `fn`) is also not here: `!name`'s placement is
//! legal on a `flow` too ([`super::annotation::is_consumed_position`]), but
//! [`collect`] only ever scans top-level `fn` declarations into the
//! dispatch table — the same restriction `claims` already has, for the
//! same reason (the rewrite is an expression call). `!name` dispatch never
//! had a cross-file counterpart at all — cross-file dispatch-name
//! resolution is `docs/prose-dialect-spec.md` §3.5b's own Deferred item,
//! so [`try_dispatch`] stays file-local; only `claims` (project-configured
//! conventions) reaches across files.
//!
//! What this does **not** do: an injected [`ClaimHandler`]'s `annotation`/
//! `name` ranges are copied straight off the declaring file's
//! `ClaimHandlerDecl` — real source positions, but in *another file's*
//! text. A consumer of `HirFile::element_matches` that assumes every range
//! it carries indexes into *this* file's own source (true for every local
//! match, and true before this issue) will misresolve an injected match's
//! `handler`/`annotation` fields. No such consumer exists yet (checked:
//! `brink-ide`'s only reader tests line equality, not these two fields) —
//! flagged here rather than either fabricating a cross-file-safe schema
//! this issue never asked for, or silently shipping the hazard unremarked.
use BTreeMap;
use SyntaxKind as N;
use ;
use Hir;
use ;
use crateFileId;
use crate::;
use SyntaxNode;
use native_provenance;
use crateNodeClass;
/// One declared natural-notation handler: a top-level `fn` whose
/// `@[convention(claims = "…", order = N)]` pattern claims prose lines —
/// OR a handler injected from the project's configured conventions
/// module (issue #2289), for which `decl` is `None` (see that field's own
/// doc).
/// One declared `!name`-dispatched handler: a top-level `fn` whose
/// `@[element(args = "…")]` pattern parses the remainder after a `!name`
/// sigil (issue #2004). Unlike [`ClaimHandler`], there is no `decl`
/// self-suppression field — a dispatched handler's own body is not exempt
/// from matching its own sigil (see the module doc's "What claims, and
/// what does not" section for why) — `!name` dispatch is file-local (same
/// doc, "Deliberately not here").
/// The dispatcher threaded through body lowering: the file's claiming
/// handlers plus the per-line classification records they produce.
///
/// Built once per file by [`collect`] and passed down by reference, rather
/// than re-derived per line: a per-line whole-tree scan would make body
/// lowering quadratic in file size.
pub
/// Collect every claiming handler declared in `root`.
///
/// Silent on everything `container.rs` already validated: each
/// `@[element(…)]`/`@[convention(…)]` line is parsed and checked against
/// its own declaration exactly once there — that validation pass's own
/// diagnostics are discarded here (into a throwaway `scratch` vec) rather
/// than threaded through, since re-reporting would double every
/// `E159`/`E160`/`E167`/`E178`. Duplicate-pattern diagnosis
/// ([`diagnose_duplicate_patterns`]) does *not* happen here either: it
/// needs to see which handlers actually fired during body lowering, which
/// hasn't happened yet at collection time — see that function's doc.
/// Duplicate-*order* diagnosis ([`diagnose_duplicate_order`]) DOES happen
/// here, since it needs no lowering ground truth — `order` is a static
/// property of the declaration alone.
///
/// `handlers` is sorted by `@[convention]`'s `order` (ascending) before
/// this returns — issue #2164's ruling: "the claiming walk takes its
/// precedence from that property instead of from declaration order." A
/// stable sort, so two declarations that (incorrectly) share an `order`
/// keep their declaration-order relative position — moot in practice,
/// since a shared `order` is `E179`, an `Error`-severity diagnostic that
/// fails the compile; the tie-break only matters for what a caller sees
/// while diagnostics are still being collected.
///
/// `external` is the issue #2289 injection point: every `@[convention]`
/// handler declared in the project's configured conventions module,
/// already resolved by the caller (`brink_db::queries::analysis::
/// external_claim_handlers_query`) — `None`/empty for the conventions
/// module's own file (it already has these declarations locally; the
/// caller skips injecting a file into itself) and for every project with
/// no conventions module configured. Each `external` entry is compiled
/// and merged into `handlers` alongside the local declarations, then the
/// **combined** set is sorted by `order` — real project-wide precedence,
/// not "local always wins" (contrast the deleted #1863 design, which had
/// no real `order` to sort an injected handler by). An external entry
/// whose name collides with a handler this file declares *locally* is
/// dropped: a local declaration always wins over an injected one of the
/// same name — in practice this only fires when a caller mistakenly
/// injects a file into its own lowering, which should never happen, but
/// costs nothing to guard against.
pub
/// `E179` (issue #2164, `docs/decision-log.md` 2026-08-03 "`order` is
/// REQUIRED on `@[convention]`…"): flag every group of two or more of this
/// file's locally declared claiming handlers that share the same `order`.
///
/// A static check, unlike [`diagnose_duplicate_patterns`] — it needs no
/// lowering ground truth (`elements.matches`), only the declared `order`
/// values themselves, so `super::lower` calls this right after
/// [`collect`] returns, before `walk_top_level` even runs.
///
/// Reported against **every** conflicting declaration in a shared-`order`
/// group (each one's own `annotation` range), the duplicate-definition
/// posture the ruling calls for — not a single "first one wins" report
/// the way `E048` (duplicate directive on one target) is, since here the
/// declarations are different `fn`s and none is more "the real one" than
/// another. Each diagnostic's message names every *other* declaration in
/// the group and the shared `order` value, the same "name both/all
/// conflicting declarations" posture `E169`'s sibling
/// (`brink_analyzer::conventions_confinement`) already takes. Scoped to
/// `elements.handlers` (this file's own declarations, matching
/// `handler_decls`'s own "declared IN THIS FILE" posture).
///
/// Grouped by `order` rather than walked as all pairs, so three or more
/// handlers sharing one `order` value produce exactly one diagnostic per
/// participating declaration (naming every *other* handler in the group),
/// not one per pair — an all-pairs walk over a group of size `k` would
/// emit `k * (k - 1)` diagnostics, each declaration repeated `k - 1` times.
///
/// `O(n²)` worst case over a file's claiming handlers (the grouping pass
/// itself, plus building each message's "other declarations" list) — see
/// [`diagnose_duplicate_patterns`]'s own doc for why that headroom is
/// never a real concern at this scale.
///
/// Reads [`Elements::local_handlers`], never an injected one (issue
/// #2289) — an order collision between this file's own declaration and a
/// handler injected from elsewhere is not two declarations in *one*
/// module sharing a value, so it is not this check's concern.
pub
/// Cap on the number of witness strings [`generate_witnesses_from_hir`]
/// expands a concatenation into, so an alternation-heavy pattern can't blow
/// up the cartesian product it builds.
const MAX_GENERATED_WITNESSES: usize = 16;
/// Try to prove that every string `later_pattern` can match is also matched
/// by `earlier_pattern` — i.e. `later_pattern`'s language is a subset of
/// `earlier_pattern`'s, so under first-match-wins dispatch the later handler
/// can never win a claim the earlier one doesn't already win first.
///
/// Returns `true` if subsumption is proven, `false` otherwise (which does
/// not prove the later pattern is *not* subsumed, only that this heuristic
/// couldn't prove it). Mere overlap — some string both patterns match, but
/// each also matches strings the other doesn't — is not enough: a later
/// handler can still be genuinely useful (see `docs/diagnostics/E170.md`'s
/// "What this does not catch"). Subsumption is proven by generating a set
/// of candidate strings from `later_pattern`'s structure and checking that
/// every one of them is also accepted by `earlier_pattern`.
/// Generate a set of candidate strings the regex HIR might match.
///
/// This is a best-effort heuristic: an empty result does not mean the regex
/// matches nothing, only that this function couldn't construct an example.
/// Unlike a single-witness generator, this expands **every** branch of an
/// alternation and recurses into capture groups — skipping either would make
/// [`later_pattern_provably_subsumed`] blind to every claim pattern with a
/// named capture (which is all of them, per `E160`/`E167`) or an
/// alternation (a very common way to spell "either of these branches").
/// `Concat` builds its result as the cartesian product of its parts'
/// witnesses, capped at [`MAX_GENERATED_WITNESSES`] so an alternation-heavy
/// pattern can't blow this up.
/// `E168` (issue #1848): flag every claiming handler whose pattern is
/// byte-identical to an earlier-declared one's *and never actually won a
/// claim*.
///
/// `E170` (issue #1859): flag every claiming handler whose pattern can
/// provably overlap with an earlier-declared one's *and never actually won a
/// claim of its own*.
///
/// `elements.handlers` is sorted by `@[convention]`'s `order` (issue
/// #2164 — ascending, [`collect`]'s own doc), which is also
/// [`try_claim`]'s dispatch order — see that function's doc for why
/// "earlier" (lower `order`) is the same as "wins". An identical pattern
/// *provably* matches the identical set of lines — but "the earlier one
/// always wins" is not quite the same claim as "the later one is dead
/// code". `try_claim` excludes a handler from claiming lines inside its
/// **own** declaration (the staging rule), and that exclusion does not
/// extend to a later, byte-identical twin: a twin is exactly the handler
/// that *can* claim a line living inside the earlier one's own body, since
/// the earlier one is barred from claiming there. So a later twin is
/// genuinely live, not dead code, for precisely those lines.
///
/// The same logic applies to E170: a later handler with an overlapping
/// (but non-identical) pattern is live if it actually won at least one claim
/// (necessarily for a line that the earlier pattern couldn't claim, or where
/// it was barred by the staging rule). Only report when the later handler
/// produced zero actual claims.
///
/// Must therefore run **after** the whole file has been lowered
/// ([`super::lower`] calls this once `walk_top_level` has returned), not
/// from [`collect`] before any body is lowered — `elements.matches` is the
/// only ground truth for "did this handler ever actually win a claim",
/// and it does not exist yet at collection time. A later handler that
/// produced at least one entry there is live and is not diagnosed; one
/// that produced none is provably dead or unreachable.
///
/// Each later handler is reported **at most once**, against the first
/// (source-order) earlier handler it overlaps with — a handler that overlaps
/// two or more earlier ones is not re-reported once per overlap.
///
/// `O(n²)` over a file's claiming handlers, which in practice number in
/// the single digits (one project's worth of prose conventions, not a
/// generated table) — a sorted/hashed pass would trade clarity for
/// headroom this call site doesn't need.
///
/// Reads [`Elements::local_handlers`], never an injected one (issue
/// #2289) — this file's own declarations are what "byte-identical to an
/// earlier-declared one" and "dead code" mean here; an injected handler
/// was not declared in this file and is never a candidate for either
/// role, matching [`Elements::handler_decls`]'s own "declared IN THIS
/// FILE" posture.
pub
/// Try to claim one body item, returning the statements that replace it.
///
/// `None` means "nothing claimed this" and the caller lowers the item the
/// way it always did — the fall-through that keeps every unclaimed line,
/// and every file with no claiming handler, byte-identical.
///
/// # Dispatch order
///
/// When more than one handler's pattern matches a line, the first one in
/// `elements.handlers` wins — [`Iterator::find`] below, over a `Vec`
/// [`collect`] sorts by `@[convention]`'s required `order` property
/// (ascending) before returning it. Issue #2164 (`docs/decision-log.md`
/// 2026-08-03) makes this the RULED mechanism, replacing the interim
/// declaration-order rule issue #1848 first documented here: precedence
/// is now total, explicit, and authored on each declaration, never
/// inferred from textual position. Two patterns that can both claim one
/// line still get no diagnostic except the narrow byte-identical case
/// ([`diagnose_duplicate_patterns`], issue #1848) — a genuinely
/// overlapping (non-identical) pair silently prefers the lower-`order`
/// one, exactly the failure mode "pattern power proportional to
/// auditability" (`docs/prose-dialect-spec.md` §3.5b) exists to keep
/// visible, not eliminate outright.
///
/// # Block capture (issue #1839)
///
/// When `handler.block` is set, the trailing declared parameter is not a
/// regex-bound capture at all — `annotation::has_block_content_param`'s own
/// `E166` check already guarantees it is the *last* param, is `content`-
/// typed, and is excluded from `captures`, so only the params *before* it
/// need a named capture here. That trailing param instead binds an
/// `Expr::Fragment` built from the **following run** ([`capture_block`]):
/// `following` is the caller's remaining, not-yet-lowered sibling items,
/// and the terminator search consumes a prefix of it (a blank line, or any
/// non-`CONTENT_LINE` item, ends the run — the ruled terminator). The
/// number of items consumed is returned alongside the statements so the
/// caller (`body::lower_items`) can skip them rather than lowering them
/// a second time.
pub
/// [`try_claim`]'s attach-mode (issue #2108) rewrite: `call` becomes a
/// `Stmt::AttachElement` rather than ordinary `Stmt::Content`, followed by
/// the captured following run's own already-lowered statements and,
/// usually, a closing `EndElementRun`.
///
/// Ruling item 6: "AN EVENT EXISTS IFF A LINE EXISTS" — an attaching
/// convention emits no `Stmt::Content`/`Stmt::EndOfLine` at all.
///
/// **The one exception** (found by tracing the actual bytecode for `cue`
/// immediately followed by `parenthetical` — #2108's own fixture):
/// [`capture_block`]'s terminator search stops at ANY element-level line,
/// including another `CUE`/`PARENTHETICAL` — so `cue`'s own captured run is
/// *empty* when a `parenthetical` immediately follows it, exactly the
/// shape ruling item 3 ("cue and parenthetical both attach to the SAME
/// run") requires to chain. Closing right there (as an earlier version of
/// this code unconditionally did) would clear `cue`'s data before
/// `parenthetical`'s own `AttachElement` — or the dialogue after it — ever
/// reads it. So: an empty capture caused SPECIFICALLY by an
/// immediately-following `CUE`/`PARENTHETICAL` node leaves the run open
/// (no `EndElementRun` here — the following claim's own rewrite closes it
/// once IT finishes); any other empty-capture reason (a blank line, a
/// heading, a dispatch, end of statements) closes immediately, so an
/// attach with genuinely nothing after it never leaks into unrelated later
/// content.
/// [`try_claim`]'s issue #2077/#2350 seam: recover the pieces `candidate`
/// stripped from `node`'s literal text before matching
/// (`docs/decision-log.md` 2026-08-06 "Slug-bearing headings: strip
/// structure, then match", generalized by 2026-08-07 "Cue/parenthetical tag
/// extensions: strip-then-match, uniformly"). `(None, Vec::new())` for
/// every other `node` kind — `CONTENT_LINE` still declines outright on a
/// tag, since #1720/#2350 never widened `candidate`'s `CONTENT_LINE` arm
/// the way they did `SCENE_HEADING`/`CUE`/`PARENTHETICAL`.
///
/// - The slug: the *address capture* role `docs/prose-dialect-spec.md`
/// §8b.5 reserves, returned as a reserved `ElementCapture` for the caller
/// to store ALONGSIDE `ElementMatch::captures`, not merged into it —
/// `captures`' own doc says "bound into the call, in parameter order",
/// and the slug is never bound into the rewritten call. Named `slug`,
/// not the spec's more generic "address": only a scene heading has one
/// today (`SCENE_SLUG`, §3.3), so the concrete CST/spec term is more
/// honest than a generalization nothing else uses yet — a future element
/// gaining its own address capture can rename/generalize then. Wiring
/// the slug into structure/`DefinitionId` (what would make it
/// load-bearing rather than descriptive) is heading→stitch promotion,
/// issue #2078 — deliberately untouched here; a caller reads a real
/// source span and nothing more. `CUE`/`PARENTHETICAL` have no address
/// capture of their own, so this is always `None` for them.
/// - The tags: the EXISTING tag channel (`Content.tags`, via the same
/// `lower_tag` every other tagged line already goes through) — not a
/// second delivery mechanism invented for headings, and not a new one
/// invented for cues/parentheticals either. This is a deliberate INTERIM
/// carrier pending issue #474 (the per-flow tag API), not a ruled
/// semantic — see `try_claim`'s own call site for why. That interim
/// posture is what #2350's ruling explicitly carries over unchanged
/// ("the heading-tags delivery caveat from #2344 … applies identically
/// here"): `docs/prose-dialect-spec.md` §8b.4 names a *heading's*
/// trailing `#tag`s container-level per-flow tags, a concept a cue or
/// parenthetical tag extension (§8d.4) never claimed to be — both still
/// ride the same ordinary per-line `Content.tags` field regardless.
/// The trailing `#tag` nodes [`element_extras`] recovers for `node`'s own
/// kind — empty for anything but `SceneHeading`/`Cue`/`Parenthetical`
/// (`CONTENT_LINE` never reaches here; see [`element_extras`]'s own doc for
/// why). Factored out of `element_extras` itself (issue #2351's review
/// finding) so it and [`has_trailing_tags`] — a pure predicate a caller
/// outside this module needs — select the exact same set of tag nodes and
/// can never drift apart the way `candidate`'s selection and a hand-copied
/// duplicate would.
/// Whether `node` carries at least one trailing tag in the position
/// [`element_extras`] would recover tags from — issue #2351's review
/// finding: `hir::classify::classify_node_compiled` needs this exact
/// answer to mirror [`try_claim`]'s own attach-mode decline (`if is_attach
/// && !extra_tags.is_empty() { return None; }`, above) for a caller that
/// never runs `try_claim` itself and must not trigger `element_extras`'s
/// diagnostic side effects (`lower_tag`'s `E172`) just to ask the
/// question. Built on the exact same [`raw_element_tags`] selection
/// `element_extras` itself uses, so the two can never disagree on which
/// nodes have tags at all.
pub
/// The block-capture terminator search (issue #1839, ruled 2026-07-31):
/// consume a prefix of `following` — the caller's remaining, not-yet-
/// lowered sibling items — stopping at **a blank line, or any element-level
/// line**. "Element-level" is read structurally against this dialect's own
/// candidate set: a *plain* `CONTENT_LINE` — [`is_plain_content_line`] —
/// continues the run (and is lowered through the ordinary
/// [`super::body::lower_items`] path, so a handler that claims *it* still
/// claims it — "interior lines keep their own handlers" falls out of
/// reusing the normal dispatch loop rather than needing a special case);
/// anything else ends the run: a new `SCENE_HEADING`/`SCENE_STITCH`,
/// `CUE`/`COMPACT_CUE`/`PARENTHETICAL`, another `BANG_DISPATCH`, a
/// standalone choice point or divert, a nested declaration, running out of
/// items — **or a `CONTENT_LINE` that is not plain**, i.e. one carrying a
/// `LABEL` (it would otherwise absorb the rest of the captured run into a
/// `Stmt::LabeledBlock` — reviewer finding, #1839's PR review) or an
/// element-level construct fused onto the same line (`DIVERT_STMT`/
/// `TUNNEL_CALL`/`CHOICE_POINT` — a trailing `-> target`/`->->`/`{?}` on a
/// prose line is still "an element-level line" in the ruled sense, even
/// though the parser fuses it onto the preceding `CONTENT_LINE` rather than
/// giving it its own sibling node; same reviewer finding). Absorbing either
/// shape into the fragment either mis-lowers as `Stmt::LabeledBlock`/
/// `Stmt::ChoiceSet` (rejected at LIR by `reject_unsupported_inline_construct`,
/// E059, with a message that talks about inline-content position rather than
/// block-capture) or — for a bare divert/tunnel, which *does* lower cleanly
/// at LIR — silently corrupts the runtime's fragment-depth tracking, since
/// the divert transfers control before the fragment's own `EndFragment` can
/// run. Both are avoided by simply never absorbing such a line into the
/// capture: it becomes the terminator instead, and lowers normally as the
/// next ordinary body item. Returns the lowered statements, how many items
/// were consumed (so the caller can skip re-lowering them), and the
/// captured span's own source range (`None` when nothing was captured — an
/// immediate terminator, e.g. a claimed header line with a blank line right
/// after it).
/// [`capture_block`]'s twin for a compact cue's fused dialogue (issue
/// #2079, RULED 2026-08-06 "Compact cue desugars to cue + content line").
///
/// `dialogue` is unconditionally the captured run's first line — it is
/// **not** run through [`is_plain_content_line`]/[`blank_line_precedes`]
/// the way a real sibling is: those two checks exist to decide whether a
/// *sibling* item is eligible to extend an already-open run, and `dialogue`
/// isn't a sibling being offered for absorption, it is structurally *part
/// of* the compact cue itself. That said, the caller ([`try_claim`]) has
/// already required `dialogue` itself to satisfy [`is_plain_content_line`]
/// before ever reaching here — a fused `LABEL` or trailing divert/choice on
/// `dialogue` declines the WHOLE claim instead (review finding, #2079's PR:
/// unconditionally absorbing either shape here let a divert transfer
/// control before this run's own closing statement ran, corrupting the
/// runtime's fragment/attach-run bookkeeping). So by the time this function
/// runs, `dialogue` is known plain — this function itself does not
/// re-check it, it only extends the run with whatever *plain* siblings
/// follow. `following`'s normal terminator search still applies to
/// whatever comes after `dialogue` — unchanged from before this finding.
///
/// Returns the same three-part shape as [`capture_block`], except the
/// range is never `None`: `dialogue` alone guarantees at least one
/// captured item.
/// `true` when `node` is a `CONTENT_LINE` that [`capture_block`]'s
/// terminator search may fold into the captured run.
///
/// A `CONTENT_LINE` is not automatically "plain" just because its `SyntaxKind`
/// matches: the native parser fuses a `LABEL`, or a trailing `DIVERT_STMT`/
/// `TUNNEL_CALL`/`CHOICE_POINT`, onto the *same* `CONTENT_LINE` node as the
/// preceding prose rather than giving it its own sibling item (see
/// `brink-syntax-native`'s `labeled_content_line_produces_a_label_node` and
/// `divert_inside_multiline_choice_body_after_prose_is_a_divert_node` tests).
/// Each of those is "an element-level line" in the ruled terminator's sense
/// even though it shares a `CONTENT_LINE` wrapper with ordinary text —
/// folding it into the capture is what let a labeled/divert/choice-bearing
/// line be silently absorbed and mis-lowered (reviewer finding, #1839's PR
/// review; see [`capture_block`]'s own doc for the two concrete failure
/// modes). Checked structurally over `node`'s direct children — the same
/// depth [`super::body::lower_content_run`] scans when it lowers a content
/// line's own body — rather than a deep descendant search, since a divert
/// nested inside e.g. a bracketed span is not "this line ends in a divert"
/// in the same sense.
/// `true` when at least one blank source line separates `node` from
/// whatever real body item precedes it in the tree — a lone `NEWLINE`
/// token ends the previous item's own line; a *second* bare `NEWLINE` with
/// nothing but trivia between the two is the blank line itself (native's
/// content-ground layer never wraps a blank line in its own node — see
/// `brink-syntax-native`'s `blank_line_produces_no_content_line` test).
/// Walks backwards over raw sibling tokens the same way
/// `annotation::annotations_before`/`attached_declaration` already do,
/// rather than re-deriving trivia classification here.
/// Try to dispatch one body item via the `!name` sigil (issue #2004),
/// returning the statements that replace it.
///
/// `None` means "not dispatched" — either `node` isn't a `BANG_DISPATCH` at
/// all (the harmless, overwhelmingly common case, mirroring how [`try_claim`]
/// is harmless for any node [`candidate`] doesn't recognize), no handler is
/// declared under its dispatch name, its remainder isn't a wholly-literal
/// candidate ([`candidate`], the same requirement [`try_claim`] enforces on
/// a claimed line), or the handler's `args` pattern doesn't match the
/// (trimmed) remainder. Every one of those is a real `!name` line the
/// author wrote that this compiler cannot yet honor — the caller
/// (`body::lower_one_item`) falls through to its own default arm, which
/// diagnoses an unrecognized `BANG_DISPATCH` node loudly (`E129`, "parses
/// cleanly but has no HIR lowering yet") rather than silently dropping it.
///
/// The ruled spec text asks for more than that: "an unmatched remainder is
/// a targeted diagnostic naming both the line and the handler's pattern"
/// (§3.5b). `E129`'s generic message doesn't name either — a sharper
/// diagnostic would need a new code, which this issue's own hint says to
/// treat as a stop-and-report rather than an allocate-it-yourself (rule
/// 12q, no code is pre-assigned here). `E129` is the honest, already-
/// established "not fully implemented" fallback in the meantime, loud
/// rather than silent, not a substitute for the ruled diagnostic.
///
/// No dispatch-*order* question analogous to [`try_claim`]'s own doc
/// section: `elements.dispatch` is keyed by name, so at most one handler
/// can ever match a given `!name` line's own name. Two *declarations*
/// colliding on the same dispatch name is a distinct question — see
/// `Elements::dispatch`'s own doc for the interim first-declared-wins rule
/// there.
///
/// Block capture (issue #1839) works identically to [`try_claim`]'s own
/// "Block capture" doc section: a `block`-declared handler's trailing param
/// binds an `Expr::Fragment` built from `following` via [`capture_block`]
/// instead of a named capture, and the number of items consumed is
/// returned alongside the statements.
pub
/// Classify a body item as a claim candidate, yielding the node whose text
/// a pattern is matched against.
///
/// A `CONTENT_LINE` qualifies only when it is *wholly* literal — exactly
/// one `TEXT` child and nothing else (no `LABEL`, `INTERPOLATION`, `SPAN`,
/// `TAG`, `GLUE_NODE`, `ESCAPE`, embedded divert or choice point).
///
/// A `SCENE_HEADING`'s title run qualifies by selecting its `SCENE_TITLE`
/// child, **not** by requiring it be the heading's only child (issue
/// #2077, `docs/decision-log.md` 2026-08-06 "Slug-bearing headings: strip
/// structure, then match"): the heading's optional `[slug]` and trailing
/// `#tag`s are structure the pattern is never shown, so they are simply
/// not selected — rather than causing the whole heading to decline, the
/// way an equivalent shape does for the other three node kinds below.
/// `try_claim` recovers both stripped pieces separately: the slug as a
/// reserved capture (the *address capture* role
/// `docs/prose-dialect-spec.md` §8b.5 reserves), the tags through the
/// same `Content.tags` channel any other tagged line already uses. This
/// makes `SCENE_HEADING` the one arm below whose "wholly literal" bar is
/// about the *title* alone, not the whole node.
///
/// **Issue #1720** (the built-in screenplay preset) widens this to the
/// two remaining literal-line grammar shapes `docs/prose-dialect-spec.md`
/// §3.5b now names as claim candidates alongside a prose line and scene
/// heading — the spec's clause was amended in the same PR (rule 20d: a
/// ruling lands in the spec, not only in a code comment) — the ruling's own
/// natural-notation examples are cue/heading text, and the wave retro
/// posted on #1720 itself names the gap this closes: without it, real
/// `@NAME` cue and `(parenthetical)` lines are structurally invisible to
/// `claims`/`args` dispatch and always fall to `body::lower_one_item`'s
/// loud `E129`, no matter what a project or preset declares):
///
/// - A `CUE`'s `CUE_NAME` run qualifies the same way `SCENE_TITLE` does —
/// selecting the `CUE_NAME` child without requiring it be the only one.
/// **Issue #2350** (`docs/decision-log.md` 2026-08-07 "Cue/parenthetical
/// tag extensions: strip-then-match, uniformly") extends the #2077
/// heading rule here: a `CUE`'s trailing tag extension (§8d.4, `@VENDOR
/// #(v.o.)`) is structure the pattern is never shown, exactly like a
/// heading's `[slug]`/`#tag`s, so any run of trailing `TAG` children
/// after `CUE_NAME` no longer causes a decline. `try_claim` recovers
/// those tags the same way it recovers a heading's — see
/// [`element_extras`]'s own doc.
/// - A `PARENTHETICAL`'s `TEXT` run (the text strictly between the
/// parens — `(`/`)` are tokens, not part of the child) qualifies the
/// same way, with the identical #2350 widening: trailing `TAG` children
/// after `TEXT` no longer cause a decline.
///
/// **Issue #2079** (RULED 2026-08-06, "Compact cue desugars to cue +
/// content line") adds a third arm: `COMPACT_CUE` (`@NAME: text`)
/// qualifies against its `CUE_NAME` segment alone, exactly like a bare
/// `CUE`'s own arm — but unlike the two arms above, `COMPACT_CUE` is not a
/// lone-child node (it always carries a second child, the fused dialogue
/// `CONTENT_LINE`), so its arm below deliberately does not require
/// `children.next().is_none()`. The fused dialogue itself is never shown
/// to the pattern here — `try_claim` desugars it separately (its own
/// "Compact cue" note) and, unlike the two arms above, does not feed the
/// *same* mechanism unchanged: `try_claim` requires the fused dialogue to
/// independently satisfy `is_plain_content_line` before folding it into
/// the claim's captured run, declining the whole line otherwise (review
/// finding, #2079's PR) — a check the `CUE`/`PARENTHETICAL` arms have no
/// analog of, since neither carries any fused content of its own.
///
/// The `CUE`/`PARENTHETICAL` arms feed the exact same `try_claim`/
/// `try_dispatch` mechanism unchanged; the block-capture terminator
/// (`capture_block`) already treats an upcoming `CUE`/`COMPACT_CUE`/
/// `PARENTHETICAL` as "ends the run" regardless of whether any of them is
/// itself claimable, so nothing there changes.
///
/// `pub(crate)` (issue #2351): this is the ONE place the sub-node selection
/// rules above are written down. `crate::hir::classify`'s node-aware
/// entry points (`classify_node_compiled`, `nearest_element_candidate`)
/// call this exact function — via `super::candidate` in
/// `hir::lower_native::mod`'s crate-visible re-export — rather than
/// re-deriving the selection against the raw line text, which is
/// precisely the divergence #2351 exists to close: a copy would
/// re-diverge from this one the next time a `candidate` arm changes.
pub