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
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
// Svelte AST module
//
// - convert: emits the public JSON-compatible wire format (matches Svelte
//   parser output) directly from this AST via the writer

#[cfg(feature = "json")]
pub(crate) mod convert;

// Svelte internal AST types
//
// Internal representation optimized for manipulation and formatting.
// Element/attribute names are span-identity — recovered from `source[name_span]`
// on demand, never stored (see `Element::name` / `Attribute::name`).
//
// ## Arena allocation
//
// Like `tsv_ts`, the Svelte AST is allocated in a per-parse [`bumpalo::Bump`]
// supplied by the caller. Recursive children are `&'arena T<'arena>` (not
// `Box`), child collections are `&'arena [T<'arena>]` (not `Vec`), and decoded /
// raw strings are `&'arena str` (not `String`) — so a whole parse (template plus
// the embedded TS `<script>`/`{expr}` and CSS `<style>` ASTs, which share the
// same `Bump`) is one bump-allocated graph, freed wholesale when the `Bump`
// drops. `Style` holds a `CssStyleSheet<'arena>` borrowing that shared arena.
// Leaf nodes that hold only `Span`/primitives carry no lifetime
// (`HtmlComment`, `Text`, `SvelteOptions`, the `*Tag`-with-no-expression nodes).

use std::borrow::Cow;

use tsv_css::ast::CssStyleSheet;
pub use tsv_lang::{Comment, Span};
use tsv_ts::ast::{Expression, Program, TSTypeParameterDeclaration, VariableDeclaration};

/// Svelte Root - top-level AST node
///
/// Represents a complete Svelte component with template, scripts, and styles.
/// Contains optional instance script, module script, and style sections.
#[derive(Debug, Clone)]
pub struct Root<'arena> {
    pub fragment: Fragment<'arena>,
    pub instance: Option<&'arena Script<'arena>>,
    pub module: Option<&'arena Script<'arena>>,
    pub css: Option<&'arena Style<'arena>>,
    /// `<svelte:options>` configuration (not part of fragment)
    pub options: Option<SvelteOptions<'arena>>,
    /// All comments from scripts and template expressions.
    /// Use `comments_to_emit_in_range(span)` to find comments for a specific node.
    pub comments: Vec<Comment>,
    /// The wire's parameter lists for the `{#snippet}` heads that hold a grouping pair,
    /// ascending by [`SnippetWireParameters::snippet_start`] — see
    /// [`SnippetWireParameters`].
    pub snippet_wire_parameters: &'arena [SnippetWireParameters<'arena>],
    /// Whether the parser read a `<script>` / `<style>` nested in the markup — a raw-text
    /// element anywhere in `fragment`, as opposed to the lifted top-level `instance` /
    /// `module` / `css`. Recorded where the parser already knows it, so the printer can skip
    /// analysis only such an element needs without walking the tree to ask. Not on the wire.
    pub(crate) holds_nested_raw_text: bool,
    /// The nesting the printer's own parse of a nested `<script>` / `<style>` body starts
    /// from: the deepest such element's markup nesting plus the island levels, so that
    /// parse is held to the same document-wide depth budget as every island the parser
    /// read (`tsv_lang::DepthBudget`). The parser leaves those bodies as raw text.
    pub(crate) nested_raw_text_nesting: u32,
}

/// A `{#snippet}` head's parameters as Svelte's parse shapes them: acorn's
/// `preserveParens`, so each grouping pair is a `ParenthesizedExpression`. Read by the wire
/// writer alone — every other consumer reads [`SnippetBlock::parameters`], the paren-free
/// tree of the same text.
///
/// Recorded only for a head that holds a pair; for every other head the two trees are one,
/// and the writer emits [`SnippetBlock::parameters`]. A side table on [`Root`] rather than a
/// field on the block because `SnippetBlock` sets `FragmentNode`'s width, which every
/// template node pays, for a list no printer reads.
#[derive(Debug, Clone, Copy)]
pub struct SnippetWireParameters<'arena> {
    /// The snippet block's `span.start` — the key the writer finds the list by.
    pub snippet_start: u32,
    pub parameters: &'arena [Expression<'arena>],
}

/// Svelte Fragment - container for template nodes
///
/// A fragment contains a sequence of template nodes (elements, text, expressions).
/// Used both at the root level and as children of elements.
#[derive(Debug, Clone)]
pub struct Fragment<'arena> {
    pub nodes: &'arena [FragmentNode<'arena>],
}

/// Svelte template node types
///
/// Represents the different kinds of nodes that can appear in a Svelte template.
///
/// All variants are inline by value: the layout favors traversal locality over
/// node size (boxing the fat variants added a pointer-chase on hot format-read
/// paths that cost more than the slice-density win).
#[derive(Debug, Clone)]
pub enum FragmentNode<'arena> {
    Element(Element<'arena>),
    SpecialElement(SpecialElement<'arena>),
    ExpressionTag(ExpressionTag<'arena>),
    Text(Text),
    Comment(HtmlComment),
    IfBlock(IfBlock<'arena>),
    EachBlock(EachBlock<'arena>),
    AwaitBlock(AwaitBlock<'arena>),
    KeyBlock(KeyBlock<'arena>),
    SnippetBlock(SnippetBlock<'arena>),
    HtmlTag(HtmlTag<'arena>),
    ConstTag(ConstTag<'arena>),
    DeclarationTag(DeclarationTag<'arena>),
    DebugTag(DebugTag<'arena>),
    RenderTag(RenderTag<'arena>),
}

/// HTML comment node: <!-- content -->
///
/// Represents an HTML comment in the template. `content_span` is the span of the
/// raw content between `<!--` and `-->` (whitespace preserved exactly) in the host
/// source; recover the text via `HtmlComment::content`. A pure sub-slice — no
/// decode — so it is a `Span`, not an owned `String` (mirrors
/// `tsv_lang::Comment::content_span`).
///
/// Note: `content` mirrors `tsv_lang::Comment` and `CssComment` for naming
/// consistency. The public AST uses `data` (Svelte's naming) via conversion.
#[derive(Debug, Clone)]
pub struct HtmlComment {
    /// Span of the content between `<!--` and `-->` in the host source; text via `content`.
    pub content_span: Span,
    pub span: Span,
}

impl HtmlComment {
    /// Content between `<!--` and `-->` — a sub-slice of `source`, no allocation.
    /// `source` must be the host document the spans were recorded against.
    pub fn content<'s>(&self, source: &'s str) -> &'s str {
        self.content_span.extract(source)
    }
}

/// Svelte IfBlock - conditional rendering
///
/// Represents {#if test}...{:else if test}...{:else}...{/if} blocks.
/// The `elseif` field is true for {:else if} branches (nested in alternate).
#[derive(Debug, Clone)]
pub struct IfBlock<'arena> {
    pub elseif: bool,
    pub test: &'arena Expression<'arena>,
    pub consequent: Fragment<'arena>,
    pub alternate: Option<Fragment<'arena>>,
    pub span: Span,
    /// Span of the opening tag `{#if ... }` or `{:else if ... }` for comment lookup
    pub opening_tag_span: Span,
}

/// Svelte EachBlock - list iteration
///
/// Represents {#each expression as context, index (key)}...{:else}...{/each} blocks.
/// Also supports {#each expression} and {#each expression, index} without `as`.
#[derive(Debug, Clone)]
pub struct EachBlock<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub context: Option<&'arena Expression<'arena>>, // Pattern (identifier or destructuring), None if no `as`
    pub index: Option<&'arena str>,
    pub key: Option<EachKey<'arena>>,
    pub body: Fragment<'arena>,
    pub fallback: Option<Fragment<'arena>>,
    pub span: Span,
    /// Span of the opening tag `{#each ... }` for comment lookup
    pub opening_tag_span: Span,
}

/// An `{#each}` key (`{#each … (key)}`) together with the span of the parentheses
/// that hold it.
///
/// One field rather than two `Option`s that must covary: every reader needs the
/// parens to locate the expression (the printer's embed offsets, the wire writer's
/// comment-attach window), and a reader that could hold the expression without
/// them had to invent a fallback for a state the parser never produces — three of
/// them did, and one silently widened its comment window back over the binding
/// pattern.
#[derive(Debug, Clone)]
pub struct EachKey<'arena> {
    pub expression: &'arena Expression<'arena>,
    /// Span of the key INCLUDING its parentheses — `(` through past `)`.
    pub span: Span,
}

/// Svelte AwaitBlock - promise handling
///
/// Represents {#await expression}...{:then value}...{:catch error}...{/await} blocks.
/// Also supports shorthand: {#await expression then value}...{/await}
#[derive(Debug, Clone)]
pub struct AwaitBlock<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub value: Option<&'arena Expression<'arena>>, // Pattern for :then binding
    pub error: Option<&'arena Expression<'arena>>, // Pattern for :catch binding
    /// The pending-phase **content** (`{#await x}<here>{:then}…`), or `None` when
    /// empty. Distinct from `pending_block`: an empty block-form pending is `None`
    /// here but `pending_block == true`. The printer reads this (an empty pending
    /// full form collapses to the `then`/`catch` shorthand, matching prettier).
    pub pending: Option<Fragment<'arena>>,
    /// Whether the block form was used (`{#await x}…{/await}`) vs the inline
    /// `then`/`catch` shorthand (`{#await x then v}` / `{#await x catch e}`). The
    /// block form always has a pending Fragment — empty or not — matching Svelte's
    /// `block.pending = create_fragment()`; the shorthand has `pending: null`. The
    /// writer emits `{Fragment, nodes: []}` vs `null` from this flag (the wire
    /// distinction the formatter's shorthand-collapse erases). See
    /// `ast/convert/write.rs::write_await_block`.
    pub pending_block: bool,
    pub then: Option<Fragment<'arena>>,
    pub catch: Option<Fragment<'arena>>,
    pub span: Span,
    /// Span of the opening tag `{#await ... }` for comment lookup
    pub opening_tag_span: Span,
}

/// Svelte KeyBlock - keyed updates
///
/// Represents {#key expression}...{/key} blocks.
/// Forces re-creation of contents when expression changes.
#[derive(Debug, Clone)]
pub struct KeyBlock<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub fragment: Fragment<'arena>,
    pub span: Span,
    /// Span of the opening tag `{#key ... }` for comment lookup
    pub opening_tag_span: Span,
}

/// Svelte SnippetBlock - reusable template snippets
///
/// Represents {#snippet name(params)}...{/snippet} blocks.
/// Defines a reusable chunk of markup that can be rendered with {@render}.
#[derive(Debug, Clone)]
pub struct SnippetBlock<'arena> {
    pub expression: &'arena Expression<'arena>, // Snippet name (Identifier)
    /// Parsed generic type parameters (`<T extends X = Y>`), routed through
    /// `tsv_ts`'s type-parameter printer for constraint/default/modifier
    /// handling and width-based wrapping. `Some` whenever `type_params_raw` is
    /// — a signature the parser cannot read is a parse error, not a node.
    pub type_parameters: Option<TSTypeParameterDeclaration<'arena>>,
    /// Raw inner text of the generics (`T extends X` for `<T extends X>`),
    /// always set when generics are present. Feeds the public AST's `typeParams`
    /// string, matching Svelte's parser (which stores it raw too).
    pub type_params_raw: Option<&'arena str>,
    /// Function parameters (patterns), **paren-free**: the tree a `function` signature
    /// with the same text parses to, so the printer and the compiler read the head exactly
    /// as they read that signature, re-deriving every grouping pair from precedence. The
    /// wire's own shape of a head that holds a pair is [`Root::snippet_wire_parameters`].
    pub parameters: &'arena [Expression<'arena>],
    /// Source span of the parameter parens: `start` is the `(`, `end` is the `)`
    /// (for leading / dangling / trailing comment lookup when printing parameters).
    /// `None` only if no `(` was found (malformed).
    pub params_paren: Option<Span>,
    pub body: Fragment<'arena>,
    pub span: Span,
    /// Span of the opening tag `{#snippet ... }` for comment lookup
    pub opening_tag_span: Span,
}

/// Svelte HtmlTag - raw HTML injection
///
/// Represents {@html expression} tags.
/// Injects raw HTML content without escaping.
#[derive(Debug, Clone)]
pub struct HtmlTag<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub span: Span,
}

/// Svelte ConstTag - local constant declaration
///
/// Represents {@const name = expression} tags.
/// Declares a local constant within a block scope.
/// The `id` is the pattern (identifier or destructuring) and `init` is the value.
#[derive(Debug, Clone)]
pub struct ConstTag<'arena> {
    pub id: &'arena Expression<'arena>, // Pattern (identifier or destructuring)
    pub init: &'arena Expression<'arena>, // Initializer expression
    pub span: Span,
}

/// Svelte DeclarationTag - local `{const …}` / `{let …}` declaration
///
/// The bare `{const name = expr}` / `{let name = expr}` tags (no `@`). The body is
/// a TS `VariableDeclaration` parsed, printed, and converted by `tsv_ts`, so
/// multiple declarators, comments, and every bracket/string case are handled
/// natively. (`{@const}` is a separate `ConstTag` on its own path.)
#[derive(Debug, Clone)]
pub struct DeclarationTag<'arena> {
    pub declaration: VariableDeclaration<'arena>,
    pub span: Span,
}

/// Svelte DebugTag - debugging helper
///
/// Represents {@debug} or {@debug x, y, z} tags.
/// Triggers debugger when any listed variable changes.
/// Empty identifiers array means "debug all state".
///
/// Note: Unlike Prettier (which strips comments), we preserve TS comments
/// within debug tags. Comments are stored in `Root.comments` and looked
/// up by span during formatting. This is an intentional divergence.
#[derive(Debug, Clone)]
pub struct DebugTag<'arena> {
    pub identifiers: &'arena [Expression<'arena>], // List of identifiers to debug
    pub span: Span,
}

/// Svelte RenderTag - snippet rendering
///
/// Represents {@render fn()} or {@render fn?.()} tags.
/// Renders a snippet, optionally with arguments.
#[derive(Debug, Clone)]
pub struct RenderTag<'arena> {
    pub expression: &'arena Expression<'arena>, // CallExpression or ChainExpression
    pub span: Span,
}

/// Svelte AttachTag - element attachment
///
/// Represents {@attach expr} inside element opening tags.
/// Attaches reactive functions to elements (Svelte 5.29+).
#[derive(Debug, Clone)]
pub struct AttachTag<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub span: Span,
}

//
// Directives
//

/// OnDirective - event handler (`on:click={handler}`)
///
/// Event handlers can have modifiers like `preventDefault`, `stopPropagation`, etc.
/// When no expression is provided (rare), expression is null.
#[derive(Debug, Clone)]
pub struct OnDirective<'arena> {
    /// Span of the directive name only (e.g. "click"). A **verbatim** source slice —
    /// HTML/Svelte attribute names are never entity-decoded — recovered via
    /// `name_span.extract(source)`. Distinct from `head_span` below, which is the whole
    /// directive head token ("on:click|preventDefault", prefix + name + modifiers).
    pub name_span: Span,
    pub expression: Option<&'arena Expression<'arena>>, // Handler function
    pub modifiers: &'arena [&'arena str],               // "preventDefault", "stopPropagation", etc.
    pub span: Span,
    /// Span of the whole directive head (`on:click|preventDefault`); used as `name_loc`.
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None if no expression)
    pub expression_tag_span: Option<Span>,
}

/// BindDirective - two-way binding (`bind:value={name}`)
///
/// Bindings connect a property to a variable. When shorthand (`bind:value`),
/// an identifier with the same name is auto-generated as the expression.
#[derive(Debug, Clone)]
pub struct BindDirective<'arena> {
    /// Span of the property name only (e.g. "value") — verbatim source slice (see `OnDirective`).
    pub name_span: Span,
    pub expression: &'arena Expression<'arena>, // Binding target (always present - auto-generated for shorthand)
    pub modifiers: &'arena [&'arena str], // Unofficial — no official modifier support; preserved verbatim
    pub span: Span,
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None for shorthand bindings)
    pub expression_tag_span: Option<Span>,
}

/// ClassDirective - conditional class (`class:class1={cond}`)
///
/// Applies a class conditionally based on an expression.
/// When shorthand (`class:class1`), an identifier with the same name is auto-generated.
#[derive(Debug, Clone)]
pub struct ClassDirective<'arena> {
    /// Span of the class name only (e.g. "class1") — verbatim source slice (see `OnDirective`).
    pub name_span: Span,
    pub expression: &'arena Expression<'arena>, // Condition (always present - auto-generated for shorthand)
    pub modifiers: &'arena [&'arena str], // Unofficial — no official modifier support; preserved verbatim
    pub span: Span,
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None for shorthand)
    pub expression_tag_span: Option<Span>,
}

/// StyleDirective - inline style (`style:color={value}`)
///
/// Sets a CSS property value. Unlike other directives, uses `value` instead of `expression`
/// because it can be a string value, not just an expression.
/// When shorthand (`style:color`), value is `true` (boolean).
#[derive(Debug, Clone)]
pub struct StyleDirective<'arena> {
    /// Span of the CSS property name only (e.g. "color") — verbatim source slice (see
    /// `OnDirective`).
    pub name_span: Span,
    pub value: StyleDirectiveValue<'arena>, // true, ExpressionTag, or mixed text/expressions
    pub modifiers: &'arena [&'arena str],   // "important"
    pub span: Span,
    pub head_span: Span,
}

/// Value of a style directive
#[derive(Debug, Clone)]
pub enum StyleDirectiveValue<'arena> {
    /// Shorthand: `style:color` (uses variable with same name)
    True,
    /// Pure expression: `style:color={value}`
    ExpressionTag(ExpressionTag<'arena>),
    /// Mixed value (string with possible expressions): `style:color="red"`
    Parts(&'arena [AttributeValue<'arena>]),
}

/// UseDirective - action (`use:action={params}`)
///
/// Actions are functions that run when an element is mounted.
#[derive(Debug, Clone)]
pub struct UseDirective<'arena> {
    /// Span of the action name only (e.g. "action") — verbatim source slice (see `OnDirective`).
    pub name_span: Span,
    pub expression: Option<&'arena Expression<'arena>>, // Parameters passed to the action
    pub modifiers: &'arena [&'arena str], // Unofficial — no official modifier support; preserved verbatim
    pub span: Span,
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None if no expression)
    pub expression_tag_span: Option<Span>,
}

/// Direction of a transition directive
///
/// Encodes the three valid states instead of two booleans:
/// - `Both`: bidirectional transition (`transition:fade`)
/// - `In`: intro only (`in:fly`)
/// - `Out`: outro only (`out:slide`)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransitionDirection {
    /// Bidirectional: `transition:name` - runs on both enter and exit
    Both,
    /// Intro only: `in:name` - runs only on enter
    In,
    /// Outro only: `out:name` - runs only on exit
    Out,
}

impl TransitionDirection {
    /// Returns the directive prefix for this direction
    pub const fn prefix(self) -> &'static str {
        match self {
            Self::Both => "transition",
            Self::In => "in",
            Self::Out => "out",
        }
    }

    /// Returns the directive prefix with colon (e.g., "transition:")
    pub const fn prefix_with_colon(self) -> &'static str {
        match self {
            Self::Both => "transition:",
            Self::In => "in:",
            Self::Out => "out:",
        }
    }

    /// Returns true if this includes intro (enter) animation
    pub const fn has_intro(self) -> bool {
        matches!(self, Self::Both | Self::In)
    }

    /// Returns true if this includes outro (exit) animation
    pub const fn has_outro(self) -> bool {
        matches!(self, Self::Both | Self::Out)
    }
}

/// TransitionDirective - transition (`transition:fade`, `in:fly`, `out:slide`)
///
/// Controls enter/exit animations. Can be bidirectional (transition:) or unidirectional (in:/out:).
#[derive(Debug, Clone)]
pub struct TransitionDirective<'arena> {
    /// Span of the transition name only (e.g. "fade") — verbatim source slice (see `OnDirective`).
    pub name_span: Span,
    pub expression: Option<&'arena Expression<'arena>>, // Transition parameters
    pub modifiers: &'arena [&'arena str],               // "local", "global"
    pub direction: TransitionDirection,                 // Which animations to run
    pub span: Span,
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None if no expression)
    pub expression_tag_span: Option<Span>,
}

/// AnimateDirective - animation (`animate:flip={params}`)
///
/// FLIP animations for list items.
#[derive(Debug, Clone)]
pub struct AnimateDirective<'arena> {
    /// Span of the animation name only (e.g. "flip") — verbatim source slice (see `OnDirective`).
    pub name_span: Span,
    pub expression: Option<&'arena Expression<'arena>>, // Animation parameters
    pub modifiers: &'arena [&'arena str], // Unofficial — no official modifier support; preserved verbatim
    pub span: Span,
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None if no expression)
    pub expression_tag_span: Option<Span>,
}

/// LetDirective - slot prop (`let:item={localItem}`)
///
/// Receives values from a slot. The expression is the local binding pattern.
#[derive(Debug, Clone)]
pub struct LetDirective<'arena> {
    /// Span of the slot-prop name only (e.g. "item") — verbatim source slice (see `OnDirective`).
    pub name_span: Span,
    pub expression: Option<&'arena Expression<'arena>>, // Local binding pattern (Identifier, ArrayPattern, ObjectPattern)
    pub modifiers: &'arena [&'arena str], // Unofficial — no official modifier support; preserved verbatim
    pub span: Span,
    pub head_span: Span,
    /// Span of the expression tag `{...}` for comment lookup (None if no expression)
    pub expression_tag_span: Option<Span>,
}

//
// Special Elements
//

/// Tag identifier for special elements (used during parsing before data is available)
///
/// This is a simple Copy enum used to identify the kind of special element
/// before we've parsed the `this` attribute. After parsing, use `SpecialElementKind`
/// which includes the associated data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecialElementTag {
    SvelteHead,
    SvelteWindow,
    SvelteBody,
    SvelteDocument,
    SvelteElement,
    SvelteComponent,
    SvelteSelf,
    SlotElement,
    SvelteFragment,
    SvelteBoundary,
    TitleElement,
}

impl SpecialElementTag {
    /// Try to parse a tag name into a special element tag.
    ///
    /// Two classifications are ancestor-context-dependent, so the caller supplies its parse
    /// state (mirroring Svelte's stack walks in `1-parse/state/element.js`):
    /// - `title` is `TitleElement` only inside `<svelte:head>` (`parent_is_head`).
    /// - `slot` is `SlotElement` only when *not* inside a `<template shadowrootmode>`
    ///   (`parent_is_shadowroot_template`); there it's an ordinary `RegularElement`, so this
    ///   returns `None` and the caller parses it on the regular-element path.
    pub fn from_tag_name(
        name: &str,
        in_svelte_head: bool,
        in_shadowroot_template: bool,
    ) -> Option<Self> {
        match name {
            "svelte:head" => Some(Self::SvelteHead),
            "svelte:window" => Some(Self::SvelteWindow),
            "svelte:body" => Some(Self::SvelteBody),
            "svelte:document" => Some(Self::SvelteDocument),
            "svelte:element" => Some(Self::SvelteElement),
            "svelte:component" => Some(Self::SvelteComponent),
            "svelte:self" => Some(Self::SvelteSelf),
            "slot" if !in_shadowroot_template => Some(Self::SlotElement),
            "svelte:fragment" => Some(Self::SvelteFragment),
            "svelte:boundary" => Some(Self::SvelteBoundary),
            "title" if in_svelte_head => Some(Self::TitleElement),
            _ => None,
        }
    }

    /// Whether `name` is one of the `svelte:*` meta tags — Svelte's `meta_tags.has(name)`
    /// (`1-parse/state/element.js`), the gate that makes the `svelte:` namespace reserved.
    ///
    /// Derived from [`Self::from_tag_name`] rather than a second hand-written list, so the two
    /// cannot drift. The caller gates on the `svelte:` prefix first, which makes the two
    /// context flags irrelevant here: neither `slot` nor `title` is namespaced. The one meta
    /// tag with no `SpecialElementTag` is `svelte:options` — it fills `Root`'s single `Option`
    /// slot instead of becoming a fragment node, so the root dispatch takes it before element
    /// parsing ever sees it.
    pub fn is_meta_tag_name(name: &str) -> bool {
        name == "svelte:options" || Self::from_tag_name(name, false, false).is_some()
    }

    /// Returns the tag name as it appears in source code
    #[inline]
    pub const fn tag_name(self) -> &'static str {
        match self {
            Self::SvelteHead => "svelte:head",
            Self::SvelteWindow => "svelte:window",
            Self::SvelteBody => "svelte:body",
            Self::SvelteDocument => "svelte:document",
            Self::SvelteElement => "svelte:element",
            Self::SvelteComponent => "svelte:component",
            Self::SvelteSelf => "svelte:self",
            Self::SlotElement => "slot",
            Self::SvelteFragment => "svelte:fragment",
            Self::SvelteBoundary => "svelte:boundary",
            Self::TitleElement => "title",
        }
    }

    /// Whether a `this` attribute on this tag binds the element rather than staying an
    /// ordinary attribute.
    ///
    /// Only these two consume one, and only the first — on every other special element (and
    /// on any later `this` here) the name has no meaning beyond being an attribute.
    #[inline]
    pub const fn takes_this(self) -> bool {
        matches!(self, Self::SvelteElement | Self::SvelteComponent)
    }
}

/// The `this=` binding of `<svelte:element>`, in the two forms Svelte lets it be spelled.
///
/// Svelte's public AST holds the expression bare (`SvelteElement.tag`) with no
/// `ExpressionTag` around it. Keeping the tag here instead of unwrapping to the expression
/// is what preserves the `{…}` span, and with it the `{`→expression and expression→`}`
/// gaps: a comment lives in either (`this={/* c */ tag}`), and an unwrapped expression
/// leaves nowhere to look for one.
///
/// `<svelte:component>` does **not** use this type: it accepts only the braced form (a
/// non-`{expression}` `this` is a parse error), so it carries an `ExpressionTag` directly.
/// The asymmetry is Svelte's — `<svelte:element this="div">` merely *warns*, deliberately
/// preserving Svelte 4 behavior, where the component errors.
#[derive(Debug, Clone)]
pub enum SpecialThis<'arena> {
    /// `this={expr}` — the expression form. The tag's span covers the braces, so the
    /// printer emits it as the `{…}` attribute value it is.
    Braced(ExpressionTag<'arena>),
    /// `this="value"` — the plain HTML-attribute form. No braces (so no gap a comment could
    /// occupy) and **no expression parse at all**: the value is the attribute's decoded
    /// text, held as such. Svelte's wire reports it as a `Literal`, which the writer emits
    /// from these two fields directly — synthesizing an `ExpressionKind::Literal` here only to
    /// take it apart again at every consumer bought nothing but an unreachable arm in each
    /// of their matches.
    Plain {
        /// Decoded attribute text (entities resolved, quotes stripped).
        content: &'arena str,
        /// Span of that text in source — no quotes, so `raw` is not recoverable from it.
        span: Span,
    },
}

impl<'arena> SpecialThis<'arena> {
    /// Span of the bound value: the braced form's expression, or the plain form's text.
    /// Both sit hard against whatever delimits them, so this is the region a comment can
    /// be adjacent to.
    pub fn span(&self) -> Span {
        match self {
            Self::Braced(tag) => tag.expression.span(),
            Self::Plain { span, .. } => *span,
        }
    }

    /// The `{…}` span of the braced form, braces included; `None` for the plain-string
    /// form, which has no braces and therefore no gap a comment could occupy.
    pub fn braces(&self) -> Option<Span> {
        match self {
            Self::Braced(tag) => Some(tag.span),
            Self::Plain { .. } => None,
        }
    }
}

/// Kind of Svelte special element
///
/// These are elements with special behavior in Svelte:
/// - Document injection: `<svelte:head>`, `<svelte:window>`, `<svelte:body>`, `<svelte:document>`
/// - Dynamic elements: `<svelte:element>`, `<svelte:component>`, `<svelte:self>`
/// - Content slots: `<slot>`, `<svelte:fragment>`
/// - Error handling: `<svelte:boundary>`
/// - Semantic HTML: `<title>` (inside svelte:head)
///
/// Variants that require additional data (SvelteElement, SvelteComponent) carry it
/// directly, eliminating the need for Option fields on the parent struct.
#[derive(Debug, Clone)]
pub enum SpecialElementKind<'arena> {
    /// `<svelte:head>` - inject content into document head
    SvelteHead,
    /// `<svelte:window>` - bind to window events/properties
    SvelteWindow,
    /// `<svelte:body>` - bind to body events
    SvelteBody,
    /// `<svelte:document>` - bind to document events
    SvelteDocument,
    /// `<svelte:element this={tag}>` - dynamic element tag
    SvelteElement { tag: SpecialThis<'arena> },
    /// `<svelte:component this={Component}>` - dynamic component (legacy). Always the
    /// braced form: a missing or non-`{expression}` `this` is rejected at parse, as Svelte
    /// does — so unlike `<svelte:element>` there is no plain-string variant to model.
    SvelteComponent { expression: ExpressionTag<'arena> },
    /// `<svelte:self>` - recursive self-reference
    SvelteSelf,
    /// `<slot>` - content slot
    SlotElement,
    /// `<svelte:fragment>` - wrapper for slot content
    SvelteFragment,
    /// `<svelte:boundary>` - error boundary (Svelte 5)
    SvelteBoundary,
    /// `<title>` - semantic title element (inside svelte:head)
    TitleElement,
}

impl<'arena> SpecialElementKind<'arena> {
    /// Whether this special element is a block-level element (forces line breaks).
    ///
    /// Block elements: `svelte:head`, `svelte:window`, `svelte:body`, `svelte:document`
    /// — these bind to global objects and don't participate in inline flow.
    ///
    /// Inline elements: `slot`, `svelte:element`, `svelte:component`, `svelte:self`,
    /// `svelte:fragment`, `svelte:boundary`, `title` — these render content inline.
    ///
    /// The set is exactly the [global](Self::is_global) kinds. Being block-classified is the
    /// printer's layout default for them, not a fact about the render: the compiler hoists them
    /// out of their fragment, so one glued to content on both sides lays out inline instead
    /// (`Printer::is_glued_global_element`).
    #[inline]
    pub const fn is_block(&self) -> bool {
        self.is_global()
    }

    /// Whether this is one of the four **global** elements — `svelte:head` / `svelte:window` /
    /// `svelte:body` / `svelte:document` — which bind to a global object, render nothing where
    /// they are written, and are root-only in Svelte (`svelte_meta_invalid_placement`).
    ///
    /// The compiler's `clean_nodes` **hoists** exactly these kinds out of their fragment before
    /// its whitespace rules run, alongside the tags [`FragmentNode::is_hoisted_from_fragment`]
    /// lists — see [`FragmentNode::is_compiler_hoisted`] for the full list.
    #[inline]
    pub const fn is_global(&self) -> bool {
        matches!(
            self,
            Self::SvelteHead | Self::SvelteWindow | Self::SvelteBody | Self::SvelteDocument
        )
    }

    /// Whether this kind's **content** prints verbatim — the whitespace-sensitive class, which
    /// for regular elements is `crate::html::preserves_whitespace` (`<pre>` / `<textarea>`).
    ///
    /// Exactly one special kind joins it. A `TitleElement` — `<title>` as a (transparent) child
    /// of `<svelte:head>` — is compiled by visitors that walk `fragment.nodes` **directly**
    /// (`$$renderer.title(…)` on the server, a `document.title` assignment on the client), so
    /// `clean_nodes` never runs over its children and every byte between the tags reaches the
    /// page. The two predicates together are the whole verbatim set, and every reader of "does
    /// the printer own this whitespace?" must consult both — the printer's dispatch and the
    /// audits that mirror it alike, since an audit excluding a different set than the printer
    /// emits either accuses the author's bytes or blinds itself to the printer's.
    ///
    /// ⚠️ This is about the element's **interior**. The `clean_nodes` **hoist** is a separate
    /// fact that still applies to a `TitleElement`: it is lifted out of its parent fragment, so
    /// the run between it and a *sibling* is a fragment edge and is deleted.
    ///
    /// Readers walking the public wire AST ask the same question of a node's `"TitleElement"`
    /// type string, there being no kind enum on that side.
    #[inline]
    pub const fn preserves_content_whitespace(&self) -> bool {
        matches!(self, Self::TitleElement)
    }

    /// Returns the tag name as it appears in source code
    #[inline]
    pub const fn tag_name(&self) -> &'static str {
        match self {
            Self::SvelteHead => "svelte:head",
            Self::SvelteWindow => "svelte:window",
            Self::SvelteBody => "svelte:body",
            Self::SvelteDocument => "svelte:document",
            Self::SvelteElement { .. } => "svelte:element",
            Self::SvelteComponent { .. } => "svelte:component",
            Self::SvelteSelf => "svelte:self",
            Self::SlotElement => "slot",
            Self::SvelteFragment => "svelte:fragment",
            Self::SvelteBoundary => "svelte:boundary",
            Self::TitleElement => "title",
        }
    }

    /// Returns the AST node type name for JSON output
    #[inline]
    pub const fn node_type(&self) -> &'static str {
        match self {
            Self::SvelteHead => "SvelteHead",
            Self::SvelteWindow => "SvelteWindow",
            Self::SvelteBody => "SvelteBody",
            Self::SvelteDocument => "SvelteDocument",
            Self::SvelteElement { .. } => "SvelteElement",
            Self::SvelteComponent { .. } => "SvelteComponent",
            Self::SvelteSelf => "SvelteSelf",
            Self::SlotElement => "SlotElement",
            Self::SvelteFragment => "SvelteFragment",
            Self::SvelteBoundary => "SvelteBoundary",
            Self::TitleElement => "TitleElement",
        }
    }

    /// The `<svelte:element>` `this` binding — the wire's `tag` field.
    ///
    /// Yields the whole [`SpecialThis`], not just its expression, because the two forms
    /// serialize differently: the plain-string `this="x"` is a fused Svelte-style `Literal`,
    /// the braced `this={x}` an island. Which form it is, is the binding's own structure —
    /// the writer must not re-derive it from the source bytes.
    pub fn tag(&self) -> Option<&SpecialThis<'arena>> {
        match self {
            Self::SvelteElement { tag } => Some(tag),
            _ => None,
        }
    }

    /// The `<svelte:component>` `this` binding — the wire's `expression` field.
    ///
    /// The whole tag, not the bare expression: its `{…}` span is what bounds the expression's
    /// comment-attach window, and handing out the expression without it is how comments
    /// outside the braces came to attach to it.
    pub fn expression(&self) -> Option<&ExpressionTag<'arena>> {
        match self {
            Self::SvelteComponent { expression } => Some(expression),
            _ => None,
        }
    }
}

/// Svelte Special Element
///
/// Represents special Svelte elements that have unique behavior:
/// - `<svelte:head>`, `<svelte:window>`, `<svelte:body>`, `<svelte:document>`
/// - `<svelte:element>` (dynamic tag), `<svelte:component>` (dynamic component)
/// - `<svelte:self>`, `<slot>`, `<svelte:fragment>`, `<svelte:boundary>`
/// - `<title>` (when inside `<svelte:head>`)
///
/// Variant-specific data (tag for SvelteElement, expression for SvelteComponent)
/// is stored in the `SpecialElementKind` enum, not as Option fields here.
#[derive(Debug, Clone)]
pub struct SpecialElement<'arena> {
    pub kind: SpecialElementKind<'arena>,
    pub attributes: &'arena [AttributeNode<'arena>],
    pub fragment: Fragment<'arena>,
    pub span: Span,
    pub name_span: Span,
    /// Position of the `>` that closes the opening tag.
    /// Used by the printer to find trailing comments between the last attribute and `>`.
    pub open_tag_end: u32,
}

/// Svelte Options
///
/// Represents `<svelte:options>` which configures component behavior.
/// Stored separately from the fragment in `Root.options`.
#[derive(Debug, Clone)]
pub struct SvelteOptions<'arena> {
    pub attributes: &'arena [AttributeNode<'arena>],
    pub span: Span,
    /// End of the `svelte:options` tag name — where the attribute list's first gap begins.
    /// Kept from the parse rather than derived from `span.start` + the tag's length, so no
    /// reader has to assume how the name was spelled.
    pub name_end: u32,
    /// The `>` closing the opening tag; with `name_end` it bounds the region the attribute
    /// list's comments live in. `span.end` is not it: the paired form
    /// (`<svelte:options></svelte:options>`) runs on to the closing tag.
    pub open_tag_end: u32,
}

impl<'arena> FragmentNode<'arena> {
    pub fn span(&self) -> Span {
        match self {
            FragmentNode::Element(elem) => elem.span,
            FragmentNode::SpecialElement(elem) => elem.span,
            FragmentNode::ExpressionTag(tag) => tag.span,
            FragmentNode::Text(text) => text.span,
            FragmentNode::Comment(comment) => comment.span,
            FragmentNode::IfBlock(block) => block.span,
            FragmentNode::EachBlock(block) => block.span,
            FragmentNode::AwaitBlock(block) => block.span,
            FragmentNode::KeyBlock(block) => block.span,
            FragmentNode::SnippetBlock(block) => block.span,
            FragmentNode::HtmlTag(tag) => tag.span,
            FragmentNode::ConstTag(tag) => tag.span,
            FragmentNode::DeclarationTag(tag) => tag.span,
            FragmentNode::DebugTag(tag) => tag.span,
            FragmentNode::RenderTag(tag) => tag.span,
        }
    }

    /// Check if this node is whitespace-only text.
    ///
    /// Returns true only for Text nodes whose content is entirely *collapsible*
    /// whitespace `[ \t\n\r]` ([`is_collapsible_ws`]). A non-breaking space
    /// (U+00A0 / U+202F), a form feed, or any other separator CSS does not collapse
    /// is template *content*, not collapsible whitespace, so a node made only of
    /// those returns false. All non-Text nodes return false.
    ///
    /// Reads the precomputed `Text::is_collapsible_ws_only` flag — O(1), source-free.
    #[inline]
    pub fn is_whitespace_only_text(&self) -> bool {
        matches!(self, FragmentNode::Text(t) if t.is_collapsible_ws_only)
    }

    /// Check if this node is a whitespace-only text containing at least one newline.
    ///
    /// Used to detect source line breaks at element boundaries (hug mode pattern).
    /// "Whitespace-only" is the collapsible (ASCII) class — see `is_whitespace_only_text`;
    /// a node with a non-breaking space is content, not a boundary break. Returns false
    /// for non-Text nodes or Text without newlines. Reads precomputed flags — source-free.
    #[inline]
    pub fn is_boundary_break(&self) -> bool {
        matches!(self, FragmentNode::Text(t) if t.is_collapsible_ws_only && t.has_newline())
    }

    /// Whether this node is a **declaration** — `{@const}`, `{const …}`, `{let …}`, or a
    /// `{#snippet}` block.
    ///
    /// The nodes that declare a binding and render nothing. Because the compiler
    /// [hoists](FragmentNode::is_hoisted_from_fragment) them out of the fragment before it applies
    /// the whitespace rules, the break beside one is render-free, and the printer spends that
    /// licence on giving each its own line — see `Printer::is_own_line_declaration`.
    ///
    /// A `{#snippet}` belongs here on both counts: it declares a binding (the snippet name) and
    /// renders nothing where it is written — `<C>docs{#snippet icon()}…{/snippet}</C>` compiles
    /// byte-identically with the snippet broken onto its own line
    /// (`../test-svelte-prettier-whitespace/hoisted-tags.md` carries the full oracle matrix).
    ///
    /// ⚠️ `{@debug}` is hoisted alike but is **not** a declaration: it is a transient debugging
    /// aid, so it keeps the edge *trim* the hoist also licenses rather than a line of its own.
    #[inline]
    pub fn is_declaration(&self) -> bool {
        matches!(
            self,
            FragmentNode::ConstTag(_)
                | FragmentNode::DeclarationTag(_)
                | FragmentNode::SnippetBlock(_)
        )
    }

    /// Whether the compiler **hoists** this node out of its fragment before it applies the
    /// whitespace rules — `clean_nodes`' `hoisted` list.
    ///
    /// Such a node is invisible to those rules, so the node beside it is the fragment's real
    /// first/last one and the run between them is a render-free *edge* run rather than an
    /// inter-sibling one: `{#if c}text {@const x = 1}{/if}` compiles to `text`, exactly like the
    /// glued authoring, where `{#if c}text <b>y</b>{/if}` keeps its space. The printer's boundary
    /// analysis therefore has to skip these nodes when it asks "am I at the content boundary?"
    /// ([`FragmentNode::content_bounds`]).
    ///
    /// ⚠️ The neighbour is **not** always a text — a whitespace-only separator between a hoisted
    /// node and a non-text sibling is the same edge run, and
    /// [`crate::printer::Printer::is_hoisted_edge_separator`] is where that half is decided
    /// (`blocks/hoisted_boundary_sibling_kinds`). Being deletable only licenses a choice of form
    /// there; which form is picked is the "a node that owns its own line keeps it" exclusion
    /// below, asked of BOTH ends of the run.
    ///
    /// ⚠️ The hoist is **not** one of Svelte 5's three published whitespace rules (collapse
    /// between nodes / trim at the edges / `<pre>` exempt) — those say nothing about which nodes
    /// the edge is measured against. It lives only in `clean_nodes`, so it is verified against
    /// the compiler rather than the summary; see
    /// [hoisted_boundary_convergence](../../../../tests/fixtures/svelte/blocks/hoisted_boundary_convergence_prettier_divergence/).
    ///
    /// ⚠️ Scoped to the **edges**. With content on both sides the hoist makes neither run an
    /// edge: the two runs merge into a single rendered space (`a {@const} b` → `a b`), so a space
    /// must survive there and gluing would be a different document.
    ///
    /// ⚠️ **Deliberately NARROWER than the oracle's list**, which also holds `SvelteHead` /
    /// `SvelteWindow` / `SvelteBody` / `SvelteDocument`. Those four are **block-classified**
    /// here, so `handle_block_child` gives each its own line — and a line break at a fragment
    /// edge is itself render-free, so trimming it and breaking it are both correct for the
    /// render but cannot both happen: `<svelte:body … />b` trims to the glued form, whose next
    /// pass re-breaks it, forever (a real F1 2-cycle the fuzz gate caught). Their own line is
    /// the better form — a `<svelte:head>` welded to its neighbour would be the alternative —
    /// so the printer keeps the break and declines the trim. The four are excluded HERE rather
    /// than at each reader, so the two rules cannot re-collide at a new call site. The one
    /// question they DO answer as hoisted is the glue scan's — "what is the nearest content
    /// beside me?" — which asks the compiler's whole list, [`FragmentNode::is_compiler_hoisted`],
    /// instead of this one: a glued boundary is never split, and the compiler's glue runs
    /// through these four exactly as through a `{@const}`.
    ///
    /// ⚠️ **The hoist licenses two different things, and only one of them is this trim.** The break
    /// beside a hoisted node is render-free for the same reason its edge run is, so trimming the
    /// run and breaking it are both correct and only one can happen. A **declaration**
    /// ([`FragmentNode::is_declaration`] — the tags and the `{#snippet}` block) spends the licence
    /// on the break — it takes its own line (`Printer::is_own_line_declaration`), which is where
    /// authors already write declarations — and reaches the trim only through that break.
    /// `DebugTag` and `TitleElement` are what still trim: no layout rule gives either a line of
    /// its own.
    ///
    /// So the five kinds stay in this ONE set even though they split on layout: every reader here
    /// is asking the compiler's question ("does this node stand between the content and the
    /// fragment edge?"), and the answer is the same for all five. (The glue scan behind
    /// `is_own_line_declaration` asks a different question and reads the compiler's whole list,
    /// [`FragmentNode::is_compiler_hoisted`], which includes these five.)
    ///
    /// The layout split does make [`FragmentNode::content_bounds`] *redundant* for a declaration —
    /// the whole fixture suite stays green with those kinds treated as content there, because the
    /// run beside an own-line declaration is trimmed by `handle_text_child`'s own arms before the
    /// bounds are consulted. Narrowing it would state something false about the compiler to
    /// record which reader happens to fire first, so the set answers the compiler's question and
    /// the readers keep their own.
    #[inline]
    pub fn is_hoisted_from_fragment(&self) -> bool {
        match self {
            FragmentNode::ConstTag(_)
            | FragmentNode::DeclarationTag(_)
            | FragmentNode::DebugTag(_)
            | FragmentNode::SnippetBlock(_) => true,
            FragmentNode::SpecialElement(se) => {
                matches!(se.kind, SpecialElementKind::TitleElement)
            }
            _ => false,
        }
    }

    /// Whether the compiler hoists this node out of its fragment — `clean_nodes`' `hoisted` list
    /// in FULL: [`FragmentNode::is_hoisted_from_fragment`]'s tags and `<title>`, plus the four
    /// [global](SpecialElementKind::is_global) `svelte:*` elements that set leaves out.
    ///
    /// ⚠️ **For the glue scans only** (`Printer::glued_to_content`). Two nodes the compiler's
    /// whitespace rules see as neighbours once the hoisted ones are gone are glued exactly when
    /// no whitespace stands between them, whatever was hoisted from between: `a<svelte:window
    /// />b` renders `ab`, so breaking either side of the element renders a space — a glued
    /// boundary is never split. That question has to see the whole list. The **trim** readers
    /// ([`FragmentNode::content_bounds`] and the edge-separator test) must not: they ask the
    /// narrower set, whose doc says why a fragment-edge trim beside a global element is an F1
    /// 2-cycle.
    #[inline]
    pub fn is_compiler_hoisted(&self) -> bool {
        self.is_hoisted_from_fragment()
            || matches!(self, FragmentNode::SpecialElement(se) if se.kind.is_global())
    }

    /// The index range of `nodes` that the whitespace rules see — the first and last node that
    /// is **not** [hoisted](FragmentNode::is_hoisted_from_fragment), or `None` when every node is.
    ///
    /// Computed once per fragment and compared against, rather than asked per node: a
    /// `nodes[..i].all(is_hoisted)` test at each child would be O(n²) over a fragment, on a
    /// question whose answer two bounds settle.
    pub(crate) fn content_bounds(nodes: &[FragmentNode<'_>]) -> Option<(usize, usize)> {
        let first = nodes.iter().position(|n| !n.is_hoisted_from_fragment())?;
        let last = nodes.iter().rposition(|n| !n.is_hoisted_from_fragment())?;
        Some((first, last))
    }

    /// Whether index `i` sits at (or past) the **start** of [`FragmentNode::content_bounds`] —
    /// no node the whitespace rules see stands before it, so the run on its leading side is the
    /// fragment's own boundary air rather than a seam between two children.
    ///
    /// ⚠️ **The one spelling of that comparison**, and it is shared because the readers must not
    /// drift: `Printer::handle_content_text_child` TRIMS a text's leading run here
    /// (`is_first`), `Printer::content_holds_interior_blank` declines to read a blank there for
    /// the same reason, and `Printer::is_hoisted_edge_separator` asks it of the separator node
    /// between two non-text siblings. A gate that answered it differently from the emitter it
    /// models would break a body open on a blank that emitter had already deleted — the whole
    /// bug class those three exist to close. `<=` rather than `==` because a HOISTED node sits
    /// at a real index below `bounds.0`, and every index it occupies answers the same.
    #[inline]
    pub(crate) fn at_content_start(i: usize, bounds: (usize, usize)) -> bool {
        i <= bounds.0
    }

    /// The mirror of [`FragmentNode::at_content_start`] at the **end** of the content bounds —
    /// same rule, same readers, same reason for `>=`.
    #[inline]
    pub(crate) fn at_content_end(i: usize, bounds: (usize, usize)) -> bool {
        i >= bounds.1
    }
}

/// Svelte Element kind - distinguishes HTML elements from components.
///
/// Classification-only (the printer's block/inline decision + the writer's
/// `RegularElement`/`Component` `type` tag, both by `match`); never serialized.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElementKind {
    /// HTML element: `<div>`, `<span>`, `<input>`, etc. (lowercase first character)
    Html,
    /// Svelte component: `<MyComponent>`, `<Button>`, etc. (uppercase first character)
    Component,
}

/// Whether a tag `name` is a Svelte **component** rather than an HTML element.
///
/// A `:`-namespaced tag (`foo:bar`, `Foo:bar`) is never a component — Svelte's
/// `regex_valid_component_name` excludes `:`, so a namespaced name is a `RegularElement` even
/// with an uppercase prefix. Otherwise: a dotted tag (member access, e.g. `ns.Comp`,
/// `Object.component`) is a component, as is any name whose first character is uppercase
/// (Unicode, so `\p{Lu}` such as `Δ` / `Я` counts, not just ASCII). Mirrors Svelte's
/// `regex_valid_component_name` (`1-parse/state/element.js`): uppercase-first with optional dots,
/// or any `ID_Start`-first name with one or more dotted segments.
///
/// The single source for component-ness: the parser reads it to set [`ElementKind::Component`],
/// and the printer's tag classification reads it too (the printer's separate `NAMESPACED` bit
/// carries the `foo:bar` self-close term). One predicate keeps the two from drifting — the
/// printer must not classify a Unicode-uppercase component as a plain inline element and strip
/// its self-close.
///
/// Examples: `Comp` → true, `ns.Comp` → true, `Object.component` → true, `div` → false,
/// `foo:bar` → false, `Foo:bar` → false.
pub(crate) fn is_component_name(name: &str) -> bool {
    name_shape(name) == NameShape::Component
}

/// Whether `name` is void as Svelte's `is_void` (`utils.js`) answers it: a void HTML element
/// (`crate::html::is_void_element`), or a `!doctype` declaration in any ASCII case — which
/// Svelte's parser reads as an element and its compiler closes like a void one, though no
/// element it is. The parser's element facts and the compiler's server output read this.
pub fn is_svelte_void(name: &str) -> bool {
    // the declaration test behind its `!`, so the case-folding compare (an out-of-line call)
    // runs only for a declaration-shaped name, never for every name the element set rejects
    crate::html::is_void_element(name)
        || (name.starts_with('!') && name.eq_ignore_ascii_case("!doctype"))
}

/// What a tag name's own punctuation makes it: `:`-namespaced, else component-shaped
/// ([`is_component_name`]), else neither.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum NameShape {
    /// A `:` in the name (`foo:bar`, `Foo:bar`) — never a component.
    Namespaced,
    Component,
    Plain,
}

/// The name's [`NameShape`], from one walk that answers every byte question — any `:`
/// namespaces (and so refuses component-ness), any `.` admits — where `contains(':')` then
/// `contains('.')` read the name twice, and [`TagFacts::compute`]'s namespaced bit a third
/// time; both are ASCII, so a byte match is the `char` match exactly.
fn name_shape(name: &str) -> NameShape {
    let mut dotted = false;
    for &b in name.as_bytes() {
        match b {
            b':' => return NameShape::Namespaced,
            b'.' => dotted = true,
            _ => {}
        }
    }
    if dotted || name.chars().next().is_some_and(char::is_uppercase) {
        NameShape::Component
    } else {
        NameShape::Plain
    }
}

/// Every classification fact derivable from a tag *name* alone, packed into a `u16` and computed
/// once at parse (stored on [`Element::facts`], read back by the printer's element/fragment/
/// sibling paths).
///
/// Nothing element-instance-specific lives here — a `<script>`'s has-content overlay and the
/// `Component`/`Block`/`Inline` element-kind split both stay in the printer. Those paths re-ask
/// the same tag-name questions many times per element, and every answer is a pure function of the
/// name, so computing them once (where the raw `&str` is already in hand) turns each print-time
/// read into a single field load. The exhaustive equivalence test below grades each accessor
/// against the pure predicate it encodes — a mispacked bit changes layout only on rare tags at
/// rare widths, which no fixture or corpus diff can be relied on to see.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct TagFacts(u16);

impl TagFacts {
    /// `crate::html::is_block_element` (block-level for formatting).
    const BLOCK: u16 = 1 << 0;
    /// [`is_svelte_void`] (`<br>`, `<img>`, `!doctype`).
    const VOID: u16 = 1 << 1;
    /// `crate::html::is_foreign_element` (SVG or MathML).
    const FOREIGN: u16 = 1 << 2;
    /// Component-shaped name — [`is_component_name`] (Unicode-uppercase initial or a dotted member
    /// name — `Button`, `Δcomp`, `foo.bar`). Drives the `Component` element kind. A `:`-namespaced
    /// name (`foo:bar`) is a `RegularElement`, not a component, so it is *not* here — it carries
    /// [`NAMESPACED`](Self::NAMESPACED) instead.
    const COMPONENT_NAME: u16 = 1 << 3;
    const STYLE: u16 = 1 << 4;
    const SCRIPT: u16 = 1 << 5;
    const TEMPLATE: u16 = 1 << 6;
    /// `crate::html::preserves_whitespace` (`<pre>`, `<textarea>`).
    const WS_SENSITIVE: u16 = 1 << 7;
    /// `<!DOCTYPE>`-style declaration (leading `!`), which closes with `>`, not `/>`.
    const DECLARATION: u16 = 1 << 8;
    /// A `:` in the name (`<foo:bar>`) — a namespaced `RegularElement`. Independent of
    /// [`COMPONENT_NAME`](Self::COMPONENT_NAME): it takes the inline element kind like any other
    /// non-block regular element, but may still print self-closing (prettier's `didSelfClose`), so
    /// it is the third contributor to `can_self_close` alongside component and foreign.
    const NAMESPACED: u16 = 1 << 9;
    /// `crate::html::collapses_child_whitespace` — a whitespace-collapsing container (`<table>`,
    /// `<select>`, …) whose inter-sibling whitespace the compiler removes entirely.
    const WS_COLLAPSING: u16 = 1 << 10;
    /// `crate::html::is_line_break_element` (`<br>` alone — the element that IS a rendered line
    /// break). Deliberately narrower than [`VOID`](Self::VOID): the other void elements render
    /// inline, so a `<img>`/`<input>`/`<wbr>` flows where a `<br>` owns its line.
    const LINE_BREAK: u16 = 1 << 11;

    /// Derive the facts from the tag name. The single source: [`Element::facts`] stores exactly
    /// this, and the equivalence test grades every accessor against the predicates named here.
    ///
    /// Never inlined: its one caller outside the tests is the element parser, whose frame every
    /// level of element nesting pays, and the membership `match`es behind these predicates are
    /// kilobytes of code whose spills would land in that frame.
    #[inline(never)]
    pub(crate) fn compute(tag_name: &str) -> Self {
        let mut bits: u16 = 0;
        if crate::html::is_block_element(tag_name) {
            bits |= Self::BLOCK;
        }
        if is_svelte_void(tag_name) {
            bits |= Self::VOID;
        }
        if crate::html::is_foreign_element(tag_name) {
            bits |= Self::FOREIGN;
        }
        match name_shape(tag_name) {
            NameShape::Namespaced => bits |= Self::NAMESPACED,
            NameShape::Component => bits |= Self::COMPONENT_NAME,
            NameShape::Plain => {}
        }
        if tag_name == "style" {
            bits |= Self::STYLE;
        }
        if tag_name == "script" {
            bits |= Self::SCRIPT;
        }
        if tag_name == "template" {
            bits |= Self::TEMPLATE;
        }
        if crate::html::preserves_whitespace(tag_name) {
            bits |= Self::WS_SENSITIVE;
        }
        if crate::html::collapses_child_whitespace(tag_name) {
            bits |= Self::WS_COLLAPSING;
        }
        if tag_name.starts_with('!') {
            bits |= Self::DECLARATION;
        }
        if crate::html::is_line_break_element(tag_name) {
            bits |= Self::LINE_BREAK;
        }
        Self(bits)
    }

    pub(crate) fn is_block(self) -> bool {
        self.0 & Self::BLOCK != 0
    }
    /// The kind a regular element with this name takes: `Component` for a component-shaped
    /// name ([`is_component_name`]), `Html` for every other.
    pub(crate) fn element_kind(self) -> ElementKind {
        if self.is_component_name() {
            ElementKind::Component
        } else {
            ElementKind::Html
        }
    }
    pub(crate) fn is_void(self) -> bool {
        self.0 & Self::VOID != 0
    }
    pub(crate) fn is_foreign(self) -> bool {
        self.0 & Self::FOREIGN != 0
    }
    pub(crate) fn is_component_name(self) -> bool {
        self.0 & Self::COMPONENT_NAME != 0
    }
    pub(crate) fn is_namespaced(self) -> bool {
        self.0 & Self::NAMESPACED != 0
    }
    pub(crate) fn is_style(self) -> bool {
        self.0 & Self::STYLE != 0
    }
    /// A raw-text element — `<script>` or `<style>`, whose body Svelte reads verbatim up to
    /// the first literal end tag rather than as template markup. The one definition the
    /// parser's content regime and the printer's raw-text readers share.
    pub(crate) fn is_raw_text(self) -> bool {
        self.0 & (Self::SCRIPT | Self::STYLE) != 0
    }
    pub(crate) fn is_template(self) -> bool {
        self.0 & Self::TEMPLATE != 0
    }
    pub(crate) fn is_ws_sensitive(self) -> bool {
        self.0 & Self::WS_SENSITIVE != 0
    }
    pub(crate) fn collapses_child_whitespace(self) -> bool {
        self.0 & Self::WS_COLLAPSING != 0
    }
    pub(crate) fn is_declaration(self) -> bool {
        self.0 & Self::DECLARATION != 0
    }
    pub(crate) fn is_line_break(self) -> bool {
        self.0 & Self::LINE_BREAK != 0
    }
}

/// Svelte Element - HTML/component tag
///
/// Represents an HTML element or Svelte component in the template.
/// Elements have a name, attributes, and child nodes in a fragment.
#[derive(Debug, Clone)]
pub struct Element<'arena> {
    pub kind: ElementKind,
    /// Name-derived classification, computed once at parse (see [`TagFacts`]). Occupies padding
    /// beside `kind`, so it costs no extra size; the printer reads it instead of re-deriving.
    /// Crate-internal like [`TagFacts`] — derived from `name`, not part of the public wire AST.
    pub(crate) facts: TagFacts,
    pub attributes: &'arena [AttributeNode<'arena>],
    pub fragment: Fragment<'arena>,
    pub span: Span,
    pub name_span: Span,
    /// Position of the `>` that closes the opening tag.
    /// Used by the printer to find trailing comments between the last attribute and `>`.
    pub open_tag_end: u32,
}

impl Element<'_> {
    /// The tag name — span-identity, the verbatim `source[name_span]` slice
    /// (tag names never carry surrounding whitespace).
    #[inline]
    pub fn name<'s>(&self, source: &'s str) -> &'s str {
        &source[self.name_span.range()]
    }

    /// Whether this is a `<template>` whose `lang` / `type` names a language other than HTML
    /// — the elements whose CONTENT the formatter copies out verbatim rather than formatting.
    ///
    /// The one definition of that composite. It has three callers across two crates (the
    /// element builder, the sibling-`>` dangle's eligibility test, and `tsv_debug`'s razor
    /// audit, which must agree with the printer about which bodies are the author's bytes),
    /// and each spelling it out itself would be three copies of a predicate whose every
    /// clause is a drift risk, down to which bytes the `lang` value is read off (see
    /// [`lang_attribute`]: the decoded text, not the raw bytes). The template question stays on
    /// the parse-time [`TagFacts`] bitfield, so the printer's hot paths keep the field load
    /// rather than re-comparing the tag name.
    pub fn is_frozen_template(&self, source: &str) -> bool {
        self.facts.is_template() && EmbeddedLang::Template.is_frozen(self.attributes, source)
    }
}

/// The `lang` or `type` attribute value from an attribute list, `text/` prefix stripped
/// (`type="text/less"` → `"less"`). `None` when neither attribute is present.
///
/// **`lang` outranks `type`**, whatever their source order — prettier's `getLangAttribute`
/// is `lang || type`, so `<template type="text/html" lang="pug">` is pug to both formatters.
/// A first-hit-in-source-order read answered that tag "html" and formatted a pug body as
/// markup. **An empty value names no language** and reads as absent (the attribute falls out
/// of the answer entirely, so an empty `lang` still yields the `type` beside it) — prettier
/// again: `''` is falsy on both sides of its `||`, and Svelte's own `lang` regex cannot
/// match an empty value either. Pinned by `tests/fixtures/svelte/attributes/lang_priority`.
///
/// Reads the **decoded** value ([`Text::data`]), never the raw bytes: the language a
/// `lang`/`type` names is what the attribute *means*, and the parser already computed that —
/// `lang="&#99;ss"` is `css`, and a raw read routes it to the preserve-verbatim path instead
/// of the CSS printer. Prettier's `getLangAttribute` reads its `data` for the same reason.
/// The decode borrows the source slice whenever the value carries no `&` (the overwhelming
/// case), so the `Cow` costs nothing there; only an entity-bearing value allocates.
///
/// ⚠️ This is the **formatting** question, and it is the only one that decodes. The wire
/// schema asks a different one — "is this component TypeScript?" — whose oracle is Svelte's
/// own `this.ts`, a regex over the RAW template bytes (`1-parse/index.js`:
/// `lang=(["'])?([^"' >]+)` compared against `ts`). So `<script lang="&#116;s">` is a
/// TypeScript body to *this* reader and NOT TypeScript to the wire, and `convert`'s
/// `script_lang` deliberately stays a separate raw-keyed reader rather than sharing this one.
/// Pinned by `tests/fixtures/svelte/attributes/lang_entity`, which holds both answers.
fn lang_attribute<'s>(attributes: &[AttributeNode<'_>], source: &'s str) -> Option<Cow<'s, str>> {
    let mut type_value = None;
    for attr_node in attributes {
        if let AttributeNode::Attribute(attr) = attr_node {
            let name = attr.name(source);
            let is_lang = name == "lang";
            if (is_lang || name == "type")
                && let Some(value_parts) = attr.value
            {
                for part in value_parts {
                    if let AttributeValue::Text(text) = part {
                        let value = narrow_lang_value(text.data(source));
                        if !value.is_empty() {
                            if is_lang {
                                return Some(value);
                            }
                            if type_value.is_none() {
                                type_value = Some(value);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
    type_value
}

/// A position that carries an embedded body the printer either formats or freezes — the only
/// variable in the opacity rule below, and the owner of that position's formattable-name set.
///
/// **The rule: a body declared as a language tsv does not format at that position is the
/// author's own bytes.** One reader answers it everywhere ([`lang_attribute`] — decoded,
/// trimmed, `text/`-stripped, `lang` over `type`), an absent attribute is always formattable,
/// and this enum names the only thing that differs between positions. Asked at every position
/// that has a body — both `<script>` positions, both `<style>` positions, and `<template>` —
/// and answered the same way at each, since a nested body has had *nothing* established about
/// it (no parser reads it) and a top-level one only that it parsed.
///
/// A **tag**, not a body kind: the two `<script>` positions share `Script` because they share
/// the answer. See docs/conformance_prettier_svelte.md §Foreign-language embedded bodies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmbeddedLang {
    Script,
    Style,
    Template,
}

impl EmbeddedLang {
    /// The `lang` / `type` values whose body this position's printer formats; every other
    /// name freezes. [`lang_attribute`]'s narrowing applies, so `lang=" ts "` and
    /// `type="text/javascript"` are in the script set.
    ///
    /// - **`Style`** — `css` alone: tsv has one CSS parser and no scss/less one, and guessing
    ///   with the CSS printer corrupts what it half-understands (`@color: red;` →
    ///   `@color : red;`, no longer a less variable declaration).
    /// - **`Script`** — the JS/TS family, under the bare names and the living JavaScript MIME
    ///   essences. The line is where tsv's **printer** stops, not where Svelte's *parser*
    ///   switches grammars (`this.ts` recognizes the single raw value `ts`): tsv parses every
    ///   body under the TS grammar whatever the tag says. `module` is here because on a
    ///   `<script>` `type` is a loading and MIME attribute, so its value need not be a
    ///   language at all. Out: `coffee`, the `json` / `importmap` family, every unknown name,
    ///   and the **dead** MIME essences mimesniff still lists (`text/jscript`,
    ///   `text/livescript`, the `x-` spellings, `text/javascript1.<n>`).
    /// - **`Template`** — `html` alone; any other name (`pug`, `jade`, …) is a markup
    ///   language tsv cannot reflow.
    ///
    /// The argument for each line — and every divergence from prettier it creates — is
    /// docs/conformance_prettier_svelte.md §Foreign-language embedded bodies, which owns the
    /// rule; this doc says only what a reader of the list needs.
    fn formattable_langs(self) -> &'static [&'static str] {
        match self {
            Self::Script => &[
                "ts",
                "typescript",
                "js",
                "javascript",
                "ecmascript",
                "application/javascript",
                "application/ecmascript",
                "module",
            ],
            Self::Style => &["css"],
            Self::Template => &["html"],
        }
    }

    /// Whether an attribute list's `lang`/`type` names a language outside this position's
    /// [formattable set](Self::formattable_langs) — the bodies the printer freezes (emits
    /// verbatim, the author's own bytes) instead of reprinting from the AST.
    ///
    /// Note the **parser** is untouched by this: at a *top-level* position a body must still
    /// parse under its grammar whatever its `lang` says (canonical Svelte runs acorn and
    /// `parseCss` on every top-level body regardless), so a top-level freeze only ever sees
    /// parseable files. A *nested* body is raw text to both parsers and carries no such
    /// guarantee — which is why the freeze it takes is verbatim rather than anything that
    /// would rewrite it.
    pub fn is_frozen(self, attributes: &[AttributeNode<'_>], source: &str) -> bool {
        lang_attribute(attributes, source)
            .is_some_and(|lang| !self.formattable_langs().contains(&lang.as_ref()))
    }
}

/// Trim a decoded `lang` / `type` value and strip its `text/` prefix, keeping the borrow when
/// the decode kept one. Both narrowings are sub-slices, so the owned arm re-owns the remainder
/// rather than the whole value — reached only by an entity-bearing attribute.
///
/// ⚠️ **The trim is tsv's own, not a transcription** — prettier's `getLangAttribute` does not
/// trim at all (it is `getAttributeTextValue('lang') || …('type')` plus the same `^text/`
/// strip) and compares the raw value against an exact five-name **denylist**. Only the
/// *decode* is prettier's. The trim is a cataloged divergence, docs/conformance_prettier_svelte.md
/// §Foreign-language embedded bodies, "Untrimmed `lang` routing".
///
/// ⚠️ Its class is therefore the **union** of JS `\s` and Rust's `White_Space`, wider than
/// either — and this is the one whitespace read in the crate where "which oracle does this
/// mirror" is the wrong question, because it mirrors none. tsv's list is an **allowlist** and
/// the trim is what lands a padded name on it, so a WIDER class can only ever move a name
/// *toward* formatting; no denylist entry carries whitespace, so no widening can make tsv
/// format a body prettier freezes. Both single-class spellings give a witness away, in
/// opposite directions, and each was a `<style>` body frozen where prettier formats:
/// `str::trim` lacks U+FEFF (`lang="<ZWNBSP>css"`), and
/// [`is_svelte_ws`](crate::whitespace::is_svelte_ws) alone lacks U+0085
/// (`lang="<NEL>css"`). The union closes both; `attributes/lang_unicode_space` carries them
/// side by side.
///
/// (The wire's `lang` question is a different reader on the RAW bytes — `script_lang` — and
/// stays separate; `attributes/lang_entity` holds both answers.)
fn narrow_lang_value(value: Cow<'_, str>) -> Cow<'_, str> {
    /// The padding a `lang` name may carry: JS `\s` ∪ Rust's `White_Space`. See above — the
    /// two disagree at U+FEFF and U+0085, and only the union keeps both off the name.
    fn is_lang_pad(c: char) -> bool {
        crate::whitespace::is_svelte_ws(c) || c.is_whitespace()
    }
    fn narrow(raw: &str) -> &str {
        let lang = raw.trim_matches(is_lang_pad);
        lang.strip_prefix("text/").unwrap_or(lang)
    }
    match value {
        Cow::Borrowed(raw) => Cow::Borrowed(narrow(raw)),
        Cow::Owned(raw) => Cow::Owned(narrow(&raw).to_owned()),
    }
}

/// `facts` rides in the tail padding beside `kind`, so the parse-time classification costs no
/// extra `Element` size. Guards that property against a future field reorder that would spill it.
/// 64-bit only — the slice fields are half-width on wasm32, a different layout.
#[cfg(all(test, target_pointer_width = "64"))]
const _: () = assert!(size_of::<Element<'static>>() == 56);

/// Svelte Attribute - element attribute
///
/// Represents an attribute on an element, e.g., `class="foo"` or `disabled`.
/// The value is optional (for boolean attributes) and can contain text or expressions.
///
/// Shorthand attributes like `{a}` (equivalent to `a={a}`) are represented as
/// Attribute with name="a" and value containing an ExpressionTag with Identifier "a".
/// Detection is implicit: check if name matches expression identifier.
#[derive(Debug, Clone)]
pub struct Attribute<'arena> {
    pub value: Option<&'arena [AttributeValue<'arena>]>,
    pub span: Span,
    pub name_span: Span,
}

impl Attribute<'_> {
    /// The attribute name — span-identity, the verbatim `source[name_span]` slice.
    /// Every attribute name is a bare source run, a padded `{ shorthand }`
    /// included: its `name_span` is the identifier alone, not the braces interior
    /// (see the parser's `parse_shorthand_attribute`).
    #[inline]
    pub fn name<'s>(&self, source: &'s str) -> &'s str {
        &source[self.name_span.range()]
    }
}

/// Svelte SpreadAttribute - spread object as attributes
///
/// Represents `{...obj}` syntax that spreads an object's properties as attributes.
/// The expression can be any valid expression: identifier, call, member access, etc.
#[derive(Debug, Clone)]
pub struct SpreadAttribute<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub span: Span,
}

/// Svelte attribute-like node
///
/// Elements can have various attribute-like constructs:
/// - `Attribute`: Standard `name="value"` or `name={expr}` attributes (including shorthand `{a}`)
/// - `SpreadAttribute`: `{...obj}` spreads object properties as attributes
/// - `AttachTag`: `{@attach expr}` attachments (Svelte 5.29+)
/// - Directives: `on:`, `bind:`, `class:`, `style:`, `use:`, `transition:`, `in:`, `out:`,
///   `animate:`, `let:`
#[derive(Debug, Clone)]
pub enum AttributeNode<'arena> {
    Attribute(Attribute<'arena>),
    SpreadAttribute(SpreadAttribute<'arena>),
    AttachTag(AttachTag<'arena>),
    // Directives
    OnDirective(OnDirective<'arena>),
    BindDirective(BindDirective<'arena>),
    ClassDirective(ClassDirective<'arena>),
    StyleDirective(StyleDirective<'arena>),
    UseDirective(UseDirective<'arena>),
    TransitionDirective(TransitionDirective<'arena>),
    AnimateDirective(AnimateDirective<'arena>),
    LetDirective(LetDirective<'arena>),
}

impl<'arena> AttributeNode<'arena> {
    /// Get the span of this attribute node
    pub fn span(&self) -> Span {
        match self {
            AttributeNode::Attribute(a) => a.span,
            AttributeNode::SpreadAttribute(s) => s.span,
            AttributeNode::AttachTag(t) => t.span,
            AttributeNode::OnDirective(d) => d.span,
            AttributeNode::BindDirective(d) => d.span,
            AttributeNode::ClassDirective(d) => d.span,
            AttributeNode::StyleDirective(d) => d.span,
            AttributeNode::UseDirective(d) => d.span,
            AttributeNode::TransitionDirective(d) => d.span,
            AttributeNode::AnimateDirective(d) => d.span,
            AttributeNode::LetDirective(d) => d.span,
        }
    }
}

/// Svelte Attribute value part
///
/// Attribute values can contain static text or dynamic expressions.
#[derive(Debug, Clone)]
pub enum AttributeValue<'arena> {
    Text(Text),
    ExpressionTag(ExpressionTag<'arena>),
}

/// Whether `b` is **collapsible whitespace** — the characters CSS white-space processing
/// actually acts on, and therefore the ones a formatter may add, drop or respell without
/// changing what renders: `[ \t\n\r]`.
///
/// ⚠️ This is **narrower than Rust's `is_ascii_whitespace`**, which includes the form feed
/// `\x0c`, and the difference is not cosmetic. CSS Text 3 §White Space Processing: "white
/// space processing in CSS affects only the document white space characters: spaces
/// (U+0020), tabs (U+0009), and segment breaks" — and in HTML the segment break is U+000A,
/// since the DOM normalizes CR/CRLF away. U+000C is in none of those, so it is *rendered
/// content*: Svelte's `clean_nodes` classifies with `regex_not_whitespace` = `/[^ \t\r\n]/`
/// and keeps a form feed verbatim. Classifying one as whitespace lets the render-free
/// boundary trim delete it and the inter-sibling collapse respell it as a space — both
/// content changes, invisible to a corpus diff against prettier, whose own class
/// (`[\t\n\f\r ]`) has the same defect. See
/// [text_form_feed_prettier_divergence](../../../../tests/fixtures/svelte/elements/text_form_feed_prettier_divergence/).
///
/// ⚠️ It is equally **not** the *tokenizer's* whitespace, which does include the form feed (a
/// form feed separates attributes) and every Unicode space besides. This is a question about
/// what RENDERS, so it is the printer's and `Text`'s class alone — the parser and lexer ask
/// the token-separator question instead, and answer it with
/// [`is_svelte_ws`](crate::whitespace::is_svelte_ws).
#[inline]
pub(crate) const fn is_collapsible_ws(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}

/// [`is_collapsible_ws`] over a `char`, for the `str` pattern positions
/// (`starts_with`, `ends_with`, `split`, …).
///
/// ⚠️ Not for a trim: `trim_matches(f)` and its halves build a searcher that decodes a char
/// from an end before it can reject, and a text node's edges are asked once per node — use
/// [`trim_start_collapsible_ws`] / [`trim_end_collapsible_ws`], which are the same answer on
/// bytes, since every member of this class is one ASCII byte.
#[inline]
pub fn is_collapsible_ws_char(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\n' | '\r')
}

/// Byte length of the [`is_collapsible_ws`] run at the head of `s` — exact, since every
/// member is one ASCII byte, so the answer is a byte boundary and a char boundary at once.
#[inline]
pub(crate) fn collapsible_ws_prefix_len(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() && is_collapsible_ws(bytes[i]) {
        i += 1;
    }
    i
}

/// Byte length of the [`is_collapsible_ws`] run at the tail of `s` — the mirror of
/// [`collapsible_ws_prefix_len`].
#[inline]
pub(crate) fn collapsible_ws_suffix_len(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut i = bytes.len();
    while i > 0 && is_collapsible_ws(bytes[i - 1]) {
        i -= 1;
    }
    bytes.len() - i
}

/// Whether `s` is [`is_collapsible_ws`] throughout (an empty `s` is).
#[inline]
pub(crate) fn is_collapsible_ws_str(s: &str) -> bool {
    collapsible_ws_prefix_len(s) == s.len()
}

/// `s.trim_start_matches(is_collapsible_ws_char)` on bytes — see [`is_collapsible_ws_char`].
#[inline]
pub(crate) fn trim_start_collapsible_ws(s: &str) -> &str {
    &s[collapsible_ws_prefix_len(s)..]
}

/// `s.trim_end_matches(is_collapsible_ws_char)` on bytes — see [`is_collapsible_ws_char`].
#[inline]
pub(crate) fn trim_end_collapsible_ws(s: &str) -> &str {
    &s[..s.len() - collapsible_ws_suffix_len(s)]
}

/// The runs of `s` between [`is_collapsible_ws_char`] characters, empties skipped, each as a
/// slice of `s` — the split the printer counts a text node's prose words with. It steps the
/// same walk as [`collapsible_word_ranges`], the fill's splitter, so a word counted here is a
/// word packed there.
#[inline]
pub(crate) fn split_collapsible_ws(s: &str) -> impl Iterator<Item = &str> {
    CollapsibleWords { s, pos: 0 }
}

/// The runs of `s` between [`is_collapsible_ws_char`] characters, empties skipped, each as
/// its byte range in `s` — the word split of a text node's fill (prettier's
/// `splitTextToDocs`, `/[\t\n\f\r ]+/`). A range rather than a slice because `s` is itself a
/// span of a longer document, and the fill names each word by position (a doc text resolved
/// against the source at render) rather than copying it.
///
/// A word split *is* a whitespace classification — every character it splits at is deleted along
/// with the run it stood for — so it shares [`is_collapsible_ws_char`] rather than restating the
/// class. `str::split_ascii_whitespace` is the same function over the **wider** set, and using it
/// here dropped a form feed out of the middle of a word; `str::split_whitespace` is wider still
/// and would drop a non-breaking space.
///
/// A byte walk, not `str::split(is_collapsible_ws_char)`: that searcher decodes a char per
/// byte of every text node's prose to find a class that is four ASCII bytes, and the fill asks
/// it of every content text it packs.
#[inline]
pub(crate) fn collapsible_word_ranges(s: &str) -> impl Iterator<Item = CollapsibleWord> {
    CollapsibleWordRanges {
        bytes: s.as_bytes(),
        pos: 0,
    }
}

/// One word of [`collapsible_word_ranges`]: a maximal run of non-[`is_collapsible_ws`] bytes,
/// as offsets into the string that was split.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CollapsibleWord {
    pub(crate) start: u32,
    pub(crate) end: u32,
    /// Whether every byte of the word is ASCII, read off the walk that found its end. A
    /// word holds no `\t` and no `\n` (both end one), so an ASCII word is one column a
    /// byte: its display width is its byte length.
    pub(crate) is_ascii: bool,
}

impl CollapsibleWord {
    /// The word's text, sliced from the string it was split out of.
    #[inline]
    pub(crate) fn extract<'a>(&self, s: &'a str) -> &'a str {
        &s[self.start as usize..self.end as usize]
    }
}

/// The next word of `bytes` at or after `from`, as `(start, end, bits)` — the one walk both
/// word iterators step. The class being ASCII is what makes each cut a char boundary.
/// `bits` is the OR of the word's bytes, so its top bit says whether any is non-ASCII; a
/// caller that does not read it pays nothing for it.
#[inline]
fn next_collapsible_word(bytes: &[u8], from: usize) -> Option<(usize, usize, u8)> {
    let mut start = from;
    while start < bytes.len() && is_collapsible_ws(bytes[start]) {
        start += 1;
    }
    if start == bytes.len() {
        return None;
    }
    // `bytes[start]` is a non-member by construction, so the word scan begins past it.
    let mut bits = bytes[start];
    let mut end = start + 1;
    while end < bytes.len() && !is_collapsible_ws(bytes[end]) {
        bits |= bytes[end];
        end += 1;
    }
    Some((start, end, bits))
}

/// The iterator behind [`split_collapsible_ws`]: `pos` is where the unconsumed tail begins.
struct CollapsibleWords<'a> {
    s: &'a str,
    pos: usize,
}

impl<'a> Iterator for CollapsibleWords<'a> {
    type Item = &'a str;

    #[inline]
    fn next(&mut self) -> Option<&'a str> {
        let Some((start, end, _)) = next_collapsible_word(self.s.as_bytes(), self.pos) else {
            self.pos = self.s.len();
            return None;
        };
        self.pos = end;
        Some(&self.s[start..end])
    }
}

/// The iterator behind [`collapsible_word_ranges`].
struct CollapsibleWordRanges<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl Iterator for CollapsibleWordRanges<'_> {
    type Item = CollapsibleWord;

    #[inline]
    fn next(&mut self) -> Option<CollapsibleWord> {
        let Some((start, end, bits)) = next_collapsible_word(self.bytes, self.pos) else {
            self.pos = self.bytes.len();
            return None;
        };
        self.pos = end;
        Some(CollapsibleWord {
            start: start as u32,
            end: end as u32,
            is_ascii: bits < 0x80,
        })
    }
}

/// The `leading` (else trailing) edge whitespace run of a text node's `raw` — its
/// [`is_collapsible_ws_char`] prefix (else suffix), empty when that edge is content. The one
/// slice every edge question reads (a newline count, a blank-line presence, a boundary's
/// authoring), so the edge is delimited by the same class the fill collapses.
#[inline]
pub fn text_edge_ws(raw: &str, leading: bool) -> &str {
    if leading {
        &raw[..collapsible_ws_prefix_len(raw)]
    } else {
        &raw[raw.len() - collapsible_ws_suffix_len(raw)..]
    }
}

/// The number of newlines in a text node's `leading` (else trailing) edge whitespace run
/// ([`text_edge_ws`]) — `0` for a glued edge, `1` for an authored line break, `2+` for an
/// authored blank line. The one count every edge-newline question reads.
///
/// Counted in the walk that finds the edge — every member of the class is one ASCII byte, so
/// the run is the [`collapsible_ws_prefix_len`] / [`collapsible_ws_suffix_len`] walk and the
/// count is its `\n` bytes — rather than delimiting the edge first and then counting through
/// `matches('\n')`, whose `char` searcher is an out-of-line call per newline on a run of a
/// few bytes.
#[inline]
pub(crate) fn text_edge_newlines(raw: &str, leading: bool) -> usize {
    let bytes = raw.as_bytes();
    let mut newlines = 0;
    if leading {
        for &b in bytes {
            if !is_collapsible_ws(b) {
                break;
            }
            newlines += usize::from(b == b'\n');
        }
    } else {
        for &b in bytes.iter().rev() {
            if !is_collapsible_ws(b) {
                break;
            }
            newlines += usize::from(b == b'\n');
        }
    }
    newlines
}

/// Svelte Text node - raw text content
///
/// Represents static text in the template or attribute values.
/// In attribute values, this represents the unquoted string content.
///
/// Stores `raw_span` — the span of the original text (with HTML entities:
/// `&lt;`, `&#65;`) in the host source; the text is a pure sub-slice (no decode)
/// recovered on demand via `Text::raw`, so it is a `Span` rather than an owned
/// `String` (mirrors `tsv_lang::Comment::content_span`). The decoded form
/// (`<`, `A`) is computed lazily via `Text::data`, borrowing `raw` without
/// allocating when no entity is present.
///
/// The printer's hot template-whitespace predicates (multiline-children analysis,
/// inline-run detection, boundary trimming) read the precomputed `is_collapsible_ws_only`
/// and `newline_count` scalars below instead of re-scanning `raw` each time — the
/// same `multiline`-style trick `comment-as-span` used for `tsv_lang::Comment`. A
/// content `Text` is otherwise re-scanned ~10× per parent-element format, across the
/// analyze and build passes (which share no result). The flags cover the *whole-raw*
/// collapsible-whitespace and newline-count notions only; boundary / leading-trailing
/// / trimmed-substring predicates stay scan-based (they're first/last-char or
/// substring, already O(1) or rare).
#[derive(Debug, Clone)]
pub struct Text {
    /// Span of the raw text (entities preserved) in the host source; text via `raw`.
    pub raw_span: Span,
    /// Which entity decode `data()` applies, fixed at parse time by context.
    pub decoding: TextDecoding,
    pub span: Span,
    /// Precomputed at parse: `raw` is entirely [collapsible whitespace](is_collapsible_ws)
    /// `[ \t\n\r]`, or empty — equivalently
    /// `raw(source).trim_matches(is_collapsible_ws_char).is_empty()`.
    /// A non-breaking space (U+00A0 / U+202F), a form feed, or any other separator CSS does
    /// not collapse is template *content*, so it makes this `false`.
    ///
    /// Keyed on `raw`, not on the decoded `data`: an entity-encoded whitespace character
    /// (`&#9;`) is content here, where Svelte's `clean_nodes` — which tests `data` — calls it
    /// whitespace. That is deliberate and matches prettier (`node.raw || node.data`): rewriting
    /// an entity's bytes is a content edit, so the node is printed verbatim. It is still a
    /// *separator* rather than prose — it carries no word for a `fill` to pack — which is the
    /// question `Printer::is_separator_like_text` answers about `data` — asked through
    /// `Printer::text_is_separator_like`, which reads `raw` and decodes only where that could
    /// change the answer.
    pub is_collapsible_ws_only: bool,
    /// Precomputed count of `\n` in `raw`, **saturating at 2** — enough for every test
    /// the printer makes (`has_newline` = `>= 1`, blank line = `>= 2`).
    pub newline_count: u8,
}

/// `Text`'s two whitespace scalars over its raw bytes in one pass:
/// `(is_collapsible_ws_only, newline_count)`, the second saturating at 2 (the printer only
/// tests `== 0` / `< 2` / `>= 1` / `>= 2`). An empty raw is collapsible-whitespace-only.
///
/// The walk counts `\n` through the [collapsible](is_collapsible_ws) head; a text that
/// ends inside it is whitespace-only, and at the first content byte (never a `\n`) the
/// rest only has to be counted — [`capped_newline_count`] — until the count saturates.
/// The head is counted by weight ([`TEXT_WS_WEIGHT`]): its sum over `i` bytes is `i` plus
/// the head's `\n`s, so one table load answers both the class and the count.
#[inline]
fn text_ws_scalars(raw: &[u8]) -> (bool, u8) {
    let mut weight = 0usize;
    let mut i = 0;
    while i < raw.len() {
        let w = TEXT_WS_WEIGHT[usize::from(raw[i])];
        if w == 0 {
            return (false, capped_newline_count(&raw[i + 1..], weight - i));
        }
        weight += usize::from(w);
        i += 1;
    }
    (true, (weight - raw.len()).min(2) as u8)
}

/// [`text_ws_scalars`]' head weights, one per byte: 2 for `\n`, 1 for the rest of the
/// [`is_collapsible_ws`] class, 0 — content, ending the head — for every other byte.
const TEXT_WS_WEIGHT: [u8; 256] = {
    let mut t = [0; 256];
    let mut i = 0;
    while i < 256 {
        let b = i as u8;
        t[i] = if b == b'\n' {
            2
        } else if is_collapsible_ws(b) {
            1
        } else {
            0
        };
        i += 1;
    }
    t
};

/// `newlines` plus the `\n`s in `rest`, saturating at 2 — the count stops reading once it
/// saturates, and reads a word at a time ([`tsv_lang::swar::count_byte_up_to`]): a content
/// text is most of the bytes `Text::new` reads, and most of its words hold no `\n`.
///
/// Out of line: only a content text reaches it, and inlined, its word loop would take
/// `Text::new` — and the whitespace-only head every text walks — out of line with it.
#[inline(never)]
fn capped_newline_count(rest: &[u8], newlines: usize) -> u8 {
    if newlines >= 2 {
        return 2;
    }
    (newlines + tsv_lang::swar::count_byte_up_to(rest, b'\n', 2 - newlines)) as u8
}

/// Entity-decode context for a `Text` node, mirroring the decode the canonical
/// Svelte parser applies when it materializes `data` from `raw`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextDecoding {
    /// Fragment/template text — decode with text-content rules.
    Fragment,
    /// Attribute value, quoted or unquoted — decode with attribute-context rules
    /// (stricter semicolon handling for named entities).
    AttributeValue,
    /// No decode — `data` is identical to `raw` (raw-content element text).
    Raw,
}

impl TextDecoding {
    /// The context a decoding text's references are read in — attribute rules for
    /// [`TextDecoding::AttributeValue`], text-content rules otherwise ([`TextDecoding::Raw`]
    /// never decodes, so its answer is never asked).
    pub(crate) fn reference_context(self) -> crate::html::ReferenceContext {
        match self {
            Self::AttributeValue => crate::html::ReferenceContext::AttributeValue,
            Self::Fragment | Self::Raw => crate::html::ReferenceContext::Text,
        }
    }
}

impl Text {
    /// Construct a `Text`, precomputing the whitespace scalars from `raw_span`.
    /// `source` must be the host document `raw_span` was recorded against (the same
    /// document every later `raw(source)` reader passes), so the flags stay in sync
    /// with `raw` whether the node is standalone or embedded.
    pub fn new(raw_span: Span, decoding: TextDecoding, span: Span, source: &str) -> Self {
        // Bytes, not `extract`: both scalars are byte questions, so the `str` slice's
        // char-boundary checks buy nothing here.
        let (is_collapsible_ws_only, newline_count) =
            text_ws_scalars(&source.as_bytes()[raw_span.range()]);
        Text {
            raw_span,
            decoding,
            span,
            is_collapsible_ws_only,
            newline_count,
        }
    }

    /// Whether `raw` contains at least one `\n` (precomputed, source-free).
    #[inline]
    pub fn has_newline(&self) -> bool {
        self.newline_count >= 1
    }

    /// Raw text (entities preserved) — a sub-slice of `source`, no allocation.
    /// `source` must be the host document the spans were recorded against.
    pub fn raw<'s>(&self, source: &'s str) -> &'s str {
        self.raw_span.extract(source)
    }

    /// Decoded text (`&lt;` → `<`, `&#65;` → `A`), computed lazily from `raw`.
    ///
    /// Borrows `raw` when no `&` is present (no entity possible, decode is
    /// identity) or when the node's context applies no decode — see
    /// [`Self::data_is_raw`], which a hot caller holding `raw` asks inline instead.
    ///
    /// Out of line, and its decode colder still. The hot askers — the wire writer's text
    /// write — ask [`Self::data_is_raw`] inline and call this only for a text they cannot
    /// borrow, so inlining `data()` at its every caller would grow the binary for nothing on
    /// the format path; and fewer than one text in a hundred holds a `&`, so a call costs the
    /// borrowed answer's price, not the decoder's frame.
    #[inline(never)]
    pub fn data<'s>(&self, source: &'s str) -> Cow<'s, str> {
        let raw = self.raw(source);
        if self.data_is_raw(raw) {
            return Cow::Borrowed(raw);
        }
        Cow::Owned(decode_text_data(raw, self.decoding.reference_context()))
    }

    /// Whether [`Self::data`] is `raw` itself — `raw` being this node's own
    /// [`Self::raw`] — answered without building it: the node's context applies no
    /// decode, or `raw` holds no `&` for one to start at.
    #[inline]
    pub(crate) fn data_is_raw(&self, raw: &str) -> bool {
        // A raw made only of `[ \t\n\r]` holds no `&`, so the precomputed flag spares
        // `data()`'s callers the search on the indentation between tags. The wire writer
        // routes those texts to its whitespace window and never asks it of one.
        debug_assert!(!self.is_collapsible_ws_only || !raw.contains('&'));
        self.is_collapsible_ws_only || self.decoding == TextDecoding::Raw || !raw.contains('&')
    }
}

/// [`Text::data`]'s decode, for a raw that holds a `&`.
#[cold]
#[inline(never)]
fn decode_text_data(raw: &str, context: crate::html::ReferenceContext) -> String {
    // Owned whether or not a reference decoded: `data` is `Cow::Borrowed` exactly when
    // `data_is_raw` says so, a cheaper question than the decode.
    crate::html::decode_character_references(raw, context).into_owned()
}

/// Svelte ExpressionTag - {expression} in template
///
/// Represents a TypeScript/JS expression embedded in the template.
/// The expression is evaluated and its result is rendered.
#[derive(Debug, Clone)]
pub struct ExpressionTag<'arena> {
    pub expression: &'arena Expression<'arena>,
    pub span: Span,
}

/// Svelte Script block - `<script>` tag contents
///
/// Contains a TypeScript/JS program and metadata about the script tag.
/// The `context` field distinguishes between instance and module scripts.
#[derive(Debug, Clone)]
pub struct Script<'arena> {
    pub content: Program<'arena>,
    pub attributes: &'arena [AttributeNode<'arena>],
    pub context: ScriptContext,
    pub span: Span,
}

/// Script context type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ScriptContext {
    Default = 0, // <script>
    Module = 1,  // <script context="module">
}

impl ScriptContext {
    /// Returns the context string for JSON output
    #[inline]
    pub const fn as_str(self) -> &'static str {
        match self {
            ScriptContext::Default => "default",
            ScriptContext::Module => "module",
        }
    }
}

/// Svelte Style block - `<style>` tag contents
///
/// Stores the span of the entire `<style>` tag and the content span.
/// Style tag with parsed CSS content
#[derive(Debug, Clone)]
pub struct Style<'arena> {
    pub span: Span,         // Full <style>...</style> span
    pub content_span: Span, // Just the CSS text inside the tags
    pub attributes: &'arena [AttributeNode<'arena>],
    /// Parsed CSS stylesheet (nodes + value comments), bump-allocated in the
    /// shared document `Bump` (`tsv_css` is arena-native).
    pub css_stylesheet: CssStyleSheet<'arena>,
}

// Widths of the slice-multiplied Svelte AST enums and the tag every attribute value and
// template `{expr}` holds. Every variant stays inline by value: arena-boxing the fat
// ones for a smaller enum shrank the slice element but added a pointer-chase on hot
// format-read paths that cost more than the density win. The embedded TypeScript
// expressions are the other story — the TS parser has already arena-allocated each one,
// so the nodes hold them as `&'arena Expression` rather than copying 72 B out of that
// allocation (`docs/architecture.md` §Nested AST, the second density rule). `SnippetBlock`
// sets `FragmentNode`'s width. 64-bit only — pointers and slices are half-width on
// wasm32, a different layout.
#[cfg(all(test, target_pointer_width = "64"))]
const _: () = assert!(size_of::<FragmentNode<'static>>() == 120);
#[cfg(all(test, target_pointer_width = "64"))]
const _: () = assert!(size_of::<AttributeNode<'static>>() == 72);
#[cfg(all(test, target_pointer_width = "64"))]
const _: () = assert!(size_of::<ExpressionTag<'static>>() == 16);

#[cfg(test)]
mod tests {
    use super::{SpecialElementKind, SpecialElementTag};

    #[test]
    fn special_element_tag_from_name() {
        use SpecialElementTag::*;
        assert_eq!(
            SpecialElementTag::from_tag_name("svelte:head", false, false),
            Some(SvelteHead)
        );
        assert_eq!(
            SpecialElementTag::from_tag_name("svelte:boundary", false, false),
            Some(SvelteBoundary)
        );
        // `title` is special only inside <svelte:head> — the flag gates both arms.
        assert_eq!(
            SpecialElementTag::from_tag_name("title", true, false),
            Some(TitleElement)
        );
        assert_eq!(
            SpecialElementTag::from_tag_name("title", false, false),
            None
        );
        // `slot` is SlotElement normally, but a plain RegularElement (→ None) inside a
        // <template shadowrootmode>.
        assert_eq!(
            SpecialElementTag::from_tag_name("slot", false, false),
            Some(SlotElement)
        );
        assert_eq!(SpecialElementTag::from_tag_name("slot", false, true), None);
        // Unknown / regular tags are not special.
        assert_eq!(SpecialElementTag::from_tag_name("div", true, false), None);
        assert_eq!(
            SpecialElementTag::from_tag_name("svelte:unknown", false, false),
            None
        );
    }

    #[test]
    fn special_element_kind_is_block() {
        // Only the four document-binding elements are block.
        assert!(SpecialElementKind::SvelteHead.is_block());
        assert!(SpecialElementKind::SvelteWindow.is_block());
        assert!(SpecialElementKind::SvelteBody.is_block());
        assert!(SpecialElementKind::SvelteDocument.is_block());
        // The content/dynamic/error elements are inline.
        assert!(!SpecialElementKind::SlotElement.is_block());
        assert!(!SpecialElementKind::SvelteSelf.is_block());
        assert!(!SpecialElementKind::SvelteFragment.is_block());
        assert!(!SpecialElementKind::SvelteBoundary.is_block());
        assert!(!SpecialElementKind::TitleElement.is_block());
    }

    #[test]
    fn text_new_precomputes_whitespace_flags() {
        use super::{Span, Text, TextDecoding};
        // A `Text` whose `raw_span` covers the whole probe string.
        let mk = |raw: &str| {
            let span = Span {
                start: 0,
                end: raw.len() as u32,
            };
            Text::new(span, TextDecoding::Fragment, span, raw)
        };

        // `is_collapsible_ws_only`: collapsible (ASCII) whitespace only; empty counts true.
        assert!(mk("  \t\n ").is_collapsible_ws_only);
        assert!(mk("").is_collapsible_ws_only);
        // A non-breaking space (U+00A0) is content, not collapsible whitespace.
        assert!(!mk("\u{00A0}").is_collapsible_ws_only);
        assert!(!mk("a").is_collapsible_ws_only);

        // `newline_count` saturates at 2 (drives `has_newline`, and the printer's own
        // `newline_count >= 2` reads).
        assert_eq!(mk("a b").newline_count, 0);
        assert!(!mk("a b").has_newline());
        assert_eq!(mk("a\nb").newline_count, 1);
        assert!(mk("a\nb").has_newline());
        assert_eq!(mk("a\n\nb").newline_count, 2);
        // 3+ newlines still report the saturated 2.
        assert_eq!(mk("\n\n\n\n").newline_count, 2);
    }

    /// The two-pass model `Text::new`'s one-pass scalars must equal:
    /// `(is_collapsible_ws_only, newline_count)`.
    fn text_scalars_model(raw: &str) -> (bool, u8) {
        (
            raw.bytes().all(super::is_collapsible_ws),
            raw.bytes().filter(|&b| b == b'\n').take(2).count() as u8,
        )
    }

    /// `Text::new`'s scalars for `raw`, read both standalone and from inside a host document
    /// (a non-zero span start, content on both sides), each graded against the model.
    fn assert_text_scalars(raw: &str) {
        use super::{Span, Text, TextDecoding};
        let expected = text_scalars_model(raw);
        let prefix = "<p>a\n\n";
        for source in [raw.to_owned(), format!("{prefix}{raw}\n\nb</p>")] {
            let start = if source.len() == raw.len() {
                0
            } else {
                prefix.len()
            };
            let span = Span {
                start: start as u32,
                end: (start + raw.len()) as u32,
            };
            let text = Text::new(span, TextDecoding::Fragment, span, &source);
            assert_eq!(
                (text.is_collapsible_ws_only, text.newline_count),
                expected,
                "raw {raw:?} at {start}"
            );
        }
    }

    /// Every string over an alphabet covering each class the scan tells apart — the four
    /// collapsible bytes, content ASCII (`&` included), the separators the class excludes
    /// (NBSP, U+202F, form feed) and a multibyte letter — graded against the two-pass model:
    /// exhaustive to length 5, and to length 6 over its first six symbols (the four
    /// collapsible bytes, `&` and `a`).
    #[test]
    fn text_new_scalars_match_the_two_pass_model_exhaustively() {
        let alphabet: Vec<String> = [' ', '\t', '\n', '\r', '&', 'a', '\u{c}']
            .into_iter()
            .chain([0xA0, 0x202F, 0xE9].map(|c| char::from_u32(c).unwrap()))
            .map(String::from)
            .collect();
        let head = &alphabet[..6];
        let mut cases = 0usize;
        for (symbols, max_len) in [(&alphabet[..], 5), (head, 6)] {
            let mut digits: Vec<usize> = Vec::new();
            loop {
                let raw: String = digits.iter().map(|&d| symbols[d].as_str()).collect();
                assert_text_scalars(&raw);
                cases += 1;
                // Odometer over `symbols`, growing the length when every digit wraps.
                let mut k = 0;
                loop {
                    if k == digits.len() {
                        digits.push(0);
                        break;
                    }
                    digits[k] += 1;
                    if digits[k] < symbols.len() {
                        break;
                    }
                    digits[k] = 0;
                    k += 1;
                }
                if digits.len() > max_len {
                    break;
                }
            }
        }
        let expected: usize = (0..=5).map(|n| 10usize.pow(n)).sum::<usize>()
            + (0..=6).map(|n| 6usize.pow(n)).sum::<usize>();
        assert_eq!(cases, expected);
    }

    /// Long runs, past any word the scan might read at a time: a whitespace or content
    /// filler with the deciding byte — a content byte, `\n`, or a pair of `\n` — at every
    /// offset.
    #[test]
    fn text_new_scalars_match_the_two_pass_model_on_long_runs() {
        for len in [7, 8, 9, 15, 16, 17, 23, 24, 25, 31, 32, 33, 64, 65] {
            for filler in [b' ', b'\t', b'a'] {
                let base = vec![filler; len];
                assert_text_scalars(std::str::from_utf8(&base).unwrap());
                for i in 0..len {
                    for decider in [b'a', b'&', b'\n', b'\r', 0x0C] {
                        let mut bytes = base.clone();
                        bytes[i] = decider;
                        assert_text_scalars(std::str::from_utf8(&bytes).unwrap());
                    }
                    for j in i + 1..len {
                        let mut bytes = base.clone();
                        bytes[i] = b'\n';
                        bytes[j] = b'\n';
                        assert_text_scalars(std::str::from_utf8(&bytes).unwrap());
                        // A content byte between, before or after the pair.
                        for k in [0, usize::midpoint(i, j), len - 1] {
                            if k != i && k != j {
                                let mut mixed = bytes.clone();
                                mixed[k] = b'x';
                                assert_text_scalars(std::str::from_utf8(&mixed).unwrap());
                            }
                        }
                    }
                }
            }
        }
    }

    /// Long runs of a multibyte filler — bytes at and above 0x80 in every word — with one or
    /// two `\n` at every character offset, behind a content or a whitespace head.
    #[test]
    fn text_new_scalars_match_the_two_pass_model_on_multibyte_runs() {
        for filler in [0xE9, 0xA0, 0x202F].map(|c| char::from_u32(c).unwrap().to_string()) {
            for len in [4, 8, 12, 17, 33] {
                for head in ["", "a", "\n", " \t"] {
                    for i in 0..len {
                        for j in i..len {
                            let raw: String = std::iter::once(head)
                                .chain((0..len).map(|k| {
                                    if k == i || k == j {
                                        "\n"
                                    } else {
                                        filler.as_str()
                                    }
                                }))
                                .collect();
                            assert_text_scalars(&raw);
                        }
                    }
                }
            }
        }
    }

    /// `Text::data` against the pre-flag model — `Raw` borrows `raw`, otherwise decode iff a
    /// `&` is present — for every decoding, over whitespace-only, entity-bearing and empty
    /// raws: the same string, and borrowed exactly when the model borrows.
    #[test]
    fn text_data_matches_the_decode_model() {
        use super::{Span, Text, TextDecoding};
        use std::borrow::Cow;
        let nbsp = char::from_u32(0xA0).unwrap();
        let raws = [
            String::new(),
            " ".into(),
            "\n\t\t".into(),
            " \r\n \t".into(),
            "a".into(),
            "&".into(),
            "&amp;".into(),
            " &lt; ".into(),
            "&#9;".into(),
            "\n&#10;\n".into(),
            "a&b".into(),
            "&notit;".into(),
            format!("{nbsp}"),
            format!(" {nbsp}&amp;"),
        ];
        for decoding in [
            TextDecoding::Fragment,
            TextDecoding::AttributeValue,
            TextDecoding::Raw,
        ] {
            for raw in &raws {
                let source = format!("<p>{raw}</p>");
                let span = Span {
                    start: 3,
                    end: (3 + raw.len()) as u32,
                };
                let text = Text::new(span, decoding, span, &source);
                let expected: Cow<'_, str> = match decoding {
                    TextDecoding::Raw => Cow::Borrowed(raw),
                    _ if raw.contains('&') => Cow::Owned(
                        crate::html::decode_character_references(raw, decoding.reference_context())
                            .into_owned(),
                    ),
                    _ => Cow::Borrowed(raw),
                };
                let data = text.data(&source);
                assert_eq!(data, expected, "{decoding:?} {raw:?}");
                assert_eq!(
                    text.data_is_raw(text.raw(&source)),
                    matches!(expected, Cow::Borrowed(_)),
                    "{decoding:?} {raw:?}"
                );
                assert_eq!(
                    matches!(data, Cow::Borrowed(_)),
                    matches!(expected, Cow::Borrowed(_)),
                    "{decoding:?} {raw:?}"
                );
            }
        }
    }

    /// Svelte's `is_void` is the element set plus the `!doctype` declaration, which
    /// `crate::html::is_void_element` leaves out (no element) and Svelte matches in any ASCII case.
    #[test]
    fn svelte_void_adds_the_doctype_declaration() {
        use super::is_svelte_void;
        for void in ["br", "img", "!doctype", "!DOCTYPE", "!DocType"] {
            assert!(is_svelte_void(void), "{void:?}");
        }
        for not_void in ["div", "BR", "doctype", "!", "!doctypex", "!DOCTYPEX"] {
            assert!(!is_svelte_void(not_void), "{not_void:?}");
        }
        assert!(!crate::html::is_void_element("!doctype"));
    }

    /// Grade every packed [`TagFacts`](super::TagFacts) accessor against the pure predicate it
    /// encodes, over an alphabet covering each bit's positive and negative cases. This is the gate
    /// with power over the bit packing: a swapped constant or an accessor reading its neighbour's
    /// bit changes layout only on rare tags at rare widths, which no fixture or corpus diff can be
    /// relied on to see.
    #[test]
    fn tag_facts_bits_agree_with_the_pure_predicates() {
        use super::{ElementKind, TagFacts, is_component_name, is_svelte_void};
        let probes = [
            // block members (hr is also void; pre is also ws-sensitive)
            "div",
            "p",
            "h1",
            "menu",
            // whitespace-collapsing containers (WS_COLLAPSING, all 8) + near-miss non-members
            "table",
            "select",
            "tr",
            "tbody",
            "thead",
            "tfoot",
            "colgroup",
            "datalist",
            "optgroup",
            "ul",
            "li",
            "pre",
            "hr",
            "blockquote",
            // void members (incl. the case-insensitive !doctype family; wbr is the line-break
            // bit's decided-against near-miss — a break OPPORTUNITY, so it flows)
            "br",
            "img",
            "input",
            "wbr",
            "command",
            "keygen",
            "!doctype",
            "!DOCTYPE",
            "!DocType",
            "!",
            "!doctypex",
            "!DOCTYPEX",
            // foreign members (SVG incl. camelCase + hyphenated; MathML)
            "svg",
            "circle",
            "foreignObject",
            "color-profile",
            "math",
            "annotation-xml",
            "mi",
            // the name-compare bits
            "script",
            "style",
            "template",
            "textarea",
            // component-shaped names (incl. non-ASCII uppercase initials — Greek, Latin, Cyrillic)
            "Button",
            "MyComponent",
            "svelte:head",
            "svelte:component",
            "foo:bar",
            "Foo:bar",
            "foo.bar",
            "foo.bar:baz",
            "Foo.bar:",
            ":",
            ".",
            "Div",
            "DIV",
            "Δcomp",
            "Écomp",
            "Яcomp",
            "étoile",
            // near-misses and odd inputs
            "span",
            "td",
            "divx",
            "di",
            "xdiv",
            "doctype",
            "é",
            "ünknown",
            "",
        ];
        for tag in probes {
            let facts = TagFacts::compute(tag);
            assert_eq!(
                facts.is_block(),
                crate::html::is_block_element(tag),
                "block: {tag:?}"
            );
            assert_eq!(facts.is_void(), is_svelte_void(tag), "void: {tag:?}");
            assert_eq!(
                facts.is_foreign(),
                crate::html::is_foreign_element(tag),
                "foreign: {tag:?}"
            );
            assert_eq!(
                facts.is_component_name(),
                is_component_name(tag),
                "component name: {tag:?}"
            );
            assert_eq!(
                facts.element_kind(),
                if is_component_name(tag) {
                    ElementKind::Component
                } else {
                    ElementKind::Html
                },
                "element kind: {tag:?}"
            );
            assert_eq!(
                facts.is_namespaced(),
                tag.contains(':'),
                "namespaced: {tag:?}"
            );
            assert_eq!(facts.is_style(), tag == "style", "style: {tag:?}");
            assert_eq!(
                facts.is_raw_text(),
                tag == "script" || tag == "style",
                "raw text: {tag:?}"
            );
            assert_eq!(facts.is_template(), tag == "template", "template: {tag:?}");
            assert_eq!(
                facts.is_ws_sensitive(),
                crate::html::preserves_whitespace(tag),
                "ws-sensitive: {tag:?}"
            );
            assert_eq!(
                facts.collapses_child_whitespace(),
                crate::html::collapses_child_whitespace(tag),
                "ws-collapsing: {tag:?}"
            );
            assert_eq!(
                facts.is_declaration(),
                tag.starts_with('!'),
                "declaration: {tag:?}"
            );
            assert_eq!(
                facts.is_line_break(),
                crate::html::is_line_break_element(tag),
                "line break: {tag:?}"
            );
        }
    }
}

#[cfg(test)]
mod lang_attribute_tests {
    use super::EmbeddedLang;

    /// The reader's answer for one opening tag, read through the two positions that carry a
    /// non-trivial allowlist — `<style>`'s (`css`) and `<script>`'s (the JS/TS family).
    ///
    /// Goes through a real parse rather than hand-built nodes: `lang_attribute` reads the
    /// *decoded* `Text::data`, and a synthetic attribute list would skip the decode the rule
    /// is partly about.
    fn langs(open_tag: &str) -> (bool, bool) {
        let tag = if open_tag.starts_with("<style") {
            "style"
        } else {
            "script"
        };
        // Nested rather than top-level: the reader is position-independent, and nested
        // raw-text content is parsed by nobody, so the body need not be valid TS/CSS.
        let src = format!("<div>{open_tag}x</{tag}></div>");
        let arena = bumpalo::Bump::new();
        let ast = crate::__private::parse(&src, &arena).expect("parses");
        let attrs =
            raw_text_attributes(ast.fragment.nodes, tag, &src).expect("the raw-text element");
        (
            EmbeddedLang::Style.is_frozen(attrs, &src),
            EmbeddedLang::Script.is_frozen(attrs, &src),
        )
    }

    /// The attribute list of the first `<tag>` element in the tree.
    fn raw_text_attributes<'a>(
        nodes: &'a [super::FragmentNode<'a>],
        tag: &str,
        source: &str,
    ) -> Option<&'a [super::AttributeNode<'a>]> {
        nodes.iter().find_map(|node| match node {
            super::FragmentNode::Element(el) if el.name(source) == tag => Some(el.attributes),
            super::FragmentNode::Element(el) => raw_text_attributes(el.fragment.nodes, tag, source),
            _ => None,
        })
    }

    #[test]
    fn an_absent_or_matching_lang_is_native() {
        assert!(!langs("<style>").0, "<style>");
        assert!(!langs("<style lang=\"css\">").0, "<style lang=\"css\">");
        assert!(!langs("<script>").1, "<script>");
        assert!(!langs("<script lang=\"ts\">").1, "<script lang=\"ts\">");
    }

    #[test]
    fn the_value_is_trimmed_and_text_stripped() {
        assert!(!langs("<style lang=\" css \">").0, "<style lang=\" css \">");
        assert!(
            !langs("<style type=\"text/css\">").0,
            "<style type=\"text/css\">"
        );
        assert!(
            !langs("<script type=\"text/ts\">").1,
            "<script type=\"text/ts\">"
        );
    }

    /// The decoded value, never the raw bytes — `lang="&#99;ss"` is css to the formatter
    /// (the *wire*'s `this.ts` question reads raw, and is a different reader on purpose).
    #[test]
    fn the_value_is_decoded() {
        assert!(
            !langs("<style lang=\"&#99;ss\">").0,
            "<style lang=\"&#99;ss\">"
        );
        assert!(
            !langs("<script lang=\"&#116;s\">").1,
            "<script lang=\"&#116;s\">"
        );
    }

    /// `lang` outranks `type` whatever their source order — prettier's `getLangAttribute`
    /// is `lang || type`. A first-hit-in-source-order read answered `<style type="text/css"
    /// lang="scss">` "css" and handed a scss body to the CSS printer.
    #[test]
    fn lang_outranks_type_in_either_order() {
        assert!(
            langs("<style type=\"text/css\" lang=\"scss\">").0,
            "<style type=\"text/css\" lang=\"scss\">"
        );
        assert!(
            langs("<style lang=\"scss\" type=\"text/css\">").0,
            "<style lang=\"scss\" type=\"text/css\">"
        );
        assert!(
            !langs("<script type=\"text/coffeescript\" lang=\"ts\">").1,
            "<script type=\"text/coffeescript\" lang=\"ts\">"
        );
        assert!(
            !langs("<script lang=\"ts\" type=\"text/coffeescript\">").1,
            "<script lang=\"ts\" type=\"text/coffeescript\">"
        );
    }

    /// An empty value names no language and reads as *absent* — so it neither freezes on its
    /// own nor shadows the `type` beside it.
    #[test]
    fn an_empty_value_names_nothing() {
        assert!(!langs("<style lang=\"\">").0, "<style lang=\"\">");
        assert!(!langs("<script lang=\"\">").1, "<script lang=\"\">");
        assert!(
            langs("<style lang=\"\" type=\"text/less\">").0,
            "<style lang=\"\" type=\"text/less\">"
        );
        assert!(
            langs("<style type=\"text/less\" lang=\"\">").0,
            "<style type=\"text/less\" lang=\"\">"
        );
    }

    /// A value-less attribute names nothing either: there is no `Text` part to read.
    #[test]
    fn a_boolean_attribute_names_nothing() {
        assert!(!langs("<style lang>").0, "<style lang>");
        assert!(!langs("<script lang>").1, "<script lang>");
    }

    /// `<script>` takes the whole JS/TS family — the bare language names plus the living
    /// JavaScript MIME essences. The set is drawn where tsv's PRINTER stops, not where
    /// Svelte's parser switches grammars, and `type="module"` names JS rather than a
    /// language of its own.
    #[test]
    fn the_script_set_is_the_js_ts_family() {
        for tag in [
            "<script lang=\"js\">",
            "<script lang=\"javascript\">",
            "<script lang=\"typescript\">",
            "<script type=\"module\">",
            "<script type=\"text/javascript\">",
            "<script type=\"text/ecmascript\">",
            "<script type=\"application/javascript\">",
            "<script type=\"application/ecmascript\">",
        ] {
            assert!(!langs(tag).1, "{tag}");
        }
    }

    #[test]
    fn any_other_name_is_foreign() {
        assert!(langs("<style lang=\"less\">").0, "<style lang=\"less\">");
        assert!(langs("<style lang=\"scss\">").0, "<style lang=\"scss\">");
        assert!(langs("<style lang=\"sass\">").0, "<style lang=\"sass\">");
        // What tsv genuinely cannot print, JSON included: prettier reaches for its JSON
        // parser there and hard-errors on a body that is not JSON. The dead MIME essences
        // freeze with them — mimesniff still lists them, tsv deliberately does not.
        for tag in [
            "<script lang=\"coffee\">",
            "<script type=\"text/coffeescript\">",
            "<script type=\"application/json\">",
            "<script type=\"application/ld+json\">",
            "<script type=\"importmap\">",
            "<script type=\"text/jscript\">",
            "<script type=\"text/livescript\">",
            "<script type=\"application/x-javascript\">",
            "<script type=\"text/javascript1.5\">",
        ] {
            assert!(langs(tag).1, "{tag}");
        }
    }
}

#[cfg(test)]
mod collapsible_ws_tests {
    use super::*;

    /// Every arrangement of the four members, a non-member ASCII space relative (`<FF>`), a
    /// multi-byte space (`<NBSP>`), content, and the two ASCII controls at the ends of the
    /// range (`<NUL>`, `<DEL>`), zero to four pieces long — the axis a corpus samples
    /// arbitrarily and a byte walk must get right at every offset.
    fn for_every_arrangement(check: impl FnMut(&str)) {
        let nul = char::from(0_u8).to_string();
        let del = char::from(0x7f_u8).to_string();
        let pieces = [
            " ", "\t", "\n", "\r", "\u{c}", "\u{a0}", "x", "é", &nul, &del,
        ];
        crate::test_support::for_every_arrangement(&pieces, 4, check);
    }

    /// The byte trims agree with the char-predicate searchers.
    #[test]
    fn byte_trims_match_the_searchers() {
        for_every_arrangement(|s| {
            assert_eq!(
                trim_start_collapsible_ws(s),
                s.trim_start_matches(is_collapsible_ws_char),
                "{s:?}"
            );
            assert_eq!(
                trim_end_collapsible_ws(s),
                s.trim_end_matches(is_collapsible_ws_char),
                "{s:?}"
            );
            assert_eq!(
                text_edge_ws(s, true).len(),
                collapsible_ws_prefix_len(s),
                "{s:?}"
            );
            assert_eq!(
                text_edge_ws(s, false).len(),
                collapsible_ws_suffix_len(s),
                "{s:?}"
            );
        });
    }

    /// The edge newline count is the `\n` count of the edge run [`text_edge_ws`] delimits, at
    /// both ends — a `\r` (alone or before a `\n`) is edge whitespace but no newline, and a
    /// form feed or a no-break space ends the edge like content.
    #[test]
    fn edge_newlines_match_the_edge_run() {
        for_every_arrangement(|s| {
            for leading in [true, false] {
                assert_eq!(
                    text_edge_newlines(s, leading),
                    text_edge_ws(s, leading).matches('\n').count(),
                    "{s:?} leading={leading}"
                );
            }
        });
        assert_eq!(text_edge_newlines("\r\n\r\n\tx", true), 2);
        assert_eq!(text_edge_newlines("x\n\t\r\n  ", false), 2);
        assert_eq!(text_edge_newlines("\n\u{c}\nx", true), 1);
        assert_eq!(text_edge_newlines("x\n\u{a0}\n", false), 1);
        assert_eq!(text_edge_newlines("\n\n", true), 2);
        assert_eq!(text_edge_newlines("", false), 0);
    }

    /// The byte splitter yields exactly the words `split(is_collapsible_ws_char)` yields with
    /// the empties dropped.
    #[test]
    fn byte_split_matches_the_searcher() {
        for_every_arrangement(|s| {
            let words: Vec<&str> = split_collapsible_ws(s).collect();
            let reference: Vec<&str> = s
                .split(is_collapsible_ws_char)
                .filter(|w| !w.is_empty())
                .collect();
            assert_eq!(words, reference, "{s:?}");
        });
    }

    /// The range splitter names exactly the words the slice splitter yields, each range
    /// extracting to its word and flagged ASCII exactly when the word is — which, for a word,
    /// is exactly when it holds no byte a width depends on.
    #[test]
    fn word_ranges_match_the_slice_split() {
        for_every_arrangement(|s| {
            let words: Vec<&str> = split_collapsible_ws(s).collect();
            let ranged: Vec<&str> = collapsible_word_ranges(s)
                .map(|word| {
                    let text = word.extract(s);
                    assert_eq!(word.is_ascii, text.is_ascii(), "{s:?} word {text:?}");
                    assert_eq!(
                        word.is_ascii,
                        !text.bytes().any(tsv_lang::printing::is_width_relevant),
                        "{s:?} word {text:?}"
                    );
                    text
                })
                .collect();
            assert_eq!(ranged, words, "{s:?}");
        });
    }
}