tsv_svelte 0.8.0

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

use crate::ast::*;
use crate::lexer::TokenKind;
use crate::parser::element::{ElementParent, ParsedElement};
use crate::whitespace::is_svelte_ws;
use bumpalo::Bump;
use tsv_lang::source_scan::{TriviaProfile, skip_trivia_run};
use tsv_lang::{Error, Span};
use tsv_ts::__private::TopLevelAs;
use tsv_ts::ast::{Expression, ExpressionKind};

use super::expression_tag::{scan_head_to_matching_brace, scan_to_matching_paren};
use super::parser_impl::{EmbeddedParseMark, SvelteParser};
use super::{match_bracket, subslice_offset};

/// Strip a **mid-head keyword separator** — optional leading whitespace, the keyword,
/// then a *required* whitespace run — returning the value that follows.
///
/// The separator every block head puts *between* its expression and a binding:
/// `{#each … as x}`, `{#await … then v}`, `{#await … catch e}`. Mirrors canonical's
/// `allow_whitespace()` / `eat(kw)` / `require_whitespace()`, so `(items)as x` is a
/// separator (no leading whitespace needed) while `as/* c */x` and a head-final `as` are
/// not. A separator with nothing after it (`as `) still matches — canonical's
/// `require_whitespace` is satisfied there and it is `read_pattern` that reports the
/// missing binding, so the empty value is the caller's error rather than a non-match.
///
/// Both whitespace runs are of **any width**, not the single spaces the canonical form
/// happens to print: an authored break or tab is legal in either, and so is the wrapped
/// head tsv's own formatter emits (`items as A[]⏎as item}`) — which a single-space match
/// rejected, leaving tsv unable to re-parse its own output. The class is [`is_svelte_ws`],
/// the `\s` canonical itself tests, not Rust's `trim_start`, whose Unicode `White_Space`
/// set disagrees at `U+0085` and `U+FEFF`.
///
/// [`SvelteParser::strip_keyword_value`] is the *leading*-keyword counterpart — same rule
/// one position earlier, where a missing keyword is an error rather than a `None`.
fn strip_head_keyword<'s>(rest: &'s str, keyword: &str) -> Option<&'s str> {
    let after_kw = rest
        .trim_start_matches(is_svelte_ws)
        .strip_prefix(keyword)?;
    let value = after_kw.trim_start_matches(is_svelte_ws);
    (value.len() < after_kw.len()).then_some(value)
}

/// The words of a `{:...}` continuation run, split on [`is_svelte_ws`] — Svelte's class,
/// not Rust's.
///
/// ⚠️ NOT `str::split_whitespace`, which splits on `char::is_whitespace` (Unicode
/// White_Space). That set lacks **U+FEFF**, so it welds `else<ZWNBSP>if` into a single word
/// and loses the `{:else if}` match that [`SvelteParser::continuation_keyword_at`]'s own cut
/// just took care to preserve — the two would then disagree about where a word ends, which is
/// the bug the shared class exists to rule out. It also *adds* U+0085 NEL, which Svelte reads
/// as junk rather than as a separator.
///
/// Empty pieces are dropped so a run of separators (`{:else  if}`) yields two words, matching
/// `split_whitespace`'s one useful property.
fn continuation_words(keyword: &str) -> impl Iterator<Item = &str> {
    keyword.split(is_svelte_ws).filter(|w| !w.is_empty())
}

/// [`strip_head_keyword`], plus the **head-final** form the keyword-with-no-value case
/// needs: `{#await p then}` names its clause and stops, so nothing follows the keyword for
/// the required whitespace run to be found in.
///
/// The `{#await}` spelling of the same question `{#each}` asks with `strip_head_keyword`
/// alone, and the difference is the whole reason both exist: `{#each xs as}` must be
/// REJECTED (canonical's `require_whitespace` after `eat('as')` fails, and it is the `as`
/// that would otherwise bind an absent pattern), while `{#await p then}` is valid — its
/// clause simply has no binding. The caller's `content` stops before the head's `}`
/// (`scan_block_tag_content`), so "ends the head" is just "nothing but whitespace left".
///
/// Returns the same empty value the with-whitespace form does (`{#await p then }`), so the
/// caller reads one answer rather than distinguishing two spellings of "no binding".
fn strip_head_keyword_or_final<'s>(rest: &'s str, keyword: &str) -> Option<&'s str> {
    strip_head_keyword(rest, keyword).or_else(|| {
        let after_kw = rest
            .trim_start_matches(is_svelte_ws)
            .strip_prefix(keyword)?;
        after_kw
            .trim_start_matches(is_svelte_ws)
            .is_empty()
            .then_some("")
    })
}

/// The two `{#await}` clauses — the phases `{:then}` / `{:catch}` name, and that a
/// shorthand head (`{#await p then v}`) fills in advance. Each fills at most one
/// [`AwaitSlot`], which is what [`SvelteParser::parse_await_block`]'s continuation loop
/// guards.
#[derive(Clone, Copy)]
enum AwaitClause {
    Then,
    Catch,
}

impl AwaitClause {
    /// The keyword as it is spelled in both the head (`{#await p then v}`) and the
    /// continuation (`{:then v}`) — one spelling drives the scan, the parse and the
    /// duplicate error.
    fn keyword(self) -> &'static str {
        match self {
            Self::Then => "then",
            Self::Catch => "catch",
        }
    }
}

/// What ends any `{#await}` body — the pending phase's and each clause's alike. An
/// unrecognized continuation ends a body regardless (`parse_block_children` breaks on
/// one), so the list is not per-clause; the continuation loop is what decides whether
/// the one that ended it is legal there.
const AWAIT_BODY_STOPS: &[&str] = &["then", "catch", "await"];

/// What one `{#await}` clause holds: its fragment and its binding pattern, kept together
/// so filling a clause and asking whether it is filled cannot name different slots.
type AwaitSlot<'arena> = (Option<Fragment<'arena>>, Option<&'arena Expression<'arena>>);

/// The TypeScript assertion keywords, each paired with whether it can BE a `{#each}`
/// binding separator. Both continue an assertion chain; only `as` is spelled the way
/// Svelte spells its separator. Neither prefix can shadow the other (`satisfies` does not
/// start with `as`), so the order here is immaterial.
const ASSERTION_KEYWORDS: [(&str, bool); 2] = [("as", true), ("satisfies", false)];

/// Step over a run of whitespace and comments at the start of `s`.
///
/// The gap between a type assertion and the `{#each}` binding separator can hold both
/// (`items as A[] /* c */ as item`, which canonical Svelte accepts), and a type's own
/// `span.end` deliberately stops *before* trailing trivia — so the separator scan has to
/// cross it explicitly. Comments only, never strings: nothing but whitespace and comments
/// can sit between a complete type and the token after it.
fn skip_ws_and_comments(s: &str) -> &str {
    &s[skip_trivia_run(s, 0, TriviaProfile::COMMENTS, is_svelte_ws)..]
}

/// What a `{#each}` head's assertion run says about its binding — the three answers
/// canonical's unwind can give, which strips the head expression's **outermost** node and
/// only when that node is a `TSAsExpression`.
///
/// Every offset is ABSOLUTE, so the caller indexes `content` by one rule (subtract its
/// offset) instead of summing the head's parts a second time.
#[derive(Debug, PartialEq, Eq)]
enum EachHeadSplit {
    /// The head's first `as` — the one the caller already stripped — is the binding
    /// separator: `{#each xs as item}`.
    FirstAs,
    /// A LATER `as` is: `{#each xs as A[] as item}`. `separator` is where that keyword
    /// begins and `binding` where the binding after it does, with nothing but the keyword
    /// and its whitespace between them.
    LaterAs { separator: usize, binding: usize },
    /// The run holds no separator at all — it ends on `satisfies`, so the whole run is
    /// the iterable and the head has NO binding, the same shape a head with no `as` at
    /// all produces: `{#each xs as A satisfies B}`, which canonical reads as a
    /// binding-less each block. `run_end` is where the run's last type ends.
    NoBinding { run_end: usize },
}

/// Split a `{#each}` head's assertion run, given `s` — the head text that follows its
/// FIRST `as`, at absolute offset `s_offset`.
///
/// `{#each xs as A[] as item}` reads as one assertion chain, and only the **type grammar**
/// can say where TypeScript's assertions stop and Svelte's binding begins — so this walks
/// the chain by parsing a type after each assertion keyword. It stops at the first item
/// that is not a type, which is precisely the binding: a destructuring default
/// (`{#each xs as A[] as { a = 1 }}`) is a pattern and no type, so the `as` before it is
/// Svelte's.
///
/// ⚠️ The separator is the run's **LAST** keyword, and only when that keyword is `as` —
/// *not* the last `as` anywhere in the run. Canonical unwinds the head by stripping the
/// expression's outermost node and only when it is a `TSAsExpression`, so a `satisfies`
/// **cancels** every `as` before it: `{#each xs as A[] as item satisfies B}` has no
/// binding at all — `item` is a type — where "keep the last `as`" hands `item` to the
/// binding parser and rejects a head canonical accepts.
///
/// ⚠️ **Both** assertion keywords continue the chain; only `as` can BE the separator. The
/// chain is `as`/`satisfies` interleaved (`xs as A satisfies B as item`), and a walk that
/// recognized `as` alone stopped dead at the first `satisfies`, handing its whole tail to
/// the binding parser. That is an over-rejection the byte scan this replaced did *not*
/// have — a scan looking for the last ` as ` steps over an intervening `satisfies` without
/// having to know it exists — so it is the one axis where modelling the grammar costs
/// something, and the cost is paid by naming both keywords rather than by scanning.
///
/// ⚠️ Asking the type grammar is the point, and a bracket-depth byte scan cannot replace
/// it. `<`/`>` are not a bracket pair, so an arrow's `>` closes a depth nothing opened:
/// a signed depth counter goes **negative** at `A<() => string>`, and every later candidate
/// dies against a `depth == 0` test that can no longer be true — rejecting `{#each fns as
/// A<() => string> as item}`. A mapped type is the same question one step subtler: its
/// `[K in T as U]` spells an `as` that is no separator, and it survives a depth scan only
/// because brackets happen to nest it — the type grammar knows it outright.
///
/// The probe is read-only: it collects no comments and keeps no node (see
/// `tsv_ts::__private::parse_type_extent`) — the caller re-reads both regions with the real
/// iterable and binding parses, so a probe that registered anything would double it.
/// Its type parses start at `host_nesting`, as the real ones do.
fn each_binding_separator(
    s: &str,
    s_offset: usize,
    host_nesting: u32,
    arena: &Bump,
) -> EachHeadSplit {
    // Every position the walk names is a subslice of `s`, so one rule converts them all
    // and no offset is ever summed from parts. Via [`subslice_offset`] rather than a
    // length subtraction, which is the same value only while the slice stays a SUFFIX —
    // a precondition each site would have to re-establish, and that a `trim_matches`
    // added later silently breaks.
    let offset_of = |part: &str| s_offset + subslice_offset(s, part);

    // The run's last keyword, as a separator: `Some` while that keyword is an `as`, reset
    // to `None` by a `satisfies` after it.
    let mut separator = None;
    // Where the run ends, set ONLY when the walk stops on a complete type — i.e. the head
    // ran out of items rather than reaching one that is a pattern. Only then can the
    // answer be `NoBinding`; an item that is no type IS the binding.
    let mut run_end = None;
    // Whether the walk consumed a keyword of its own, which is what tells a run that
    // ENDED on `satisfies` from a head whose first `as` was already the separator:
    // `{#each xs as item}` also walks one type and finds no keyword after it, and its
    // `item` is the binding, not a run end.
    let mut linked = false;
    let mut item = s;
    loop {
        // No type here ⇒ this item is the binding, and the keyword before it is the
        // separator — the one recorded below, or the head's first `as` when none is.
        let item_at = offset_of(item);
        let Ok(type_end) = tsv_ts::__private::parse_type_extent(item, item_at, host_nesting, arena)
        else {
            break;
        };
        let after_type = skip_ws_and_comments(&item[type_end - item_at..]);
        // An assertion keyword after a complete type makes that type an assertion and the
        // chain continue; nothing else can, so anything else ends the run on this type.
        let Some((is_separator, rest)) =
            ASSERTION_KEYWORDS.iter().find_map(|&(kw, is_separator)| {
                strip_head_keyword(after_type, kw).map(|rest| (is_separator, rest))
            })
        else {
            run_end = Some(type_end);
            break;
        };
        // The LAST keyword decides, so `satisfies` clears the candidate rather than being
        // skipped over — see the outermost-node rule above.
        separator = is_separator.then(|| (offset_of(after_type), offset_of(rest)));
        linked = true;
        // `strip_head_keyword` consumed the keyword plus a required whitespace run, so
        // `rest` is strictly shorter than `item` and the walk always terminates.
        item = rest;
    }

    match (separator, run_end) {
        (Some((separator, binding)), _) => EachHeadSplit::LaterAs { separator, binding },
        (None, Some(run_end)) if linked => EachHeadSplit::NoBinding { run_end },
        _ => EachHeadSplit::FirstAs,
    }
}

/// The clause an `{#await}` head's shorthand fills — `{#await promise then value}` /
/// `{#await promise catch error}` — and its binding text, read from `after_expr`, the head
/// past the promise expression; `None` for the block form, whose tag must end there.
fn await_head_clause(after_expr: &str) -> Option<(AwaitClause, &str)> {
    if let Some(value_str) = strip_head_keyword_or_final(after_expr, "then") {
        return Some((AwaitClause::Then, value_str));
    }
    strip_head_keyword_or_final(after_expr, "catch")
        .map(|error_str| (AwaitClause::Catch, error_str))
}

/// The `function f…` declaration a `{#snippet}` head's wrapper parses to. `None` only for a
/// wrapper that produced no such statement, which the caller reports as an error.
fn snippet_signature<'arena>(
    program: &tsv_ts::ast::Program<'arena>,
) -> Option<&'arena tsv_ts::ast::FunctionDeclaration<'arena>> {
    match program.body.first().map(|stmt| &stmt.kind) {
        Some(tsv_ts::ast::StatementKind::FunctionDeclaration(func)) => Some(*func),
        _ => None,
    }
}

/// Return type for parse_each_binding: (context, index, key, consumed_end).
/// `consumed_end` is the absolute source offset just past the last token the binding
/// consumed — the caller rejects any non-whitespace between it and the closing `}`.
type EachBindingResult<'arena> = (
    &'arena Expression<'arena>,
    Option<&'arena str>,
    Option<EachKey<'arena>>,
    usize,
);

/// Return type for parse_index_and_key_after_context: (index, key, consumed_end).
type IndexAndKeyResult<'arena> = (Option<&'arena str>, Option<EachKey<'arena>>, usize);

/// An `{#each}` head's ", index" / "(key)" tail as `SvelteParser::split_index_and_key`
/// reads it — the key bounded by its parens but not yet parsed.
struct EachIndexAndKey<'s> {
    index: Option<&'s str>,
    key: Option<EachKeyRegion<'s>>,
    /// Absolute offset just past the last token the tail consumed.
    consumed_end: usize,
}

/// A `(key)` region: the key expression's text (leading whitespace trimmed), its absolute
/// offset, and the span of the parens around it.
struct EachKeyRegion<'s> {
    expr_str: &'s str,
    expr_offset: usize,
    span: Span,
}

impl<'a, 'arena> SvelteParser<'a, 'arena> {
    /// Parse a control flow block starting with {#
    ///
    /// Dispatches to specific block parsers based on the keyword.
    pub(crate) fn parse_block(&mut self) -> Result<FragmentNode<'arena>, Error> {
        // two wire levels: the block and the `Fragment` its children sit in (the depth
        // limit's count)
        self.nested(2, Self::parse_block_body)
    }

    /// [`Self::parse_block`] inside its depth levels.
    fn parse_block_body(&mut self) -> Result<FragmentNode<'arena>, Error> {
        let start = self.current_start();

        // We're at {#, consume it
        if !self.check(TokenKind::BlockOpen) {
            return Err(self.error_expected_found("'{#'"));
        }

        // After {# we expect a block keyword: if, each, await, key, snippet
        let keyword = self.keyword_at(self.current_end());

        match keyword {
            "if" => self.parse_if_block(start),
            "each" => self.parse_each_block(start),
            "await" => self.parse_await_block(start),
            "key" => self.parse_key_block(start),
            "snippet" => self.parse_snippet_block(start),
            _ => Err(self.error_unknown_at("block type", &format!("{{#{keyword}}}"), start)),
        }
    }

    /// Parse an if block: {#if test}...{:else if test}...{:else}...{/if}
    fn parse_if_block(&mut self, start: usize) -> Result<FragmentNode<'arena>, Error> {
        self.parse_if_block_inner(start, false)
    }

    /// Inner parser for if blocks (handles both {#if} and {:else if})
    fn parse_if_block_inner(
        &mut self,
        start: usize,
        is_elseif: bool,
    ) -> Result<FragmentNode<'arena>, Error> {
        // Get the content start position (after {# or {:)
        let tag_content_start = self.current_end();

        // Scan to find closing } and extract content
        let (expr_content, content_start) = self.scan_block_tag_content(tag_content_start)?;

        // Extract the expression (skip "if " or "else if " prefix, handling
        // variable whitespace). Svelte requires whitespace after the `if`
        // keyword, so `{#if(x)}` / `{:else if(x)}` are rejected.
        let expr_str = if is_elseif {
            // {:else if expr} - skip "else", whitespace, "if", whitespace
            let after_else = self
                .strip_dispatched_keyword(expr_content, "else", tag_content_start)?
                .trim_start_matches(is_svelte_ws);
            self.strip_block_keyword(after_else, "if", tag_content_start)?
                .trim_start_matches(is_svelte_ws)
        } else {
            // {#if expr} - skip "if", whitespace
            self.strip_block_keyword(expr_content, "if", tag_content_start)?
                .trim_start_matches(is_svelte_ws)
        };

        // Parse the test expression (with comments)
        let expr_offset = tag_content_start + subslice_offset(expr_content, expr_str);

        let test = self.parse_ts_expression(expr_str, expr_offset, "'}'")?;

        // Opening tag span is from start to content_start (includes the closing })
        let opening_tag_span = Span {
            start: start as u32,
            end: content_start as u32,
        };

        // Parse consequent (content until {:else}, {:else if}, or {/if})
        let consequent = self.parse_block_children(&["else", "if"], content_start)?;

        // Check for alternate branch
        let alternate = if self.check(TokenKind::BlockContinue) {
            // Peek at what follows {:. Match the first two whitespace-delimited
            // words allocation-free (the old `.take(2).join(" ")` normalized
            // "else  if" -> "else if" only to compare against these two forms).
            let keyword = self.continuation_keyword_at(self.current_end());
            let mut words = continuation_words(keyword);
            let first = words.next();
            let second = words.next();
            let is_else_if = first == Some("else") && second == Some("if");
            let is_else = first == Some("else") && second.is_none();

            if is_else_if {
                // {:else if} - parse as nested if block
                let elseif_start = self.current_start();
                // two wire levels: the `alternate` fragment and the nested `IfBlock` in it
                let elseif_block =
                    self.nested(2, |p| p.parse_if_block_inner(elseif_start, true))?;
                let mut nodes = self.bvec();
                nodes.push(elseif_block);
                Some(Fragment {
                    nodes: nodes.into_bump_slice(),
                })
            } else if is_else {
                // {:else} - parse else branch
                let else_tag_start = self.current_end();
                let (else_tag_content, else_content_start) =
                    self.scan_block_tag_content(else_tag_start)?; // consume "else}"
                // Only whitespace may follow `else` before the `}` — Svelte's
                // `allow_whitespace` then `eat('}')`. `continuation_keyword_at` cannot
                // answer this: it stops the run at the first char that is neither
                // alphabetic nor a SPACE, so a U+0085 (whitespace to Rust, not to JS `\s`)
                // ended the run at `else` and was then silently dropped.
                let after_else =
                    self.strip_dispatched_keyword(else_tag_content, "else", else_tag_start)?;
                self.reject_trailing_tag_content(after_else, else_tag_start + "else".len())?;
                let else_content = self.parse_block_children(&["if"], else_content_start)?;
                self.reject_duplicate_else()?;
                Some(else_content)
            } else {
                None
            }
        } else {
            None
        };

        // Determine end position
        // For {:else if}, the nested IfBlock already consumed {/if}, so use its end position
        // For all other cases (no alternate, {:else}, {:else}{#if}), consume {/if} ourselves
        let elseif_end = alternate.as_ref().and_then(|alt| {
            if let Some(FragmentNode::IfBlock(inner)) = alt.nodes.first()
                && inner.elseif
            {
                return Some(inner.span.end as usize);
            }
            None
        });

        let end = if let Some(end_pos) = elseif_end {
            end_pos
        } else {
            self.expect_block_close_keyword("if", start)?
        };

        Ok(FragmentNode::IfBlock(IfBlock {
            elseif: is_elseif,
            test,
            consequent,
            alternate,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
            opening_tag_span,
        }))
    }

    /// Re-parse a `{#each}` iterable over `iterable` — the wider slice the head's
    /// assertion run turned out to cover, once [`each_binding_separator`] has said where
    /// the run really ends.
    ///
    /// The slice STARTS where the partial parse did and reaches further, so it re-registers
    /// everything that parse registered — rewinding to `mark` first is what keeps each
    /// registration single. Without it a comment here was listed twice in the root
    /// `comments` array and printed twice by whichever emitter owned its gap. Both
    /// re-parsing arms share this, so the rewind cannot be done at one and forgotten at the
    /// other.
    fn reparse_each_iterable(
        &mut self,
        iterable: &str,
        expr_offset: usize,
        mark: EmbeddedParseMark,
    ) -> Result<&'arena Expression<'arena>, Error> {
        self.rewind_embedded_parses(mark);
        // Leading whitespace only, and `expr_offset` is already the first non-whitespace byte:
        // this slice ends at the head's SECOND `as`, so its trailing run may be a line
        // comment's own text (`SvelteParser::parse_ts_expression`).
        let iterable = iterable.trim_start_matches(is_svelte_ws);
        // The partial parse stopped at no top-level comma, so a bare sequence here is tsc's
        // comparison reading a list the partial parse read as acorn-typescript's
        // (`f<T, U><V>(x) as A[]`) — refused inside the parse, so it is re-read the same way.
        self.parse_ts_expression_checked(iterable, expr_offset, "'}'", |this, expression| {
            match super::tag::bare_sequence_comma(expression, iterable) {
                Some(comma) => Err(this.error_expected_at("'as'", expr_offset + comma)),
                None => Ok(()),
            }
        })
    }

    /// Whether an `{#each}` head continues as its grammar requires where the iterable's
    /// partial parse stopped — `parse_each_block`'s host check on that parse
    /// (`parse_ts_expression_partial`). An `as` there leaves the rest to the binding; with
    /// none, the remainder from the iterable's end must be the `, index` / `(key)` tail
    /// and nothing after it, read by the same [`Self::split_index_and_key`] the block
    /// reads it with. Refused inside the parse, a stop that only tsc's comparison makes
    /// (`{#each f<T, U><V>(x) as item}`, stopped at the `,`) is re-read as
    /// acorn-typescript reads the list.
    ///
    /// `content` is the head after `each`, running to the tag's `}`, and `content_offset`
    /// its first byte's offset.
    fn check_each_head_tail(
        &self,
        content: &str,
        content_offset: usize,
        expression: &Expression<'arena>,
        expr_end_pos: usize,
    ) -> Result<(), Error> {
        if strip_head_keyword(&content[expr_end_pos - content_offset..], "as").is_some() {
            return Ok(());
        }
        // The SEMANTIC end, as the no-binding arm of `parse_each_block` reads it.
        let semantic_end = expression.span().end as usize;
        let tail =
            self.split_index_and_key(&content[semantic_end - content_offset..], semantic_end)?;
        self.reject_trailing_tag_content(
            &content[tail.consumed_end - content_offset..],
            tail.consumed_end,
        )
    }

    /// Parse an each block: {#each expression as context, index (key)}...{:else}...{/each}
    fn parse_each_block(&mut self, start: usize) -> Result<FragmentNode<'arena>, Error> {
        // Get the content start position (after {#)
        let tag_content_start = self.current_end();

        // Scan to find closing } and extract content
        let (tag_content, content_start) = self.scan_block_tag_content(tag_content_start)?;

        // Parse: "each expression as context, index (key)" — Svelte requires
        // whitespace after the keyword. The remainder keeps its leading
        // whitespace; `content_offset` points just past the keyword and the
        // `trim_start()` below recovers the expression's exact offset.
        let content = self.strip_block_keyword(tag_content, "each", tag_content_start)?;
        let content_offset = tag_content_start + subslice_offset(tag_content, content);

        // Use partial parsing for the iterable expression, which is also what keeps
        // `getItems(" as ")` from splitting on the `as` inside its string.
        //
        // A top-level `as` is the HOST's here, unlike `{#await}`: this head's separator IS
        // `as`, so the keyword has to survive the parse for the split below to find it
        // ([`TopLevelAs`]) — and giving it away is what obliges that split to walk the
        // assertion run itself (`each_binding_separator`). `satisfies` is not in question
        // and stays TypeScript's, so `{#each xs satisfies A[] as item}` parses here.
        //
        // The mark is what the type-assertion branch below rewinds the embedded-parse ledgers
        // to before re-parsing the same region — see `reparse_each_iterable`; `expr_offset` is
        // where BOTH parses of the iterable start, so it is derived once rather than twice.
        let mark_before_expr = self.embedded_parse_mark();
        let expr_str = content.trim_start_matches(is_svelte_ws);
        let expr_offset = content_offset + subslice_offset(content, expr_str);
        let (expression, expr_end_pos) = self.parse_ts_expression_partial(
            expr_str,
            expr_offset,
            TopLevelAs::HostSeparator,
            |this, expression, end_pos| {
                this.check_each_head_tail(content, content_offset, expression, end_pos)
            },
        )?;

        // Opening tag span is from start to content_start (includes the closing })
        let opening_tag_span = Span {
            start: start as u32,
            end: content_start as u32,
        };

        // After the expression, check for the `as` separator, `, index`, or just the head end
        let after_expr = &content[expr_end_pos - content_offset..];

        // Where the binding is, if this head has one at all. A SECOND `as` in the binding
        // means the first was a TypeScript type assertion (`items as A[] as item`), not
        // the Svelte binding separator; a run ENDING on `satisfies` (`items as A satisfies
        // B`) means there is no binding at all and the whole run is the iterable — see
        // [`EachHeadSplit`]. Only the slice each side owns differs between the cases; the
        // binding is read once whichever it is.
        let mut expression = expression;
        let binding = match strip_head_keyword(after_expr, "as") {
            None => None,
            Some(binding_str) => {
                // `binding_str` is a suffix of `content`, so its offset follows the same
                // one rule the separator walk uses — and `content[abs - content_offset]`
                // is how every absolute position below indexes back into the head.
                let binding_offset = content_offset + subslice_offset(content, binding_str);
                match each_binding_separator(
                    binding_str,
                    binding_offset,
                    self.island_nesting(),
                    self.arena,
                ) {
                    EachHeadSplit::FirstAs => Some((binding_str, binding_offset)),
                    EachHeadSplit::LaterAs { separator, binding } => {
                        let iterable = &content[..separator - content_offset];
                        expression =
                            self.reparse_each_iterable(iterable, expr_offset, mark_before_expr)?;
                        Some((&content[binding - content_offset..], binding))
                    }
                    EachHeadSplit::NoBinding { run_end } => {
                        let iterable = &content[..run_end - content_offset];
                        expression =
                            self.reparse_each_iterable(iterable, expr_offset, mark_before_expr)?;
                        None
                    }
                }
            }
        };

        let (context, index, key, binding_end) = match binding {
            Some((binding_str, binding_offset)) => {
                let (ctx, idx, k, b_end) = self.parse_each_binding(binding_str, binding_offset)?;
                (Some(ctx), idx, k, b_end)
            }
            None => {
                // No binding: the remainder is the optional `, index` and/or `(key)` —
                // the same grammar as after a context, just without one — so route it through
                // the shared parser (context stays `None`). Svelte allows index/key without
                // `as` (`{#each items, i}`, `{#each items, i (key)}`); the shared parser also
                // bounds the key with the trivia-aware bracket scanner and reports a precise
                // `consumed_end`, so trailing junk is rejected below instead of swallowed.
                // A `satisfies`-terminated run reaches here too, which is the point of
                // routing both through one tail: the two heads produce one shape.
                //
                // Read from the expression's SEMANTIC end, not `expr_end_pos` (the partial
                // parser's stop, which swallows a trailing comment as trivia) — mirroring
                // Svelte's `parser.index = expression.end`. This way a comment after the
                // iterable with no binding (`{#each items /* c */}`) becomes trailing junk
                // rejected below, not a silently kept comment. (The binding branch keeps
                // using `after_expr` so a comment *before* `as` — `{#each items /* c */ as
                // item}`, which Svelte accepts — still resolves to the binding.)
                let semantic_end = expression.span().end as usize;
                let after_semantic = &content[semantic_end - content_offset..];
                let (idx, k, b_end) =
                    self.parse_index_and_key_after_context(after_semantic, semantic_end)?;
                (None, idx, k, b_end)
            }
        };

        // The opening tag must end at `}` immediately after the binding (Svelte's final
        // `eat('}')`): only whitespace may remain. A stray comment, leftover index/key
        // fragment, or junk here is rejected — not silently dropped (content loss).
        let brace_pos = content_start - 1;
        self.reject_trailing_tag_content(&self.source[binding_end..brace_pos], binding_end)?;

        // Parse body
        let body = self.parse_block_children(&["else", "each"], content_start)?;

        // Check for fallback. Only `{:else}` is an each continuation — any other
        // `{:keyword}` (e.g. `{:catch}`, `{:then}`) is left unconsumed so it
        // surfaces as an orphan-continuation error, matching the canonical parser.
        let fallback = if self.check(TokenKind::BlockContinue)
            && self.continuation_keyword_at(self.current_end()) == "else"
        {
            let else_tag_start = self.current_end();
            let (else_tag_content, else_content_start) =
                self.scan_block_tag_content(else_tag_start)?; // consume "else}"
            // The same gate the `{#if}` continuation applies to its own `{:else}`
            // (`parse_if_block_inner`): only whitespace may follow `else` before the `}`.
            // `continuation_keyword_at` cannot answer it — its run stops at the first byte
            // that is neither alphabetic nor `is_svelte_ws`, so `{:else!}` and `{:else<NEL>}`
            // both reduce to `else`, pass the `== "else"` test above, and the trailing bytes
            // were then dropped from the output rather than rejected.
            let after_else =
                self.strip_dispatched_keyword(else_tag_content, "else", else_tag_start)?;
            self.reject_trailing_tag_content(after_else, else_tag_start + "else".len())?;
            let fallback_content = self.parse_block_children(&["each"], else_content_start)?;
            self.reject_duplicate_else()?;
            Some(fallback_content)
        } else {
            None
        };

        // Expect closing {/each}
        let end = self.expect_block_close_keyword("each", start)?;

        Ok(FragmentNode::EachBlock(EachBlock {
            expression,
            context,
            index,
            key,
            body,
            fallback,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
            opening_tag_span,
        }))
    }

    /// Parse each binding: "context, index (key)" using the TypeScript expression parser.
    ///
    /// Uses partial expression parsing which correctly handles:
    /// - Simple identifiers: `item`
    /// - Object destructuring: `{ a, b }` (commas inside braces don't split)
    /// - Array destructuring: `[a, b]` (commas inside brackets don't split)
    /// - Strings with brackets: `{ a: "}" }` (braces inside strings don't count)
    /// - Template literals: `` { a: `${x}` } ``
    ///
    /// The TS parser stops at top-level commas, so `{ a, b }, i` parses `{ a, b }` and leaves `, i`.
    ///
    /// Returns (context, index, key); the key carries the span of its parentheses.
    fn parse_each_binding(
        &mut self,
        binding: &str,
        binding_offset: usize,
    ) -> Result<EachBindingResult<'arena>, Error> {
        // Calculate leading whitespace and adjust offset accordingly
        let leading_ws = binding.len() - binding.trim_start_matches(is_svelte_ws).len();
        // A trailing trim here cannot clip a line comment the way a head's does
        // (`SvelteParser::parse_ts_expression`): every sub-parse below is bounded by the grammar —
        // the pattern by its bracket or identifier run, the annotation by its own end — and a
        // comment trailing the annotation is REJECTED, as canonical rejects it.
        let trimmed = binding.trim_matches(is_svelte_ws);
        let adjusted_offset = binding_offset + leading_ws;

        // Parse context as a PATTERN (like Svelte does), not as expression
        // Patterns are: identifiers OR destructuring {..}/[..]
        // This naturally stops at whitespace/comma/paren, avoiding the
        // `item (key)` being parsed as a function call
        let (context, pattern_end) = self.parse_block_pattern(trimmed, adjusted_offset)?;

        // Parse remaining: ", index" and/or "(key)"
        let consumed = pattern_end - adjusted_offset;
        let remaining = &trimmed[consumed..];
        let (index, key, consumed_end) =
            self.parse_index_and_key_after_context(remaining, pattern_end)?;

        Ok((context, index, key, consumed_end))
    }

    /// Parse a block or tag pattern — Svelte's `read_pattern` (`1-parse/read/context.js`):
    /// an identifier or a destructuring pattern, each with an optional `: Type` annotation
    /// (`{#each xs as x: T}`, `{:then { a }: T}`, `{@const [a]: T = expr}`). The one reader
    /// for every `read_pattern` position — `{#each}`'s context, the `{:then}`/`{:catch}`
    /// value, the `{@const}` id — returning the pattern and the absolute offset just past
    /// the binding (the annotation's end when there is one). What follows is the caller's
    /// grammar: `, index` / `(key)`, the tag's `}`, or the declarator's `=`.
    ///
    /// Both halves of canonical's reading are enforced here, and the caller must not re-find
    /// either with a byte scan:
    ///
    /// - **The head gate.** The binding STARTS as a name (the shared `read_identifier`,
    ///   reserved-word rule included) or as a `{`/`[` opening a matched bracket; anything
    ///   else — a paren shell `(a)`, a comment — is `expected_pattern`. A member or paren
    ///   target stays legal INSIDE a destructure, which acorn reads as an assignment target.
    /// - **The bounded extent.** The pattern ends at the name's last byte or the bracket's
    ///   close, so a tail that would continue an expression (`a.b`, `[a][0]`, `{ a }.b`,
    ///   `a = 1`, `{ a } (a.id)` read as a *call*) is left for the caller to reject or
    ///   consume. The annotation's end is the TS type parse's own, never a scan — a
    ///   function type's `=>` and a type argument list's `,`/`>` sit at depth 0.
    ///
    /// The annotation attaches through `tsv_ts::__private::attach_pattern_type_annotation`, which
    /// owns the span convention: the span stays on the **bare** binding for every kind (only a
    /// destructuring pattern's wire `end` widens at emit time — the one kind whose byte range and
    /// `loc` genuinely disagree; an annotated identifier stays bare on the wire too, per Svelte's
    /// `read_pattern`). So `pattern.span().end` is the bare end, and the returned offset —
    /// `tsv_ts::__private::pattern_binding_end` — the end past any annotation. A comment in the gap
    /// on either side of the annotation is rejected by the reads that bound it: the annotation
    /// parse starts only at a `:`, and the caller's own check of what follows the returned offset
    /// (`, index`, `}`, `=`) finds anything else there.
    pub(super) fn parse_block_pattern(
        &mut self,
        input: &str,
        offset: usize,
    ) -> Result<(&'arena Expression<'arena>, usize), Error> {
        let trimmed = input.trim_start_matches(is_svelte_ws);
        let ws_len = input.len() - trimmed.len();
        let adjusted = offset + ws_len;

        // The pattern's extent, bounded so the annotation (and whatever the caller's
        // grammar puts after the binding) stays out of the expression parse.
        // This split IS canonical's: `read_pattern` opens with `parser.read_identifier()`
        // and only falls to acorn when that reads nothing — and then only on a `{`/`[`
        // (`expected_pattern` otherwise). So the identifier arm goes through the same
        // reader (reserved-word rule included) and the bracket arm keeps the deferral.
        let end = match trimmed.as_bytes().first() {
            Some(&open @ (b'{' | b'[')) => self.matching_bracket_end(trimmed, open, adjusted)?,
            _ => {
                let Some(name) = self.read_identifier(trimmed, adjusted)? else {
                    return Err(
                        self.error_expected_at("identifier or destructure pattern", adjusted)
                    );
                };
                name.len()
            }
        };
        // `parse_ts_pattern` yields ObjectPattern/ArrayPattern (not the Object/Array
        // *Expression* the plain expression parser would).
        let expr = self.parse_ts_pattern(&trimmed[..end], adjusted)?;

        let after_pattern = trimmed[end..].trim_start_matches(is_svelte_ws);
        if !after_pattern.starts_with(':') {
            return Ok((expr, adjusted + end));
        }
        let ws_before_colon = trimmed.len() - end - after_pattern.len();
        let colon_offset = adjusted + end + ws_before_colon;
        // The annotation is its own sub-parse of the host document, so its comments
        // exist nowhere else — dropping them dropped the comment outright
        // (`{#each xs as x: /* c */ T}`), and with no registration the print-once
        // ledger could not see the loss either. `parse_ts_type_annotation` collects
        // them the way every sibling sub-parse does; they keep their true columns,
        // since the synthetic-`(` shift belongs to the destructure parse alone (see
        // `parse_ts_pattern`).
        let ta = self.parse_ts_type_annotation(after_pattern, colon_offset)?;
        // The consumed extent is the ANNOTATION's own end. Reporting where the
        // sub-parse's lexer stopped hands the tail back with a trailing comment
        // silently eaten — canonical Svelte rejects one there
        // (`{#each xs as x: T /* c */}` → `expected_token`), and accepting it here
        // would drop the comment.
        let annotation_end = ta.span.end as usize;
        tsv_ts::__private::attach_pattern_type_annotation(expr, ta, self.arena)?;
        Ok((expr, annotation_end))
    }

    /// The byte offset just past the bracket that closes the `open` (`{` or `[`) at
    /// `input[0]`, so `&input[..end]` is the whole bracketed run. Comment- and string-aware
    /// via the shared cursor. `offset` is `input[0]`'s source offset, where an unmatched
    /// bracket is reported.
    fn matching_bracket_end(&self, input: &str, open: u8, offset: usize) -> Result<usize, Error> {
        let close = if open == b'{' { b'}' } else { b']' };
        let bytes = input.as_bytes();
        match_bracket(bytes, 0, bytes.len(), open, close, TriviaProfile::JS)
            .map(|close_pos| close_pos + 1) // include the closing bracket
            .ok_or_else(|| self.error_msg_at("Unmatched bracket", offset))
    }

    /// Parse ", index" and/or "(key)" after the context pattern
    ///
    /// Returns (index, key); the key carries the span of its parentheses.
    fn parse_index_and_key_after_context(
        &mut self,
        remaining: &str,
        remaining_offset: usize,
    ) -> Result<IndexAndKeyResult<'arena>, Error> {
        let tail = self.split_index_and_key(remaining, remaining_offset)?;
        let index = tail.index.map(|name| self.alloc_str_in(name));
        let key = match tail.key {
            Some(region) => Some(EachKey {
                expression: self.parse_ts_expression(region.expr_str, region.expr_offset, "')'")?,
                span: region.span,
            }),
            None => None,
        };
        Ok((index, key, tail.consumed_end))
    }

    /// Read the ", index" and/or "(key)" tail after an `{#each}` context — or after an
    /// iterable with no context — down to where it stops, without parsing the key: the
    /// half of [`Self::parse_index_and_key_after_context`] that needs no `&mut`, so the
    /// iterable's own parse can ask it as its host check ([`Self::check_each_head_tail`])
    /// and the two cannot read the tail differently.
    fn split_index_and_key<'s>(
        &self,
        remaining: &'s str,
        remaining_offset: usize,
    ) -> Result<EachIndexAndKey<'s>, Error>
    where
        'a: 's,
    {
        let trimmed = remaining.trim_start_matches(is_svelte_ws);
        let ws_len = remaining.len() - trimmed.len();
        let offset = remaining_offset + ws_len;

        let mut rest = trimmed;
        let mut rest_offset = offset;
        let mut index = None;
        // Absolute offset just past the last token the binding consumed. Starts at the
        // context end (`remaining_offset`): with no index/key the binding ends there, so
        // everything in `remaining` is trailing and the caller rejects it.
        let mut consumed_end = remaining_offset;

        // Check for ", index" — the index is a bare identifier (Svelte's `read_identifier`).
        if let Some(after_comma) = rest.strip_prefix(',') {
            let after_comma_trimmed = after_comma.trim_start_matches(is_svelte_ws);
            let comma_ws = after_comma.len() - after_comma_trimmed.len();

            // The index is a bare identifier read the way Svelte reads it — so a reserved
            // word (`{#each x as y, if}`) is rejected here rather than stored. A non-start
            // (`, /* c */ i`, `, 5`) leaves the index unread and the comma unconsumed, so
            // the caller's trailing check reports it, matching Svelte's "Expected an
            // identifier".
            let idx_offset = offset + 1 + comma_ws;
            if let Some(name) = self.read_identifier(after_comma_trimmed, idx_offset)? {
                index = Some(name);
                rest = &after_comma_trimmed[name.len()..];
                rest_offset = idx_offset + name.len();
                consumed_end = rest_offset;
            }
        }

        // Check for "(key)" — match the `)` with the expression scanner, so a `)` inside a
        // string, comment, template or regex literal in the key (`(/[)]/.test(s))`) can't
        // end it early, and any trailing junk after the real `)` is left for the caller's
        // trailing check (not swallowed). The key is an expression, not a pattern, so the
        // pattern scanner's regex-blindness (`match_bracket`) is wrong here.
        let rest_trimmed = rest.trim_start_matches(is_svelte_ws);
        let key = if rest_trimmed.starts_with('(') {
            let key_ws = rest.len() - rest_trimmed.len();
            let paren_start = rest_offset + key_ws; // absolute offset of '('
            let close = scan_to_matching_paren(rest_trimmed.as_bytes(), 1)
                .ok_or_else(|| self.error_expected_at("')'", paren_start + rest_trimmed.len()))?;
            let key_str = &rest_trimmed[1..close];
            let key_offset = paren_start + 1; // after '('
            // Leading whitespace only — the trailing run may be a line comment's own text
            // (`SvelteParser::parse_ts_expression`).
            let key_expr_str = key_str.trim_start_matches(is_svelte_ws);
            // Span includes the parentheses: from '(' to after ')'.
            let span = Span::new(paren_start as u32, (paren_start + close + 1) as u32);
            consumed_end = span.end as usize;
            Some(EachKeyRegion {
                expr_str: key_expr_str,
                expr_offset: key_offset + (key_str.len() - key_expr_str.len()),
                span,
            })
        } else {
            None
        };

        Ok(EachIndexAndKey {
            index,
            key,
            consumed_end,
        })
    }

    /// Parse an await block: {#await expression}...{:then value}...{:catch error}...{/await}
    fn parse_await_block(&mut self, start: usize) -> Result<FragmentNode<'arena>, Error> {
        // Get the content start position (after {#)
        let tag_content_start = self.current_end();

        // Scan to find closing } and extract content
        let (tag_content, content_start) = self.scan_block_tag_content(tag_content_start)?;

        // Parse: "await expression" or "await expression then value" — Svelte
        // requires whitespace after the keyword. The remainder keeps its leading
        // whitespace; `content_offset` points just past the keyword and the
        // `trim_start()` below recovers the expression's exact offset.
        let content = self.strip_block_keyword(tag_content, "await", tag_content_start)?;
        let content_offset = tag_content_start + subslice_offset(tag_content, content);

        // Use partial parsing for the promise expression, which is also what keeps
        // `fetch(" then ")` from splitting on the `then` inside its string.
        //
        // A top-level `as` is TypeScript's here, unlike `{#each}`: this head's separators
        // are `then` / `catch`, no part of type syntax, so an `as` in an await head is
        // always an assertion and the parse ends on its own at the clause keyword
        // ([`TopLevelAs`]) — no assertion-run walk needed, which is the whole difference
        // between the two heads. Giving the keyword away rejected every unparenthesized
        // assertion canonical accepts (`{#await p as T then v}`) and — since the printer
        // strips the parens the authored form needs — turned `{#await (p as T) then v}`
        // into output tsv itself could not re-read.
        //
        // What the head must continue with where the parse stopped — a `then` / `catch`
        // clause, or the tag's end — is checked inside the parse
        // (`parse_ts_expression_partial`), so a stop only tsc's comparison makes
        // (`{#await f<T, U><V>(x) then v}`, stopped at the `,`) is re-read as
        // acorn-typescript reads the list.
        let expr_str = content.trim_start_matches(is_svelte_ws);
        let (expression, expr_end_pos) = self.parse_ts_expression_partial(
            expr_str,
            content_offset + subslice_offset(content, expr_str),
            TopLevelAs::Assertion,
            |this, _, end_pos| {
                let after_expr = &content[end_pos - content_offset..];
                match await_head_clause(after_expr) {
                    Some(_) => Ok(()),
                    None => this.reject_trailing_tag_content(after_expr, end_pos),
                }
            },
        )?;

        // Opening tag span is from start to content_start (includes the closing })
        let opening_tag_span = Span {
            start: start as u32,
            end: content_start as u32,
        };

        // Check what follows the expression
        let expr_consumed = expr_end_pos - content_offset;
        let after_expr = &content[expr_consumed..];

        // Which clause the HEAD fills, and with what binding text. The block form fills
        // none — its first body is the pending phase — while each shorthand fills its
        // own, which is exactly the state canonical's `next` guards the continuations
        // against. Naming it here is what lets all three forms share one continuation
        // loop below: with a copy per shorthand arm, a duplicate-clause guard added
        // to one copy would silently not apply to the others.
        //
        // With no `then`/`catch` shorthand the opening tag ends right after the promise
        // expression — trailing content like `{#await p garbage}` or a shorthand jammed
        // against the expression (`{#await p then(v)}`) was refused inside the parse, as
        // the canonical parser refuses both.
        let head_clause = await_head_clause(after_expr);

        // The block form (`{#await x}…{/await}`) always carries a pending Fragment —
        // empty or not — unlike the inline `then`/`catch` shorthand (no pending
        // phase); the writer emits `{Fragment, []}` vs `null` from this.
        let pending_block = head_clause.is_none();

        // The head's binding, if it carries one. The text starts right after
        // "expression <keyword> "; the pattern parser trims its own leading whitespace,
        // so pass the raw slice plus that offset. The valueless form (`{#await p then}`)
        // yields an empty slice and no binding.
        let head_binding = match head_clause {
            Some((_, s)) if !s.is_empty() => {
                let keyword_end = expr_end_pos + subslice_offset(after_expr, s);
                Some(self.parse_await_value_pattern(s, keyword_end)?)
            }
            _ => None,
        };

        // One `(fragment, binding)` pair per clause, so the fill and the filled-check
        // always name the same slot. Keeping them as four independent locals is what let
        // the guard be added to one arm and not the other.
        let mut then_slot: AwaitSlot<'arena> = (None, None);
        let mut catch_slot: AwaitSlot<'arena> = (None, None);
        let mut pending = None;

        // The first body belongs to whichever clause the head named.
        let first_body = self.parse_block_children(AWAIT_BODY_STOPS, content_start)?;
        match head_clause {
            Some((AwaitClause::Then, _)) => then_slot = (Some(first_body), head_binding),
            Some((AwaitClause::Catch, _)) => catch_slot = (Some(first_body), head_binding),
            None => pending = (!first_body.nodes.is_empty()).then_some(first_body),
        }

        // Read `{:then}` / `{:catch}` continuations in either order. A slot may be
        // filled once — canonical's `next` guards each arm with `if (block.then)` /
        // `if (block.catch)` and raises `block_duplicate_clause`. Without the guard the
        // assignment OVERWRITES, and the discarded fragment's markup is gone from the
        // AST: a formatter reprinting it would silently delete a branch of the document.
        while let Some(clause) = [AwaitClause::Then, AwaitClause::Catch]
            .into_iter()
            .find(|c| self.check_await_continuation(c.keyword()))
        {
            let slot = match clause {
                AwaitClause::Then => &mut then_slot,
                AwaitClause::Catch => &mut catch_slot,
            };
            if slot.0.is_some() {
                return Err(self.error_duplicate_clause(clause.keyword()));
            }
            *slot = self.parse_await_continuation(clause.keyword(), AWAIT_BODY_STOPS)?;
        }

        let (then_fragment, value) = then_slot;
        let (catch_fragment, error) = catch_slot;
        let end = self.expect_block_close_keyword("await", start)?;

        Ok(FragmentNode::AwaitBlock(AwaitBlock {
            expression,
            value,
            error,
            pending,
            pending_block,
            then: then_fragment,
            catch: catch_fragment,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
            opening_tag_span,
        }))
    }

    /// Reject a second `{:else}` / `{:else if}` once the block's alternate is taken.
    ///
    /// Canonical's `next` (`1-parse/state/tag.js`) guards the slot the same way —
    /// `block_duplicate_clause` once `block.alternate` / `block.fallback` is set, as for
    /// `{#await}`'s `{:then}` / `{:catch}` — because writing it again would replace the
    /// fragment and drop the first branch's markup from the AST.
    ///
    /// A matched verdict (`docs/conformance_svelte.md` §Block Continuation Clauses);
    /// only the wording below is tsv's own. Called where the alternate has just been
    /// parsed, so the current token — the stray `{:` — carries the error's position.
    /// Any other continuation keyword (`{:catch}` after an `{:else}`) is left alone:
    /// it takes the misplaced-continuation error instead.
    ///
    /// The two spellings take different messages because only one of them is a
    /// **repeat**: a second `{:else}` is a duplicate, while an `{:else if}` after an
    /// `{:else}` is the block's *first* `{:else if}` landing on an alternate the
    /// `{:else}` already took. Calling that a duplicate names a clause the author
    /// never wrote twice.
    fn reject_duplicate_else(&self) -> Result<(), Error> {
        if !self.check(TokenKind::BlockContinue) {
            return Ok(());
        }
        let mut words = continuation_words(self.continuation_keyword_at(self.current_end()));
        if words.next() != Some("else") {
            return Ok(());
        }
        Err(if words.next() == Some("if") {
            self.error_clause_after("else if", "else")
        } else {
            self.error_duplicate_clause("else")
        })
    }

    /// Check if the next token is a BlockContinue with the given keyword (e.g., "catch", "then").
    fn check_await_continuation(&self, keyword: &str) -> bool {
        self.check(TokenKind::BlockContinue)
            && self
                .continuation_keyword_at(self.current_end())
                .starts_with(keyword)
    }

    /// Parse a `{:then value}` / `{:catch error}` continuation block within an await block.
    /// `keyword` is `"then"` or `"catch"`; `stop_keywords` are the continuations that end this
    /// block's body (`{:catch}` always stops only at `{/await}`; `{:then}` also stops at a
    /// following `{:catch}` in the full form). Returns `(fragment, binding_pattern)`.
    fn parse_await_continuation(
        &mut self,
        keyword: &str,
        stop_keywords: &[&str],
    ) -> Result<(Option<Fragment<'arena>>, Option<&'arena Expression<'arena>>), Error> {
        let tag_start = self.current_end();
        let (tag_content, content_start) = self.scan_block_tag_content(tag_start)?;
        // The value is absent only when the `}` follows the keyword directly (`{:then}`).
        // Canonical's `next` tries `eat('}')` first and otherwise commits to a pattern
        // (`require_whitespace` + `read_pattern`), so ANY text after the keyword — a
        // whitespace-only run included (`{:then }`, `{:catch⏎}`) — must read as one, and an
        // empty pattern is `expected_pattern`. Trimming first made `{:then }` a valueless
        // `{:then}`. The opening shorthand is the other rule: `{#await p then }` is valid
        // (its `/\s*}/y` test), which `strip_head_keyword_or_final` owns.
        let rest = self.strip_keyword_value(tag_content, keyword, tag_start)?;
        let binding = if rest.is_empty() {
            None
        } else {
            let offset = tag_start + subslice_offset(tag_content, rest);
            Some(self.parse_await_value_pattern(rest, offset)?)
        };

        let fragment = self.parse_block_children(stop_keywords, content_start)?;
        Ok((Some(fragment), binding))
    }

    /// Read the leading alphabetic keyword at `pos` in the source — the `if` in
    /// `{#if}`, the `each` in `{/each}`, the `html` in `{@html}`. Stops at the
    /// first non-alphabetic byte (space, `}`, …); returns `""` when there is none.
    pub(super) fn keyword_at(&self, pos: usize) -> &'a str {
        let remaining = &self.source[pos..];
        let end = remaining
            .find(|c: char| !c.is_alphabetic())
            .unwrap_or(remaining.len());
        &remaining[..end]
    }

    /// Read the continuation keyword-run at `pos` — the alphabetic-and-space run
    /// after `{:`, trailing whitespace trimmed. Unlike `keyword_at` this keeps internal
    /// spaces so the two-word `else if` survives; callers compare against `"else"`,
    /// `"else if"`, `"catch"`, etc. Trailing content makes the run miss every keyword (e.g.
    /// `{:else garbage}` yields `"else garbage"`, which is neither `else` nor
    /// `else if`), so it is left unconsumed and surfaces as an error.
    ///
    /// A run that opens with whitespace names **no** keyword (`""`). Canonical's `next`
    /// (`1-parse/state/tag.js`) eats the keyword immediately after the `:` — the only
    /// whitespace it allows is between the `{` and the `:` — so `{: then}` and `{: else}`
    /// are `expected_token`. Trimming the front here instead handed every continuation
    /// reader a tag whose content opens with whitespace: `{: then}` then bound a value
    /// NAMED `then`, and `{:<NBSP><U+3000>else}` sliced `else` off a byte offset inside a
    /// multi-byte space and panicked.
    fn continuation_keyword_at(&self, pos: usize) -> &'a str {
        let remaining = &self.source[pos..];
        if remaining.starts_with(is_svelte_ws) {
            return "";
        }
        let end = remaining
            .find(|c: char| !c.is_alphabetic() && !is_svelte_ws(c))
            .unwrap_or(remaining.len());
        // [`is_svelte_ws`] on the leading test, the cut and the trim, and they must stay the
        // same class: the cut decides which characters are inside the run, so a trim answering
        // a different question would either leave a member in or take a non-member out.
        //
        // ⚠️ A cut of `c != ' '` — a LITERAL SPACE — would make this the narrowest
        // whitespace class in the parser and break the two-word `{:else if}` in both
        // directions at once. A separator Svelte's `allow_whitespace` crosses but a space
        // isn't (a tab, a NEWLINE, or any non-ASCII JS `\s`) ended the run at `else`, so
        // `{:else⏎if x}` read as a plain `{:else}` and the `if x` then failed the head's `}`
        // — an OVER-REJECTION of a wrapped else-if, the one spelling here a human actually
        // writes. The same cut swallowed junk in the other direction: `{:else⇥junk}` also
        // reduced to `else`, so `{#each}`'s exact `== "else"` test took the branch and
        // ACCEPTED a head canonical rejects, where `{:else junk}` (space) was correctly
        // refused. One class, both bugs.
        //
        // ⚠️ Not `char::is_whitespace` / `str::trim` either — that is Rust's White_Space,
        // which disagrees with JS `\s` in both directions (it has U+0085 NEL, it lacks
        // U+FEFF). NEL must stay OUTSIDE the run so it reads as trailing junk, exactly as
        // canonical treats it.
        remaining[..end].trim_end_matches(is_svelte_ws)
    }

    /// Strip a leading block/tag keyword, enforcing the whitespace Svelte
    /// requires between the keyword and any value that follows. The value may be
    /// absent (`{:then}` → `Ok("")`), but a value jammed against the keyword
    /// (`{:then(v)}`, `{:thenx}`) is rejected — matching the canonical parser,
    /// which emits `expected_whitespace`. Any whitespace counts (space, tab,
    /// newline), so the returned remainder is left untrimmed; callers read it as their
    /// grammar needs and recover span offsets with `subslice_offset`.
    fn strip_keyword_value(
        &self,
        content: &'a str,
        keyword: &str,
        keyword_start: usize,
    ) -> Result<&'a str, Error> {
        let rest = self.strip_dispatched_keyword(content, keyword, keyword_start)?;
        if rest.is_empty() || rest.starts_with(is_svelte_ws) {
            Ok(rest)
        } else {
            Err(self.error_expected_at(&format!("whitespace after `{keyword}`"), keyword_start))
        }
    }

    /// Strip the `keyword` the caller dispatched on at `keyword_start` off the head of
    /// `content`, or reject. Every caller already read that keyword there, so a miss is an
    /// error rather than a reason to read the whole tag as what follows the keyword: that
    /// fallback is how `{: then}` bound a value named `then`.
    fn strip_dispatched_keyword(
        &self,
        content: &'a str,
        keyword: &str,
        keyword_start: usize,
    ) -> Result<&'a str, Error> {
        content
            .strip_prefix(keyword)
            .ok_or_else(|| self.error_expected_at(&format!("`{keyword}`"), keyword_start))
    }

    /// Like `strip_keyword_value`, but the value is mandatory: the keyword
    /// standing alone (`{#each}`, `{@html}`) is also rejected. Used by the blocks
    /// and tags whose expression or name is required.
    pub(super) fn strip_block_keyword(
        &self,
        content: &'a str,
        keyword: &str,
        keyword_start: usize,
    ) -> Result<&'a str, Error> {
        let rest = self.strip_keyword_value(content, keyword, keyword_start)?;
        if rest.is_empty() {
            return Err(
                self.error_expected_at(&format!("whitespace after `{keyword}`"), keyword_start)
            );
        }
        Ok(rest)
    }

    /// Require that `region` — whose first byte is at absolute source offset `region_start` —
    /// holds only whitespace before the tag's closing `}`. This is Svelte's `allow_whitespace`
    /// then `eat('}')` after a tag's payload: a stray comment, leftover binding fragment, or
    /// junk is rejected (erroring at the first non-whitespace byte), never silently dropped.
    /// Shared by every block whose tag ends right after its payload — `{#each}`'s binding,
    /// `{#await}`'s promise, `{#snippet}`'s `)`, and every `{/block}` close.
    fn reject_trailing_tag_content(&self, region: &str, region_start: usize) -> Result<(), Error> {
        let trailing = region.trim_start_matches(is_svelte_ws);
        if !trailing.is_empty() {
            let trailing_start = region_start + subslice_offset(region, trailing);
            return Err(self.error_expected_at("'}'", trailing_start));
        }
        Ok(())
    }

    /// Parse a `{#await}` `then`/`catch` binding pattern (the value/error). Svelte reads it
    /// with `read_pattern` and then `eat('}')` over `allow_whitespace`, so the binding is
    /// [`Self::parse_block_pattern`]'s — the head gate and the bounded extent — and
    /// everything after it up to the head's `}` must be whitespace. That one rule rejects
    /// every tail canonical does: a comment BETWEEN the binding and its `}` on either side of
    /// the annotation (`{:then a /* c */: A}`, `{:then a: A /* c */}`), and an expression
    /// continuing past the pattern (`{:then a.b}`, `{:then [a][0]}`, `{:then a = 1}`). A
    /// comment INSIDE a destructure (`{ a /* c */ }`) or INSIDE the type annotation
    /// (`value: /* c */ number`) stays valid — it's acorn trivia within the pattern/type.
    /// `region` runs to the head's `}`; `region_offset` is the absolute source offset of
    /// `region[0]`.
    fn parse_await_value_pattern(
        &mut self,
        region: &str,
        region_offset: usize,
    ) -> Result<&'arena Expression<'arena>, Error> {
        let (pattern, binding_end) = self.parse_block_pattern(region, region_offset)?;
        self.reject_trailing_tag_content(&region[binding_end - region_offset..], binding_end)?;
        Ok(pattern)
    }

    /// Consume the closing `{/expected}` tag and return the position after it.
    /// `block_start` is the byte offset of the opening `{#expected`, used to
    /// locate the unclosed-block error.
    ///
    /// Three failure modes, all rejected by the canonical parser:
    /// - the block is left unclosed (`{#if x}a`) — reported at `block_start`;
    /// - the close names a different block — a mismatch like `{#if x}…{/each}`;
    /// - the close carries trailing junk (`{/each foo}`) — only whitespace may
    ///   follow the keyword before `}`.
    fn expect_block_close_keyword(
        &mut self,
        expected: &str,
        block_start: usize,
    ) -> Result<usize, Error> {
        // A `{:…}` still standing here is one this block's reader did not take — a keyword
        // the block has no clause for (`{#each}…{:then}`), or one written after a space
        // (`{: else}`). Canonical's `next` rejects it at the continuation, not at the block.
        if self.check(TokenKind::BlockContinue) {
            return Err(self.error_misplaced_continuation(expected));
        }

        // Unclosed block: Svelte requires a matching `{/expected}`.
        if !self.check(TokenKind::BlockClose) {
            return Err(self.error_unclosed_at(&format!("{{#{expected}}} block"), block_start));
        }

        // The keyword after `{/` must match the open block.
        if self.keyword_at(self.current_end()) != expected {
            return Err(self.error_expected_at(&format!("{{/{expected}}}"), self.current_start()));
        }

        let close_tag_start = self.current_end();
        let (close_content, after_close) = self.scan_block_tag_content(close_tag_start)?;

        // Only whitespace may follow the keyword: `{/each foo}` is rejected.
        // The keyword matched above, so `close_content` starts with `expected`.
        self.reject_trailing_tag_content(
            &close_content[expected.len()..],
            close_tag_start + expected.len(),
        )?;

        Ok(after_close)
    }

    /// The error for a `{:…}` continuation the `expected` block does not take, at the
    /// continuation — canonical's `next` (`1-parse/state/tag.js`), which dispatches on the
    /// block the continuation lands in: the clause list the block does take (`{#if}`,
    /// `{#each}`, `{#await}`, each an `expected_token`), `block_invalid_elseif` for the
    /// welded `{:elseif}`, and `block_invalid_continuation_placement` for a block with no
    /// continuations at all (`{#key}`, `{#snippet}`).
    fn error_misplaced_continuation(&self, expected: &str) -> Error {
        // The `{:…}` braces are spelled by `clause`, so no literal reads as a format argument.
        let clause = |keyword: &str| format!("{{:{keyword}}}");
        let message = match expected {
            "if" if self.source[self.current_end()..].starts_with("elseif") => {
                "'elseif' should be 'else if'".to_owned()
            }
            "if" => format!("Expected token {} or {}", clause("else"), clause("else if")),
            "each" => format!("Expected token {}", clause("else")),
            "await" => format!(
                "Expected token {} or {}",
                clause("then ..."),
                clause("catch ...")
            ),
            _ => format!(
                "{} block is invalid at this position (did you forget to close the preceding \
                 element or block?)",
                clause("...")
            ),
        };
        self.error_msg_at(&message, self.current_start())
    }

    /// Parse a key block: {#key expression}...{/key}
    fn parse_key_block(&mut self, start: usize) -> Result<FragmentNode<'arena>, Error> {
        // Get the content start position (after {#)
        let tag_content_start = self.current_end();

        // Scan to find closing } and extract content
        let (tag_content, content_start) = self.scan_block_tag_content(tag_content_start)?;

        // Parse: "key expression" — Svelte requires whitespace after the keyword. Leading
        // whitespace only — the trailing run may be a line comment's own text
        // (`SvelteParser::parse_ts_expression`).
        let expr_str = self
            .strip_block_keyword(tag_content, "key", tag_content_start)?
            .trim_start_matches(is_svelte_ws);

        let expr_offset = tag_content_start + subslice_offset(tag_content, expr_str);
        let expression = self.parse_ts_expression(expr_str, expr_offset, "'}'")?;

        // Opening tag span is from start to content_start (includes the closing })
        let opening_tag_span = Span {
            start: start as u32,
            end: content_start as u32,
        };

        // Parse fragment
        let fragment = self.parse_block_children(&["key"], content_start)?;

        // Expect closing {/key}
        let end = self.expect_block_close_keyword("key", start)?;

        Ok(FragmentNode::KeyBlock(KeyBlock {
            expression,
            fragment,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
            opening_tag_span,
        }))
    }

    /// Parse a snippet block: {#snippet name(params)}...{/snippet}
    /// Also handles TypeScript generics: `{#snippet name<T>(params)}`
    fn parse_snippet_block(&mut self, start: usize) -> Result<FragmentNode<'arena>, Error> {
        // Get the content start position (after {#)
        let tag_content_start = self.current_end();

        // Scan to find closing } and extract content
        let (tag_content, content_start) = self.scan_block_tag_content(tag_content_start)?;

        // Parse: "snippet name(params)" or "snippet name<T>(params)" — Svelte
        // requires whitespace after the keyword.
        let content = self
            .strip_block_keyword(tag_content, "snippet", tag_content_start)?
            .trim_matches(is_svelte_ws);
        let content_bytes = content.as_bytes();
        // Absolute offset of `content[0]` (the name's first byte) in the source, the
        // base for every span and error position below.
        let content_offset = tag_content_start + subslice_offset(tag_content, content);

        // Mirror Svelte's snippet-head grammar (`1-parse/state/tag.js`): read the name,
        // then an optional `<…>` generic via the naive `<`/`>` matcher, then REQUIRE a
        // `(`. Svelte's generic matcher tracks only angle depth (never parens), so a `>`
        // from a `=>` / `>=` / `>>` closes the generic early and the required `(` can't be
        // found — Svelte rejects, and we reject in lockstep. A function type (or any stray
        // `>`) in a snippet generic is invalid Svelte, so corrupting it on format would be
        // worse than a parse error. See `find_matching_angle_bracket`.

        // Name: the leading identifier run, read the way Svelte's `read_identifier` reads
        // it. `content` is trimmed, so it starts at the name.
        let Some(name_str) = self.read_identifier(content, content_offset)? else {
            return Err(self.error_expected_at("snippet name", content_offset));
        };
        let name_len = name_str.len();
        // the slice is the name alone, so its end is the name's
        let expression =
            self.parse_ts_expression(name_str, content_offset, "end of snippet name")?;
        // The reserved-word filter above is what makes this an `Identifier` rather than
        // whatever `this` / `null` / `true` / `super` would have parsed to — a
        // `ThisExpression`, a `Literal`, a `Super`, none of which the wire's
        // `SnippetBlock.expression` may hold. Stated rather than assumed, so the filter and
        // the node shape can never drift apart silently.
        if !matches!(expression.kind, ExpressionKind::Identifier(_)) {
            return Err(self.error_expected_at("snippet name", content_offset));
        }

        // Optional `<…>` generic. `head_start` is the `<` (or, with no generic, the `(`)
        // where the parseable signature head begins — the wrapper slice below spans from
        // there through the matching `)`.
        let after_name = content[name_len..].trim_start_matches(is_svelte_ws);
        let head_start = content.len() - after_name.len();
        let (after_generic, type_params_raw): (usize, Option<&'arena str>) =
            if after_name.starts_with('<') {
                // `type_params_raw` is the raw inner text — feeds the public AST's `typeParams`
                // string (Svelte stores it raw too) and the parse-failure fallback.
                let close_pos =
                    self.find_matching_angle_bracket(content, content_offset, head_start)?;
                (
                    close_pos + 1,
                    Some(self.alloc_str_in(&content[head_start + 1..close_pos])),
                )
            } else {
                (head_start, None)
            };

        // Require `(` after only whitespace — Svelte's `allow_whitespace` then
        // `eat('(', true)`. Crucially this skips whitespace but NOT comments, so
        // `<T> /* c */ (…)` is rejected exactly as Svelte rejects it.
        let after_generic_str = &content[after_generic..];
        let paren_pos = after_generic
            + (after_generic_str.len() - after_generic_str.trim_start_matches(is_svelte_ws).len());
        if !content[paren_pos..].starts_with('(') {
            return Err(self.error_expected_at("'('", content_offset + paren_pos));
        }

        // Opening tag span is from start to content_start (includes the closing })
        let opening_tag_span = Span {
            start: start as u32,
            end: content_start as u32,
        };

        // The `)` matching the opening `(`, found the way Svelte finds it
        // (`snippet_params_close`). Svelte requires the close (`eat(')', true)`); an
        // unmatched `(` is rejected.
        let close_paren = snippet_params_close(content_bytes, paren_pos)
            .ok_or_else(|| self.error_expected_at("')'", content_offset + content.len()))?;

        // Only whitespace may follow `)` before the closing `}` — Svelte's
        // `allow_whitespace` then `eat('}', true)`. `{#snippet fn() junk}` is rejected.
        self.reject_trailing_tag_content(
            &content[close_paren + 1..],
            content_offset + close_paren + 1,
        )?;

        // Absolute source span of the parens (`start` = `(`, `end` = `)`), for comment
        // lookup when printing the parameter list.
        let params_paren = Some(Span {
            start: (content_offset + paren_pos) as u32,
            end: (content_offset + close_paren) as u32,
        });
        let params_str = &content[paren_pos + 1..close_paren];

        // Parse the signature head `<TP>(PARAMS)` as `function f<TP>(PARAMS) {}` so every
        // position — type parameters (constraints/defaults/modifiers/comments),
        // typed/destructured params, comments anywhere — goes through the canonical
        // comment-collecting parser. Wrapping a *contiguous* source slice (from the `<` or
        // `(` through the matching `)`) keeps the single `base` offset valid across both
        // `<…>` and `(…)`. Collected comments merge into the root buffer (the printer
        // locates them by position).
        //
        // A parse failure REJECTS the component, in lockstep with Svelte: its own reader
        // hands the same slice to `parse_expression_at` as `(PARAMS) => {}` and lets the
        // throw out (`1-parse/state/tag.js`). Swallowing it here instead — keeping the raw
        // text — accepted every malformed head (`fn(a b)`, `fn(,,)`, `fn<T extends>()`) and
        // was lossy twice over: the wire emits no parameters at all, and the printer
        // reflowed the kept text.
        let mut type_parameters: Option<tsv_ts::ast::TSTypeParameterDeclaration<'arena>> = None;
        let mut parameters: &'arena [Expression<'arena>] = &[];
        if type_params_raw.is_some() || !params_str.trim_matches(is_svelte_ws).is_empty() {
            // The head runs from where the signature begins (`<` or `(`) through the `)`.
            let head_slice = &content[head_start..=close_paren];
            const WRAPPER_PREFIX: &str = "function f";
            let wrapper = format!("{WRAPPER_PREFIX}{head_slice} {{}}");
            let base = (content_offset + head_start).saturating_sub(WRAPPER_PREFIX.len());
            // Two trees, one per reader. Svelte keeps acorn's `preserveParens` here (and,
            // unlike every other template expression, skips `remove_parens`), so the WIRE
            // holds a `ParenthesizedExpression` for each grouping pair, a JSDoc cast's
            // included — `c = (2, 3)` keeps one. Everything else reads the head the way it
            // reads a function signature: paren-free, the parens re-derived from precedence — which is what makes a
            // snippet parameter list format (and compile) exactly as its `function` twin
            // does. Printing the wire tree would lose every pair: a
            // `ParenthesizedExpression` matches no precedence rule, so `(x + y) * 2`
            // prints as `x + y * 2`.
            //
            // The preserved parse is Svelte's own reader, so it alone decides acceptance.
            // It is also the only parse a head without a pair needs — the two trees are
            // then the same tree.
            let (preserved, preserved_a_paren) = tsv_ts::__private::parse_embedded_preserve_parens(
                &wrapper,
                base,
                self.island_nesting(),
                self.arena,
            )?;
            // The wrapper is literally a `function` declaration, so the signature is
            // there by construction — stated as an error rather than an `if let` so a head
            // whose pieces went nowhere can never reach the printer as a silently empty
            // signature (the shape a raw-text fallback would produce).
            let signature_error =
                || self.error_expected_at("snippet signature", content_offset + head_start);
            let (program, func) = if preserved_a_paren {
                // Grouping parens change no production the grammar accepts, so a head the
                // preserved parse read reads paren-free too. If it does not, that is a
                // parser bug, and it surfaces as the paren-free parse's own error rather
                // than as a silent fallback to the wire tree (which prints a pair's
                // contents bare).
                let plain = tsv_ts::__private::parse_embedded(
                    &wrapper,
                    base,
                    self.island_nesting(),
                    self.arena,
                )?;
                // The same comments, though not the same claims on them: `owned_by_node`
                // binds a glued block to the node its token begins, and a pair's `(` begins
                // a node only in the preserved tree (`/* c */ (x + y)`). The wire reads no
                // claim, so the printer's tree supplies them all.
                debug_assert!(
                    plain.comments.len() == preserved.comments.len()
                        && plain
                            .comments
                            .iter()
                            .zip(preserved.comments)
                            .all(|(a, b)| a.span == b.span),
                    "a snippet head's paren-free and preserved parses collected different comments"
                );
                let wire = snippet_signature(&preserved)
                    .ok_or_else(signature_error)?
                    .params;
                let func = snippet_signature(&plain).ok_or_else(signature_error)?;
                self.snippet_wire_parameters.push(SnippetWireParameters {
                    snippet_start: start as u32,
                    parameters: wire,
                });
                (plain, func)
            } else {
                let func = snippet_signature(&preserved).ok_or_else(signature_error)?;
                (preserved, func)
            };
            // The comments (and their `owned_by_node` claims) are the paren-free tree's —
            // the tree the printer walks — and are merged once.
            self.expression_comments.extend_from_slice(program.comments);
            type_parameters.clone_from(&func.type_parameters);
            parameters = func.params;
        }

        // Parse body
        let body = self.parse_block_children(&["snippet"], content_start)?;

        // Expect closing {/snippet}
        let end = self.expect_block_close_keyword("snippet", start)?;

        Ok(FragmentNode::SnippetBlock(SnippetBlock {
            expression,
            type_parameters,
            type_params_raw,
            parameters,
            params_paren,
            body,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
            opening_tag_span,
        }))
    }

    /// Find the matching closing angle bracket for generics like `<T>` (the byte
    /// offset of the `>`). Used for TypeScript generics in snippet declarations.
    /// Comment- and string-aware via the shared cursor.
    ///
    /// Deliberately a naive `<`/`>` depth count, mirroring Svelte's own snippet-generic
    /// scanner (`match_bracket` with `pointy_bois`): a `>` from a `=>` / `>=` / `>>`
    /// decrements depth and closes the generic early. `parse_snippet_block` then requires
    /// a `(` immediately after, so such a head (a function type — `<T extends () => void>`,
    /// `<T = () => void>` — or any stray `>`) is rejected exactly as Svelte rejects it,
    /// rather than mis-sliced and corrupted on format.
    ///
    /// `content_offset` is `content`'s position in the document: an unmatched `<` is
    /// reported as the missing `>` at `content`'s end, in the document's coordinates. The
    /// head is bounded by its `}` before this scan runs, so an unclosed generic runs out of
    /// HEAD, not out of document — the unclosed parameter `(` reads the same way
    /// (`Expected ')'`). Svelte's own scanner is not bounded by the head and walks to the
    /// end of the template; the message is tsv's own either way.
    fn find_matching_angle_bracket(
        &self,
        content: &str,
        content_offset: usize,
        open_pos: usize,
    ) -> Result<usize, Error> {
        match_bracket(
            content.as_bytes(),
            open_pos,
            content.len(),
            b'<',
            b'>',
            TriviaProfile::JS,
        )
        .ok_or_else(|| self.error_expected_at("'>'", content_offset + content.len()))
    }

    /// Scan source from a position until we find the closing } of a block tag
    /// Returns (content between start and }, position after })
    pub(super) fn scan_block_tag_content(
        &mut self,
        start: usize,
    ) -> Result<(&'a str, usize), Error> {
        // Find the block tag's closing `}` (skips strings/comments/regex). `start`
        // is just after the `{#`/`{:`/`{@`/`{/` marker (or a declaration tag's `{`), so the
        // opening `{` is the depth-1 brace the scan matches; the scan itself starts past
        // the head's keyword, which is no operand (`scan_head_to_matching_brace`).
        let Some(end) = scan_head_to_matching_brace(self.source.as_bytes(), start) else {
            return Err(self.error_unclosed_at("block tag", start));
        };

        let content = &self.source[start..end];

        // Reposition the lexer past `}`. Block tags only occur in template content,
        // so `inside_tag` is already `false` (template mode) and stays that way for
        // the block body, which `advance_to_position` preserves.
        let after_close = end + 1; // Skip past the }
        self.advance_to_position(after_close)?;

        Ok((content, after_close))
    }

    /// Parse children of a block until we hit a closing or intermediate tag
    /// stop_keywords: keywords that should stop parsing (e.g., ["else", "if"] for if blocks)
    /// content_start: position to start capturing text from (position after opening tag's `}`)
    fn parse_block_children(
        &mut self,
        stop_keywords: &[&str],
        content_start: usize,
    ) -> Result<Fragment<'arena>, Error> {
        let mut nodes = self.bvec();
        let mut last_end = content_start;

        loop {
            // Capture text gaps
            self.capture_text_if_gap(last_end, &mut nodes)?;

            if self.check(TokenKind::Eof) {
                break;
            }

            // Check for block close {/keyword}
            if self.check(TokenKind::BlockClose)
                && stop_keywords.contains(&self.keyword_at(self.current_end()))
            {
                break;
            }

            // Check for block continue {:keyword}
            if self.check(TokenKind::BlockContinue) {
                let keyword = self.continuation_keyword_at(self.current_end());

                // Stop when the continuation keyword begins with a stop keyword,
                // so the two-word `{:else if}` matches the `else` stop.
                let should_stop = stop_keywords.iter().any(|sk| keyword.starts_with(sk));

                if should_stop {
                    break;
                }
            }

            // Parse child nodes
            if self.check(TokenKind::Comment) {
                let comment = self.parse_comment()?;
                last_end = comment.span.end_usize();
                nodes.push(FragmentNode::Comment(comment));
            } else if self.check(TokenKind::LeftAngle) {
                // Check if closing tag
                if self.is_next_token(TokenKind::Slash)? {
                    break;
                }
                match self.parse_element_or_special(ElementParent::Nested)? {
                    ParsedElement::Element(elem) => {
                        last_end = elem.span.end_usize();
                        nodes.push(FragmentNode::Element(elem));
                    }
                    ParsedElement::SpecialElement(elem) => {
                        last_end = elem.span.end_usize();
                        nodes.push(FragmentNode::SpecialElement(elem));
                    }
                }
            } else if self.check(TokenKind::LeftBrace) {
                let tag = self.parse_brace_tag()?;
                last_end = tag.span().end_usize();
                nodes.push(tag);
            } else if self.check(TokenKind::BlockOpen) {
                let block = self.parse_block()?;
                last_end = block.span().end_usize();
                nodes.push(block);
            } else if self.check(TokenKind::TagOpen) {
                let tag = self.parse_template_tag()?;
                last_end = tag.span().end_usize();
                nodes.push(tag);
            } else {
                // Unknown token - might be text content that wasn't captured
                break;
            }
        }

        Ok(Fragment {
            nodes: nodes.into_bump_slice(),
        })
    }
}

/// The `)` that closes a `{#snippet}` parameter list opened by the `(` at `open`, read the
/// way Svelte reads it (`1-parse/state/tag.js`): a raw count of every `(` and `)` byte from
/// the `(` on, whatever string, comment, template or regex literal holds it.
///
/// Deliberately naive, like the generic scan beside it (`find_matching_angle_bracket`),
/// because Svelte then parses exactly the slice its count found: a scan that read the
/// parameters as an expression would close `(a = /[)]/.test(s))` at its real `)` and accept
/// a head Svelte rejects, and a pattern scan blind to regex literals reads the quote in
/// `(a = /'/.test(s))` as a string's and rejects a head Svelte accepts. Counting the bytes
/// Svelte counts agrees with it on both.
///
/// Out of line (`inline(never)`): a snippet head is rare, and inlined into the block
/// parser this loop measurably moved the whole parse phase's layout.
#[inline(never)]
fn snippet_params_close(bytes: &[u8], open: usize) -> Option<usize> {
    let mut depth = 0_u32;
    for (i, &b) in bytes.iter().enumerate().skip(open) {
        match b {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{EachHeadSplit, each_binding_separator, is_svelte_ws, strip_head_keyword};
    use bumpalo::Bump;

    /// A mid-head separator is its keyword wearing a whitespace RUN of any width, in
    /// canonical's own [`is_svelte_ws`](super::is_svelte_ws) class — not the single ASCII
    /// spaces the canonical printed form happens to use. A newline is what tsv's own
    /// wrapped `{#each}` head emits (`items as A[]⏎as item}`), so a narrower match made
    /// the formatter's output unparseable by its own parser; the non-ASCII members are
    /// reachable only from authored source, and no fixture can carry them legibly.
    ///
    /// Leading whitespace is OPTIONAL (canonical's `allow_whitespace`) and trailing is
    /// REQUIRED (`require_whitespace`), which is what keeps `as/* c */x` and a head-final
    /// `as` out — the latter having been an out-of-bounds panic while the keyword's width
    /// was assumed rather than measured. All three keywords take the one rule, so
    /// `{#await … then v}` cannot drift from `{#each … as x}` the way they had.
    #[test]
    fn head_separator_takes_a_whitespace_run_of_any_width() {
        for kw in ["as", "then", "catch"] {
            for ws in [
                " ", "  ", "\t", "\n", "\r\n", "\u{a0}", "\u{2028}", "\u{feff}",
            ] {
                let rest = format!("{ws}{kw}{ws}v");
                assert_eq!(strip_head_keyword(&rest, kw), Some("v"), "{rest:?}");
                assert_eq!(
                    strip_head_keyword(&rest[ws.len()..], kw),
                    Some("v"),
                    "{rest:?}"
                );
            }
            // No keyword, no trailing run, or the keyword glued to its value.
            for rest in [
                String::new(),
                format!(" {kw}"),
                kw.to_string(),
                format!(" {kw}v"),
                format!(" {kw}/* c */v"),
                format!(" {kw}}}"),
            ] {
                assert_eq!(strip_head_keyword(&rest, kw), None, "{rest:?}");
            }
            // A separator followed by NOTHING is still a separator — canonical's
            // `require_whitespace` is satisfied and it is the pattern reader that then
            // reports the missing binding, so the empty value is the caller's error.
            assert_eq!(strip_head_keyword(&format!(" {kw} "), kw), Some(""));
        }
        assert_eq!(strip_head_keyword(" a s item", "as"), None);
    }

    /// The run's LAST keyword is what splits `items as A[] as item` into an assertion plus
    /// a binding, and only when that keyword is `as`. The reported binding offset is exact
    /// — the caller slices with it — and everything between the two offsets is the
    /// separator itself.
    ///
    /// The chain is walked with the type grammar rather than by counting brackets, so the
    /// cases worth listing are the ones a byte scan cannot state as a rule: an arrow
    /// inside a type argument (whose `>` closes nothing), a `satisfies` link the chain has
    /// to step over, a mapped type carrying its own `as`, and a pattern-only binding that
    /// is no type at all.
    #[test]
    fn each_binding_separator_reports_the_binding_offset() {
        let arena = Bump::new();
        for (input, binding) in [
            ("A[] as item", "item"),
            ("A[]\tas\nitem", "item"),
            ("A[]  as   item", "item"),
            ("A as B[] as item", "item"),
            ("A[] as { a, b }", "{ a, b }"),
            ("A[] as item, i (key)", "item, i (key)"),
            // The `>` of an arrow return type closes no bracket — a signed depth counter
            // went NEGATIVE here, so every later ` as ` failed the scan's `depth == 0`
            // test and the whole head was rejected.
            ("A<() => string> as item", "item"),
            ("(() => string)[] as item", "item"),
            ("A<{ a: () => string }> as item", "item"),
            ("unknown as A<() => string> as item", "item"),
            // `satisfies` is a link in the chain, never a separator: the walk steps over
            // it and keeps looking for an `as`. Stopping at it instead handed the tail to
            // the binding parser, rejecting heads canonical accepts. An `as` AFTER the
            // link is still the run's last keyword, so it still separates.
            ("A satisfies B as item", "item"),
            ("A[] satisfies B[] as item, i", "item, i"),
            ("A satisfies B satisfies C as item", "item"),
            // A mapped type spells `as` INSIDE a bracket run. A depth scan survives it
            // only because brackets nest it; the type grammar knows it outright — and the
            // two disagree as soon as an arrow has already broken the depth count.
            ("{ [K in T as U]: V } as item", "item"),
            ("{ [K in keyof A as string]: () => string } as item", "item"),
            // The gap before the separator may hold comments, which canonical accepts and
            // the caller keeps inside its expression slice.
            ("A[] /* c */ as item", "item"),
            // A type's own end is the token anchor, so no whitespace is required before
            // the keyword — canonical accepts this and the old leading-run anchor did not.
            ("A[]as item", "item"),
            // The binding need not be a type; the walk stops at the last one that is.
            ("A[] as { a = 1 }", "{ a = 1 }"),
            ("A[] as [a = 1]", "[a = 1]"),
        ] {
            let EachHeadSplit::LaterAs {
                separator,
                binding: start,
            } = each_binding_separator(input, 0, 0, &arena)
            else {
                panic!("expected a later `as` in {input:?}");
            };
            assert_eq!(&input[start..], binding, "{input:?}");
            // Between the two offsets lies the keyword and the whitespace after it — the
            // caller trims both off its expression slice.
            assert_eq!(
                input[separator..start].trim_matches(is_svelte_ws),
                "as",
                "{input:?}"
            );
        }

        // No SECOND `as`: the head's first one was already the separator. A binding that
        // is no type at all takes this arm too — a destructuring default is a pattern,
        // and an arrow inside one would drop a bracket-depth scan to a false zero and
        // split the head at the `as` buried in it. So does a run that consumed a
        // `satisfies` link and THEN reached a pattern: the item is still the binding.
        for input in [
            "item",
            "{ a } as", // head-final: not a separator, and never sliced past the end
            "Array<A as B>",
            "item /* as x */",
            "item // as x",
            "item['as x']",
            "Aas x",
            "{ a = 1 }",
            "{ a = (x) => x as T }",
            "[a = 1]",
            "A satisfies { a = 1 }",
        ] {
            assert_eq!(
                each_binding_separator(input, 0, 0, &arena),
                EachHeadSplit::FirstAs,
                "{input:?}"
            );
        }

        // A run ENDING on `satisfies` has no separator at all — canonical strips only the
        // outermost assertion and only when it is an `as`, so the whole run is the
        // iterable and the head is binding-less. The reported end is the run's last TYPE,
        // not the end of the text: what follows is the head's own `, index` / `(key)`.
        for (input, run) in [
            ("A satisfies B", "A satisfies B"),
            ("A satisfies item", "A satisfies item"),
            // A `satisfies` cancels an `as` before it, however binding-shaped the type it
            // cancels looks. Keeping the last `as` instead split these heads and rejected
            // them.
            ("A[] as item satisfies B", "A[] as item satisfies B"),
            ("A as B satisfies C", "A as B satisfies C"),
            ("A[] satisfies B[], i", "A[] satisfies B[]"),
            ("A satisfies B, i (i)", "A satisfies B"),
        ] {
            assert_eq!(
                each_binding_separator(input, 0, 0, &arena),
                EachHeadSplit::NoBinding { run_end: run.len() },
                "{input:?}"
            );
            assert_eq!(&input[..run.len()], run, "{input:?}");
        }
    }
}