tsv_ts 0.8.0

TypeScript/JS formatter, type stripper and acorn-compatible parser — 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
// List- and body-level comment emitters.
//
// These handle comments across a member/element list or a body: leading/trailing
// comments with blank-line preservation, the open-delimiter trailing-comment
// divergence (delimiter-line prefix), empty-container comments, signature/body
// comment splitting, inline-block comment runs, and comma emission in forced-
// multiline lists.

use super::{CommentVec, LeadingGlue, Printer, TrailingLineRef};
use crate::ast;
use crate::printer::statements::TerminatorGap;
use crate::printer::{next_printed_stmt, next_printed_stmt_start, statement_gap_floor};
use tsv_lang::Span;
use tsv_lang::comments_in_source_after_comment;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::arena::DocId;

/// Which side of an inline list-position block comment its separating space sits on —
/// the one axis [`Printer::inline_block_comment_doc`]'s two callers disagree on.
#[derive(Clone, Copy, PartialEq, Eq)]
enum InlineBlockSide {
    /// `/*content*/ ` — the comment leads the item after it.
    Leading,
    /// ` /*content*/` — the comment trails the item before it.
    Trailing,
}

/// How a separator binds the comments in its gap — the two per-separator axes
/// [`Printer::push_gap_comments`]'s callers state (each explained there).
#[derive(Clone, Copy)]
pub(crate) struct GapBinding {
    /// A same-line block comment trails AFTER the separator rather than staying before it.
    pub(crate) block_after: bool,
    /// An author blank line above a deferred own-line comment survives the separator.
    pub(crate) preserve_blank: bool,
}

/// How a separator gap's deferred (own-line) run renders — the axis
/// [`Printer::push_gap_comments`]'s callers name.
#[derive(Clone, Copy)]
pub(crate) enum GapDeferral {
    /// Real breaks into and inside the run — sound only where the caller's own break
    /// immediately follows the returned docs (a list joiner's hardline, the for
    /// header's `line`), closing the run's last line before anything else can queue a
    /// `line_suffix`. The doc is the break INTO the run; breaks within it are the
    /// shared site's `hardline`. A run the author GLUED onto one line keeps that line —
    /// prettier's answer at every gap this variant reaches.
    Break(DocId),
    /// The run rides in `line_suffix` docs, EVERY member carrying its break inside,
    /// dedented this many levels to the flushing construct's level
    /// ([`Printer::build_clause_tail_comment_doc`]) — the clause-body statement tail,
    /// whose last line stays open to the enclosing construct, where a later gap's
    /// deferred `//` must meet the run in source order at the flush
    /// (`doc/arena_render_suffix.rs` owes the separator between them). ⚠️ Author gluing
    /// does NOT survive here — the OPPOSITE answer to `Break`, deliberately, for the
    /// reason stated at [`Printer::push_gap_comments`].
    LineSuffix(u8),
}

/// Which blank-line rule a comma-separated list's separator follows.
///
/// Prettier asks two different questions here, and a list belongs to exactly one of them —
/// so the caller names its kind rather than passing a bare "preserve?" bool that cannot say
/// which rule it meant. The split is not cosmetic: the two disagree precisely when the comma
/// and the blank line sit on different lines.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum BlankRule {
    /// The list has no blank-preservation rule; the separator is a plain hardline.
    None,
    /// Prettier's `isNextLineEmpty` — measured from the **element's end**, so the blank must
    /// begin on the line that element ends on. Params, call arguments, object properties:
    /// prettier emits a `hardline` there, so a blank also forces the list to break.
    NextLineEmpty,
    /// Prettier's `isLineAfterElementEmpty` — advance to the **comma** first, then measure.
    /// Arrays and tuples: prettier emits a `softline`, so a blank never forces a break, and a
    /// blank before the comma is not preserved.
    AfterComma,
}

/// What follows a member in its body, for [`Printer::push_member_trailing_run`].
///
/// The `floor` is the gap's slot floor — where the leads-next test
/// ([`Printer::comment_leads_next_item`]) opens — and it is a **per-family fact**, not a
/// preference, so the caller states it rather than the shared walk guessing: a class body
/// steps past the stray `;`s that print nothing (`class_member_gap_floor`), while an
/// interface member's own span already covers its separator. Same shape and same reason as
/// [`BlankRule`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum MemberGap {
    /// A next member starts at `start`; the leads-next test opens at `floor`.
    Next { floor: u32, start: u32 },
    /// Nothing prints after this member in the body, so nothing can be led and the claim
    /// runs to `list_end` — the body's end, which only this arm has any use for, hence its
    /// place here rather than in the call's signature.
    Last { list_end: u32 },
}

/// How a brace container decides a standalone block comment is **glued to what follows**
/// ([`Printer::has_standalone_block_comment`]).
///
/// The leading half of that question is one rule everywhere — the source
/// ([`Printer::comment_follows_content_on_its_line`]). The trailing half is not, because
/// prettier genuinely answers it differently for the two families, so the caller names its
/// rule rather than inheriting one. Same shape and same reason as [`BlankRule`], and as the
/// union-vs-intersection split [`Printer::is_own_line_comment`] carries.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum StandaloneGlue {
    /// The SOURCE reading (the glue half is [`Printer::comment_hugs_next`], reached through
    /// the shared [`Printer::block_comment_owns_its_line`]): anything after the `*/` on
    /// that line glues the comment, the container's own comma included.
    /// The **object literal** and **object pattern**, whose separator is re-emitted
    /// structure outside every property span — so `{ a: 1⏎/* c */,⏎b: 2 }` collapses
    /// inline, as prettier collapses it, instead of expanding on pass 1 and collapsing on
    /// pass 2. A **dangling** comment — none of `item_spans` starts after it — is exempt:
    /// the closer pulled onto its line is not glue, the same carve-out the bracket list's
    /// no-element-follows arm makes.
    Source,
    /// Only an ITEM starting on the comment's line glues it; the separator does not. The
    /// **type literal**, and this is prettier's own answer rather than a residual: it
    /// expands `type T = { a: A⏎/* c */,⏎b: B }` where it collapses the object literal
    /// written the same way. The mechanism is that a TS member's range swallows its own
    /// `;`/`,` terminator, so a comment before it is *inside* the member and never reaches
    /// prettier's container gate at all — an item-start reading is what reproduces that
    /// from the outside.
    ItemStart,
}

impl<'a> Printer<'a> {
    /// Build the leading-comment run over `[start, end)` for a list whose comments have
    /// forced it multiline (tuples, type params/args, function-type params, unions, the
    /// bracket-break shell, the broken cast).
    ///
    /// A thin adapter over the shared leading-comment emitter
    /// ([`Printer::push_leading_comment_run`]), so the separator after each comment
    /// follows prettier's `printLeadingComment` (space / soft `line` / hardline, keyed on
    /// the source around *that* comment, never on where `end` is).
    ///
    /// `skip_delim` drops the comments sharing `pos`'s source line: they were already
    /// emitted as a trailing prefix on the opening delimiter's line (see
    /// [`Self::delimiter_line_comment_prefix`]), so emitting them here too would
    /// **duplicate** them. Pass the `Option<u32>` that helper returns — gated to the list's
    /// first element, `None` for the rest, and `None` where no delimiter is involved.
    pub(in crate::printer) fn build_leading_comments_multiline(
        &self,
        start: u32,
        end: u32,
        skip_delim: Option<u32>,
    ) -> DocBuf {
        let mut parts = DocBuf::new();
        self.push_leading_comment_run(
            &mut parts,
            self.comments_to_emit_between(start, end)
                .filter(|c| !skip_delim.is_some_and(|pos| self.comment_on_delimiter_line(pos, c))),
            end,
            LeadingGlue::Adjacent,
        );
        parts
    }

    /// Assemble one **element** of an array-like list: its leading-comment run plus the
    /// element, wrapped in a single `group`.
    ///
    /// The group is what lets a leading comment's soft `line` (prettier's
    /// `printLeadingComment`) be measured against *this element alone* and collapse
    /// (`/* c1 */ /* c2 */ a`) even though the list itself is broken. Prettier's
    /// `printArrayElements` (`src/language-js/print/array.js`) does the same — it pushes
    /// `group(print())` per element and `print()` carries the element's leading comments —
    /// and array literals, array patterns, and tuple types all route through it. A line
    /// comment (or an author blank line) in the run puts a `hardline` inside the group, so
    /// it breaks and the element drops below, also matching prettier.
    ///
    /// This grouping is what separates the array family from the params family: function /
    /// type-parameter / type-argument / call-argument lists use a bare `join([",", line])`
    /// with **no** per-element group, so the identical soft `line` rides the broken outer
    /// group and breaks. That one fact predicts the layout at every one of those sites —
    /// don't re-derive it. See conformance_prettier_ts_comments.md §Comment relocation.
    ///
    /// A list with holes passes only its real elements here; a hole carries no comments and
    /// takes no group.
    pub(crate) fn build_list_element_group(&self, mut leading: DocBuf, element: DocId) -> DocId {
        let d = self.d();
        leading.push(element);
        d.group(d.concat(&leading))
    }

    /// [`Self::build_list_element_group`] for a caller holding the element's leading
    /// comments as a list rather than a range — the array literal and array pattern, whose
    /// per-element filter (which same-line block comments trail the *previous* element
    /// across its comma) is too specific to express as a range.
    ///
    /// Builds the run here so the separator policy every array-family element shares
    /// (`LeadingGlue::Adjacent`, no continuation indent) is stated once rather than at each
    /// call. The range-holding sibling is
    /// [`Self::build_leading_comments_multiline`].
    pub(crate) fn build_list_element_group_from_comments<'c>(
        &self,
        comments: impl Iterator<Item = &'c ast::Comment>,
        element_start: u32,
        element: DocId,
    ) -> DocId {
        let mut leading = DocBuf::new();
        self.push_leading_comment_run(&mut leading, comments, element_start, LeadingGlue::Adjacent);
        self.build_list_element_group(leading, element)
    }

    /// Build the docs for a gap that FOLLOWS a printed item and runs to the next printed
    /// token: the trailing run inline behind the item, everything after it on its own line.
    ///
    /// **One ordered pass**, because the two outcomes interleave: `f(a⏎, /* c1 */⏎/* c2 */)`
    /// trails `c1` on the item's line and gives `c2` its own, and two buffers appended in a
    /// fixed order print them REVERSED.
    ///
    /// Which comments TRAIL is [`Printer::closer_trailing_comment_run`], taken as a PREFIX
    /// ([`Printer::closer_trailing_run_end`] is its boundary), and the run stops at the
    /// first `//` since nothing may share a line comment's line. A **block** takes the
    /// SOURCE reading, because an `is_same_line(start, …)` one is blind to every byte no
    /// item span covers — above all the list's own comma, which the author can push onto
    /// its own line (`[T⏎, /* c */]`), leaving the comment on a line it never had
    /// (`docs/comments.md` §Own-line-ness is a SOURCE question). A **line** comment keeps
    /// the item anchor, the sanctioned divergence that walk carries.
    ///
    /// ⚠️ **Three gap SHAPES share this walk, and the reading is sound at all three even
    /// though it was chosen for one.** `start` is never an opening delimiter — it is the
    /// end of something printed — so "does content precede this comment on its line" is the
    /// same question at a **closer** gap (a last item→`]`/`>`/`)`), at the **delimiter** gap
    /// after a cast's `>`, and at the **operator** gap before a union's `|`. Only the first
    /// can OBSERVE the difference: the two readings part exactly where text no item span
    /// covers sits on the comment's line, and a closer gap holds the list's own comma
    /// (deleted under `trailingComma: 'none'`) while the other two hold nothing but trivia.
    /// The one byte that can reach them is a preceding comment's `*/` — and a comment the
    /// source reading claims for *that* reason is GLUED to its predecessor, so the trailing
    /// arm and the own-line arm's glue branch emit the identical ` ` + comment. **The two
    /// arms agree on exactly the set the readings disagree about**, which is what makes one
    /// walk sound at all three shapes; either mechanism alone already prints
    /// `| A /* a⏎b */ /* c */⏎// d⏎| B` the way prettier does (the delimiter reading with no
    /// glue arm — the state before this seam was unified — split a pair the author wrote on
    /// one line, and that was a real divergence). A gap whose anchor genuinely IS the
    /// delimiter keeps the delimiter reading and does not belong here
    /// ([`Self::delimiter_line_comment_prefix`]'s question, not this walk's).
    ///
    /// Used wherever such a gap is already broken across lines: the tuple, type
    /// parameters and arguments, both parameter lists, the union's leading-`|` form,
    /// and the angle-bracket cast.
    ///
    /// The trailing run's **line** comment rides `line_suffix` (zero width, prettier's
    /// `lineSuffix`), a block stays inline ([`Self::build_trailing_comment_doc`]). The
    /// suffix flushes at the layout's own following hardline, so the bytes are identical
    /// to an inline emission — except when the ELEMENT's doc already ends in a deferred
    /// `//` (a stripped shell's comment): an inline `//` here lands AHEAD of that
    /// pending suffix, which then flushes welded behind it (`a | b // inj // c2`,
    /// reordered and reparsing as one comment). Deferred, the two meet the flush in
    /// source order and the run separator breaks between them
    /// (`doc/arena_render_suffix.rs`). Sound because every caller's separator lands on a
    /// new line — the same condition the inline emission always required.
    pub(crate) fn build_trailing_gap_comments(&self, start: u32, end: u32) -> DocBuf {
        let mut parts = DocBuf::new();
        let run_end = self.closer_trailing_run_end(start, end);
        let mut prev_end = start;
        // The comment emitted last, for the glue question in the own-line arm.
        let mut prev_comment: Option<&ast::Comment> = None;
        for comment in self.comments_to_emit_between(start, end) {
            if comment.span.end <= run_end {
                parts.push(self.build_trailing_comment_doc(comment));
            } else {
                // Own line comment (block or line) — unless the author GLUED it to the
                // previous one, which keeps that line. Otherwise an author blank line
                // before it (`elem⏎⏎/* c */` before the closing delimiter) is preserved:
                // prettier keeps one blank in every list position (tuple, function/-type
                // params, signatures, type args/params).
                self.push_trailing_run_separator(
                    &mut parts,
                    prev_comment,
                    prev_end,
                    comment.span.start,
                );
                parts.push(self.build_comment_doc(comment));
            }
            prev_end = comment.span.end;
            prev_comment = Some(comment);
        }
        parts
    }
    /// True when a block comment in the LAST item→closer gap `(start, end)` owns its line,
    /// so the list must open around it — the trailing counterpart of the leading-run walk
    /// ([`Printer::has_leading_own_line_comment_in_params`]), asked by the value-level
    /// parameter list ([`Printer::has_trailing_line_comment_in_params`]) and the type-level
    /// one (`type_params_force_multiline`).
    ///
    /// The classification is the shared one ([`Printer::block_comment_owns_its_line`]) with
    /// `item_follows: false`: no item is left to lead, so the closer sharing the comment's
    /// line is not glue and the predicate reduces to its leading half — nothing before the
    /// `/*` on that line. That half is what the gap's own comma defeats: under
    /// `trailingComma: 'none'` the comma is never re-emitted, and an `is_same_line(item_end,
    /// …)` reading calls a comment glued to it own-line and opens a list that fits
    /// (`docs/comments.md` §Own-line-ness is a SOURCE question).
    ///
    /// Line comments in the same position are detected separately — they always force the
    /// break, wherever on the line they sit.
    pub(crate) fn has_own_line_block_comment_before_closer(&self, start: u32, end: u32) -> bool {
        self.comments_on_page_between(start, end)
            .any(|c| c.is_block && self.block_comment_owns_its_line(c, false))
    }

    /// Check if there's a block comment on its own line within a container.
    ///
    /// A "standalone" block comment starts a line of its own in SOURCE
    /// ([`Printer::comment_follows_content_on_its_line`]) and is not glued to what follows
    /// it, under the caller's [`StandaloneGlue`] rule. Used to force multiline formatting
    /// for objects/type literals.
    ///
    /// The [`StandaloneGlue::Source`] arm is the shared classification
    /// ([`Printer::block_comment_owns_its_line`], which carries the argument), the same one
    /// the bracketed-list gate ([`Printer::has_own_line_block_comments_in_bracket_list`])
    /// and the element→comma seam ask, so the three cannot disagree about one gap. The
    /// [`StandaloneGlue::ItemStart`] arm shares only the leading half — the enum's doc
    /// carries why the type literal parts ways on the other.
    pub(crate) fn has_standalone_block_comment(
        &self,
        container_start: u32,
        container_end: u32,
        item_spans: &[Span],
        glue: StandaloneGlue,
    ) -> bool {
        self.comments_on_page_between(container_start, container_end)
            .any(|c| {
                if !c.is_block {
                    return false; // Line comments handled separately
                }
                match glue {
                    StandaloneGlue::Source => {
                        // `>=` for the same reason the bracket list takes it: an item
                        // glued to the comment starts exactly where it ends.
                        let item_follows = item_spans.iter().any(|s| s.start >= c.span.end);
                        self.block_comment_owns_its_line(c, item_follows)
                    }
                    // The leading half is shared; only the glue half differs. An item
                    // *after* the comment shares its line when the comment's end and the
                    // item's start match (`/* c */ item`); such a comment leads that item
                    // inline and forces nothing. `is_same_line` must take its earlier
                    // position first — the helper returns false for out-of-order args.
                    StandaloneGlue::ItemStart => {
                        !self.comment_follows_content_on_its_line(c)
                            && !item_spans
                                .iter()
                                .any(|s| self.is_same_line(c.span.end, s.start))
                    }
                }
            })
    }

    /// Whether the construct spanning `[span_start, span_end)` ends its doc with a **line
    /// comment** rather than with its `;` — the case where its terminator gap held one and
    /// [`Self::push_semicolon_with_gap_comments`] deferred it past the `;`, onto a line of its
    /// own.
    ///
    /// A caller that trails a same-line comment on this construct has to ask, because the
    /// anchor for "same line" is the `;`'s position in **source** while what the comment
    /// would actually land next to is the doc's **last line**. When the two differ, an
    /// appended block is welded onto the line comment (`// c /* b */`) — the block becomes
    /// text of the comment and is lost.
    ///
    /// Keyed on a **terminator the construct's own doc re-prints**, which is what puts the
    /// deferred comment behind it: the statement / class-member `;`, and a type member's
    /// separator — `;` **or** `,`, since tsv normalizes either to the `;` the member doc
    /// emits ([`Printer::push_comments_around_semicolon`]). Reading only `;` here left
    /// the comma authoring welding (`a: A // c1⏎, // c2` → `a: A; // c1 // c2`, the second
    /// `//` becoming text of the first) at the interface and type-literal walks — the very
    /// merge this predicate exists to prevent. A `}` / element-list `,` is NOT this: there
    /// the separator is re-emitted by the CONTAINER's seam, outside the item's doc, so the
    /// item ends where its source does and its same-line run still trails — and no such
    /// caller asks this question anyway (every call site is a statement or member-body
    /// walk). Keyed on a **line** comment because only a `//` runs to end of line; a
    /// deferred block leaves the line open.
    pub(crate) fn terminator_defers_line_comment(&self, span_start: u32, span_end: u32) -> bool {
        self.terminator_gap_last_comment(span_start, span_end)
            .is_some_and(|last| !last.is_block)
    }

    /// Whether the construct's doc ends with ANY deferred comment — the widened kind
    /// axis of [`Self::terminator_defers_line_comment`]: a same-line `//` defers, and
    /// so does an **own-line** comment of either kind (the terminator gap floats those
    /// out through `line_suffix` — [`Self::push_gap_comments`],
    /// [`Printer::split_terminator_gap_comments`]). Only a same-line **block** stays
    /// out: it prints as real text after the `;`, closing nothing.
    ///
    /// Asked by a FOLLOWING gap that must decide whether its own anchor-line comments
    /// can render inline (nothing pending — an inline block keeps its width and its
    /// line) or must ride `line_suffix` too, so the two runs meet the flush in source
    /// order (`GapCommentRun::Dangling` in `statements/control_flow`).
    pub(crate) fn terminator_defers_comment(&self, span_start: u32, span_end: u32) -> bool {
        self.terminator_gap_last_comment(span_start, span_end)
            .is_some_and(|last| {
                !last.is_block || !self.comment_on_gap_anchor_line(span_start, last)
            })
    }

    /// Whether `comment` sits on its gap's ANCHOR line — the line the construct's last
    /// content token ends on, the one line a same-line block prints inline on.
    ///
    /// The one-step source reading (`comment_follows_content_on_its_line`) cannot
    /// answer this: it counts a preceding COMMENT as content, so a block glued behind
    /// an own-line comment (`expr⏎/* c1 */ /* c2 */⏎;`) read as anchor-line while the
    /// gap emitter's hug arm defers it. The walk mirrors the emitter's anchor-line
    /// split instead: follow same-line predecessors comment by comment until the line
    /// bottoms out at real content (anchor line) or at an own-line / multiline
    /// predecessor (not).
    fn comment_on_gap_anchor_line(&self, span_start: u32, comment: &ast::Comment) -> bool {
        let mut c = comment;
        loop {
            if !self.comment_follows_content_on_its_line(c) {
                // Nothing non-whitespace precedes on the line: own-line.
                return false;
            }
            // What precedes c on its line — the nearest comment (in SOURCE: this is a
            // cursor question, so owned comments count), or real content.
            let Some(prev) = self
                .comments_in_source_between(span_start, c.span.start)
                .last()
            else {
                return true;
            };
            let gap = &self.source.as_bytes()[prev.span.end as usize..c.span.start as usize];
            if gap.iter().any(|b| !b.is_ascii_whitespace()) || gap.contains(&b'\n') {
                // Real content sits between them on c's line (the newline case is
                // unreachable behind the follows-content check, and reads the same
                // way: whatever precedes c on its line is content, not a comment).
                return true;
            }
            if prev.span.extract(self.source).contains('\n') {
                // Glued to a MULTILINE predecessor: c is on its end line, which is
                // not the line the content ended on.
                return false;
            }
            c = prev;
        }
    }

    /// The LAST comment in the construct's terminator gap, if the construct ends in a
    /// re-printed separator (`;` / `,`) and only whitespace sits between the comment
    /// and it — the shared fact behind both `terminator_defers_*` predicates. Anything
    /// non-whitespace after the comment means it is interior to the construct, not in
    /// its terminator gap.
    fn terminator_gap_last_comment(
        &self,
        span_start: u32,
        span_end: u32,
    ) -> Option<&'a ast::Comment> {
        let bytes = self.source.as_bytes();
        if span_end == 0 || !matches!(bytes.get(span_end as usize - 1), Some(b';' | b',')) {
            return None;
        }
        let separator = span_end - 1;
        let last = self
            .comments_to_emit_between(span_start, separator)
            .last()?;
        bytes[last.span.end as usize..separator as usize]
            .iter()
            .all(u8::is_ascii_whitespace)
            .then_some(last)
    }

    /// Whether a gap comment LEADS the next printed item rather than trailing the
    /// previous one: the **glued run** it starts reaches `next_start`'s line — code on
    /// both sides of the run binds it forward (prettier's remaining-comment placement),
    /// and per-item line breaks put the whole run on the next item's line, glued
    /// (`a(); /* c */ b();` → `a();⏎/* c */ b();`).
    ///
    /// The reach is a CHAIN, not one `is_same_line` (prettier's `isEndOfLineComment`
    /// extends the comment's end through every comment glued to it before testing for
    /// the newline): only a newline **outside comment bytes** breaks it, so a glued run
    /// whose tail is a multi-line block still leads
    /// (`a(); /* c */ /* x⏎y */ b();` → both lead `b`), while a run whose closing
    /// comment ends its line trails whole (`a(); /* c1 */ /* c2 */⏎b();`). The scan is
    /// the **in-source** axis — an owned comment's bytes glue the chain like any
    /// other's. Erased structure in the gap (a dropped `;`, a member separator) is
    /// invisible to the line test, which is why the CLAIM scan opens at its slot floor
    /// ([`statement_gap_floor`] and kin): a comment bound inside its own slot is
    /// claimed as trailing and stays behind the cursor, so this test is never asked
    /// of it.
    ///
    /// The one statement of the statement/member-gap split, asked from both sides:
    /// [`Self::trailing_claim_end`] bounds the trailing emitter's claim with it, and
    /// [`Self::comment_already_trailed`]'s `leads_target` is its escape on the leading
    /// side — the two must partition the gap, so neither may re-spell it.
    ///
    /// A line comment can never satisfy the test (its own line ends the chain before
    /// anything follows it), so the deferred-`;` machinery never interacts with it. A
    /// multi-line block reads its CLOSING line, so `a(); /* x⏎y */ b();` leads too.
    pub(crate) fn comment_leads_next_item(
        &self,
        comment: &tsv_lang::Comment,
        next_start: u32,
    ) -> bool {
        let mut pos = comment.span.end;
        for c in comments_in_source_after_comment(self.comments, comment)
            .iter()
            .take_while(|c| c.span.end <= next_start)
        {
            tsv_lang::fanout_probe::predicate();
            if !self.is_same_line(pos, c.span.start) {
                return false;
            }
            pos = c.span.end;
        }
        self.is_same_line(pos, next_start)
    }

    /// Where the previous item's same-line trailing claim ENDS in the gap
    /// `[gap_start, next_start)`: the start of the first comment (to emit) that
    /// [`Self::comment_leads_next_item`] hands to the next printed item, or `next_start`
    /// when every comment in the gap ends its own line — the claim may then run the
    /// whole gap.
    ///
    /// The claim stays a PREFIX by construction: comments are disjoint and ordered, so
    /// a later comment's glue chain to `next_start` is a suffix of an earlier one's —
    /// once one comment leads, every later one in the gap leads too.
    ///
    /// `gap_start` is the slot floor, not always the item's end: a comment before a
    /// dropped `EmptyStatement` binds inside its own slot and trails
    /// (`a(); /* c */ ; b();` — prettier reads it the same way), so statement-list
    /// callers open the scan past the last dropped `;`
    /// ([`statement_gap_floor`]); the type-literal
    /// member gap opens it past the member's source separator for the same reason (a
    /// comment before the `;` trails its member however the lines fall).
    ///
    /// Callers pass the result as the trailing emitter's upper bound and clamp their
    /// cursor with it (`find_end_with_trailing_comments(..).min(claim_end)`), so the
    /// leading side finds the handed-over comments still ahead of the cursor.
    pub(crate) fn trailing_claim_end(&self, gap_start: u32, next_start: u32) -> u32 {
        self.comments_to_emit_between(gap_start, next_start)
            .find(|c| self.comment_leads_next_item(c, next_start))
            .map_or(next_start, |c| c.span.start)
    }

    /// [`Self::trailing_claim_end`] for `body[index]`'s trailing gap: from the gap's
    /// slot floor ([`statement_gap_floor`]) toward the next printed statement — or
    /// toward `tail_target` when only dropped `;`s (or nothing) follow: the construct
    /// past the list's end that gap comments could still lead (a switch consequent's
    /// next `case` label), `None` where nothing prints there (a body's `}`). With no
    /// target at all nothing leads and the claim is unbounded (`u32::MAX`), so a
    /// caller's own scan bound stands unchanged.
    ///
    /// The one spelling for every statement-list walk (program, block/namespace body,
    /// switch consequent) so the trailing claim, the cursor clamp, and the orphan scan bound
    /// cannot drift apart. The walks' ORPHAN arm calls it as is
    /// ([`Self::orphan_semi_slot`]); a PRINTING arm, which already holds the statement's
    /// emitted end, reaches the same spelling through [`Self::statement_claim_end_with`].
    pub(crate) fn statement_claim_end(
        &self,
        body: &[ast::Statement<'_>],
        index: usize,
        tail_target: Option<u32>,
    ) -> u32 {
        // Only the orphan arm asks here, and an orphan `;` is never frozen.
        self.statement_claim_end_with(body, index, tail_target, || {
            self.statement_emitted_end(&body[index], false)
        })
    }

    /// [`Self::statement_claim_end`] for a walk that already HOLDS `body[index]`'s
    /// [`Self::statement_emitted_end`] — `emitted_end` hands it over, asked only when the
    /// gap's scan opens there. Both statement walks' printing arms compute that end for their
    /// own cursor first, and re-deriving it (the kind walk, the terminator gap's claim) for
    /// the same statement a second time is the cost this saves.
    pub(crate) fn statement_claim_end_with(
        &self,
        body: &[ast::Statement<'_>],
        index: usize,
        tail_target: Option<u32>,
        emitted_end: impl FnOnce() -> u32,
    ) -> u32 {
        match next_printed_stmt(body, index)
            .map(|s| s.span().start)
            .or(tail_target)
        {
            Some(target) => self.trailing_claim_end(
                self.statement_gap_scan_start(body, index, emitted_end),
                target,
            ),
            None => u32::MAX,
        }
    }

    /// Where `body[index]`'s trailing gap OPENS for the comment scans — the slot floor
    /// ([`statement_gap_floor`]) lowered into the statement's own terminator gap.
    ///
    /// The two directions answer two different obstacles and compose in one order. A
    /// dropped `;` after the statement RAISES the floor, because a comment before it binds
    /// inside that `;`'s own slot and trails. A `;` the statement itself owns LOWERS it, to
    /// [`Printer::statement_comment_claim_end`] — prettier's `__contentEnd` — because the
    /// trivia between a statement's content and its terminator is not inside the statement
    /// at all, and the comment there is the gap's to place
    /// ([`Self::push_statement_semicolon`], the other half of the partition).
    ///
    /// The lowering applies only when nothing was raised: with a dropped `;` in the way the
    /// gap starts past it, and reaching back over that `;` into the previous statement's
    /// tail would re-claim a comment its own slot rule already placed.
    ///
    /// A kind prettier does not eject reports its own span end and nothing moves, so the
    /// table is read here and nowhere else in the seam.
    ///
    /// `emitted_end` is `body[index]`'s [`Self::statement_emitted_end`], supplied lazily — it
    /// is read only when nothing was raised.
    fn statement_gap_scan_start(
        &self,
        body: &[ast::Statement<'_>],
        index: usize,
        emitted_end: impl FnOnce() -> u32,
    ) -> u32 {
        let floor = statement_gap_floor(body, index);
        if floor == body[index].span().end {
            emitted_end()
        } else {
            floor
        }
    }

    /// Where `stmt`'s own emission ENDS for the enclosing list's comment scans: its
    /// terminator-gap claim end ([`Printer::statement_comment_claim_end`]), or its span end
    /// when the statement is FROZEN.
    ///
    /// Named for the emission rather than for a gap, because it is not a sibling of
    /// [`statement_gap_floor`] or [`Self::statement_gap_scan_start`] and must not be reached
    /// for as one: those two answer where a gap's SCAN opens (and a dropped `;` RAISES them),
    /// while this only ever moves DOWN, into the statement's own terminator gap. It is the
    /// anchor a trailing run and a cursor take.
    ///
    /// ⚠️ A format-ignore freeze copies the statement's text verbatim up to
    /// [`Printer::statement_content_end`], and that measure counts a comment as CONTENT — so
    /// a comment in the terminator gap is already inside the slice (a cataloged divergence,
    /// `docs/conformance_prettier_ignore.md` §Format-ignore directive). Handing it to the list
    /// as well prints it TWICE. The freeze is the caller's verdict, so the caller states it.
    pub(crate) fn statement_emitted_end(&self, stmt: &ast::Statement<'_>, frozen: bool) -> u32 {
        if frozen {
            stmt.span().end
        } else {
            self.statement_comment_claim_end(stmt)
        }
    }

    /// The trailing arm of a gap seam, once: emit the item's same-line trailing run and
    /// return it with the advanced cursor.
    ///
    /// The two families differ only in how they DERIVE `upper_bound` and `claim_end`
    /// ([`Self::push_member_trailing_run`], [`Self::push_statement_trailing_run`]); what they do with
    /// them is this, and it was spelled twice. Both ends matter and they are not the same
    /// end: the emitted run stops at whichever of the two comes first, while the cursor is
    /// clamped to the **claim split alone** — a handed-over comment must stay ahead of it
    /// for the next item's leading run to find, and `upper_bound` (the next item's start)
    /// would clamp it past nothing at all.
    ///
    /// `printed_tail` is the item's own [`Printer::printed_tail`] — the second source line
    /// its last PRINTED line holds — and both the emitted run and the cursor read it, or
    /// the cursor lands above a comment the run just emitted.
    fn push_trailing_run(
        &self,
        parts: &mut DocBuf,
        item_end: u32,
        upper_bound: u32,
        claim_end: u32,
        printed_tail: u32,
    ) -> u32 {
        self.push_trailing_same_line_comment_docs(
            parts,
            item_end,
            upper_bound.min(claim_end),
            printed_tail,
        );
        self.find_end_with_trailing_comments(item_end, printed_tail)
            .min(claim_end)
    }

    /// The whole trailing arm of the **member**-gap seam, shared by the class-body and
    /// interface-body walks — the member sibling of [`Self::push_statement_trailing_run`], and
    /// for the same reason: the two walks held byte-identical copies of it, and the copy is
    /// what let them drift (the interface's re-spelled `is_same_line` filter missed a
    /// multi-line block's closing line, so a comment glued past that `*/` was torn onto its
    /// own line and, on the last member, double-printed by the end-of-body run). An enum
    /// body is NOT one of these: its members are comma-separated, so it takes the
    /// element-comma seam (`collect_trailing_comments` / `push_element_comma_trailing`)
    /// like every other comma list.
    ///
    /// Emits the member's same-line trailing run — bounded at the next member and stopped
    /// at the claim split ([`Self::trailing_claim_end`]) so a comment whose glue chain
    /// reaches that member leads it instead (`a: A; /* c */ b: B;`), emitted by its leading
    /// run into `parts` — and returns the advanced cursor, clamped to the same split so a
    /// handed-over comment stays ahead of it for that leading run to find.
    ///
    /// The caller states the gap's slot FLOOR, a per-family fact rather than a preference
    /// ([`MemberGap`]) — the same role `statement_gap_floor` plays for a statement list.
    ///
    /// Pushes into the caller's buffer rather than returning one: the run is empty on
    /// nearly every member, and a returned buffer is minted, moved and `extend`ed away
    /// on each of them.
    pub(crate) fn push_member_trailing_run(
        &self,
        parts: &mut DocBuf,
        member_end: u32,
        gap: MemberGap,
    ) -> u32 {
        let (upper_bound, claim_end) = match gap {
            MemberGap::Next { floor, start } => (start, self.trailing_claim_end(floor, start)),
            // Nothing prints after this member, so nothing can be led and the claim runs
            // to the body's end.
            MemberGap::Last { list_end } => (list_end, u32::MAX),
        };
        // A member's separator is the list's, not a terminator the member reaches back over,
        // and no member slot is ever erased: the caller already opened the gap past the
        // separator ([`MemberGap`]'s floor), so the run's line is the member's own
        // throughout and there is no printed tail to jump to.
        self.push_trailing_run(parts, member_end, upper_bound, claim_end, u32::MAX)
    }

    /// The whole trailing arm of the statement-gap seam for `body[index]`, shared by
    /// the program and block walks: emit the statement's same-line trailing run —
    /// bounded at the next *printed* statement, skipping dropped `;`s, so a comment
    /// trailing a dropped `;` (`a();; // c`) attaches here rather than being stranded,
    /// and stopped at the claim split ([`Self::statement_claim_end`]) so a comment
    /// whose glue chain reaches the next statement leads it instead
    /// (`a(); /* c */ let b = 1;`), emitted by its leading run. Pushes the run into
    /// `parts` and returns the advanced cursor, clamped to the same split so the
    /// handed-over comments stay ahead of it for that leading run to find.
    ///
    /// The run reads the statement's PRINTED tail too ([`Printer::printed_tail`]): neither a
    /// detached `;` nor a dropped one begins a new output line, so a comment the author
    /// wrote past either, on its line, trails the statement.
    pub(crate) fn push_statement_trailing_run(
        &self,
        parts: &mut DocBuf,
        body: &[ast::Statement<'_>],
        index: usize,
        list_end: u32,
        frozen: bool,
    ) -> u32 {
        // ⚠️ The ANCHOR only ever moves DOWN, so it is the claim end rather than
        // [`Self::statement_gap_scan_start`]: a dropped `;` RAISES that, and anchoring the
        // statement's own trailing run past a `;` puts the cursor above a comment written
        // before it — which that `;`'s orphan run then cannot find, a DROP. Raising is the
        // claim SCAN's rule, not the anchor's.
        let stmt_end = self.statement_emitted_end(&body[index], frozen);
        let bound = next_printed_stmt_start(body, index, list_end);
        self.push_trailing_run(
            parts,
            stmt_end,
            bound,
            self.statement_claim_end_with(body, index, None, || stmt_end),
            self.printed_tail(stmt_end, statement_gap_floor(body, index)),
        )
    }

    /// Where the statement's PRINTED tail ends in source — the [`TrailingLineRef`] jump —
    /// or [`u32::MAX`] when its last printed line is one source line.
    ///
    /// Nothing between `emitted_end` and the gap's slot floor begins a new OUTPUT line, and
    /// the two authorings that put something there are one question:
    ///
    /// - the statement's **own `;`**, when the author detached it (`a()⏎; // c`) — it prints
    ///   back up on the content's line, so its image IS on this line;
    /// - a **dropped `EmptyStatement`** (`a();⏎; // c`) — it prints nothing at all, so it
    ///   cannot begin a line either.
    ///
    /// [`statement_gap_floor`] already reports past the second, and `emitted_end`
    /// ([`Self::statement_emitted_end`]) sits below the span end exactly when the statement
    /// handed its terminator gap to this list (prettier's `__contentEnd`,
    /// [`Printer::statement_comment_claim_end`]) — which covers the first. So the whole
    /// question is one compare plus one line test, and no kind table is read a second time.
    ///
    /// The value is a **jump for a trailing run's line reference**, never an anchor: a run
    /// still opens at `emitted_end`, so a comment in the terminator gap itself stays the
    /// gap's ([`Printer::trailing_same_line_comments_through`] states the rule).
    pub(crate) fn printed_tail(&self, emitted_end: u32, slot_floor: u32) -> u32 {
        if emitted_end < slot_floor && !self.is_same_line(emitted_end, slot_floor) {
            slot_floor
        } else {
            u32::MAX
        }
    }

    /// Whether `comment` was already emitted as the PREVIOUS item's trailing run — it
    /// shares `anchor`'s source line — so this leading / end-of-body run must skip it.
    ///
    /// The single home for a question **eight** emitters ask, none with an
    /// `is_same_line` call of its own: the two statement-list leading runs (block body, switch
    /// consequent), the class-member, type-literal-member and enum-member leading runs, and
    /// the three end-of-body runs (program, block, the shared
    /// [`Self::push_trailing_body_comments`] — which the object literal now reaches
    /// too). Answering it independently is exactly what let them drift — see the
    /// one-question-one-predicate rule the printer keeps re-learning.
    ///
    /// `anchor` is `None` when there is no previous item at all: nothing trailed, so
    /// nothing is claimed and the run keeps everything.
    ///
    /// ⚠️ **The two families spell `anchor` differently, and the two are EQUIVALENT — do
    /// not "fix" one into the other.** The statement walks (program, block, switch) pass
    /// the previous statement's **span end**; the member walks (class, interface, type
    /// literal) pass the **cursor already advanced past the trailing run**
    /// (`find_end_with_trailing_comments(..).min(claim_end)`). Those hold different values
    /// whenever a multi-line block trailed the item — the cursor then sits on that block's
    /// closing line, a line below the span end — yet the predicate cannot tell them apart,
    /// because the cursor only ever advances to one of two places: **inside** the trailing
    /// run, whose comments are behind it and never reach this filter, or to the **claim
    /// split**, where every comment from there on leads the next item (the claim is a
    /// prefix) and `leads_target` rescues it. A comment that does reach the filter
    /// therefore sits on a later line than *both* anchors. Measured as well as argued: the
    /// two spellings produce byte-identical output over 9196 real files and over the
    /// targeted shapes that provably move the cursor off the item's line.
    ///
    /// `claims_trailing` forces `false`. The previous item deferred a line comment past its
    /// own `;` ([`Self::terminator_defers_line_comment`]) and therefore trailed **nothing**
    /// on that line, which leaves this run the only emitter left for it. Skipping the run
    /// in BOTH places is a dropped comment; trailing it in both is a double-print.
    ///
    /// `leads_target` is the printed item this gap's comments could lead — the escape
    /// matching [`Self::trailing_claim_end`]'s cut on the trailing side: a comment
    /// [`Self::comment_leads_next_item`] hands forward shares the anchor's line yet was
    /// NOT claimed, so it must not be skipped here. Pass `None` where nothing prints at
    /// the range's end (an orphaned/end-of-body run) — there the trailing claim ran the
    /// whole gap and the line test alone is the answer.
    pub(crate) fn comment_already_trailed(
        &self,
        anchor: Option<u32>,
        comment: &tsv_lang::Comment,
        claims_trailing: bool,
        leads_target: Option<u32>,
    ) -> bool {
        !claims_trailing
            && !leads_target.is_some_and(|t| self.comment_leads_next_item(comment, t))
            && anchor.is_some_and(|a| self.is_same_line(a, comment.span.start))
    }

    /// The comments that TRAIL a node ending at `after_pos` on its own output line — the
    /// same-line run in `[after_pos, upper_bound)`.
    ///
    /// The run **follows a multi-line block comment to its closing `*/` line**, so a
    /// comment the author glued past that `*/` trails the node too rather than being torn
    /// onto a line of its own (`a; /* x⏎y */ /* c */`). That is the same `line_ref` walk
    /// [`Self::find_end_with_trailing_comments`] makes, and the two are deliberately on
    /// different axes and must stay that way: this one is **to emit** (an owned comment is
    /// printed by its own node), while the cursor is **in source** (it steps over comment
    /// bytes so a blank-line scan can't read a comment's own newlines as an author's
    /// blank).
    ///
    /// The one statement of "what trails here", for the emitter that renders it
    /// ([`Self::build_trailing_same_line_comment_docs`]) and for the caller that needs the
    /// run as a LIST first — a type-literal member partitions it around its own `;`, and
    /// collects. A re-spelled `is_same_line(after_pos, c.span.start)` filter answers the
    /// multi-line case wrong, which is what put the interface and type-literal member walks
    /// at odds with the class body and with prettier.
    ///
    /// Yielded lazily: the run is empty in nearly every ask (the next comment is lines
    /// away), and a buffer built, returned by value and moved again into the caller's loop
    /// was the whole cost of asking.
    pub(crate) fn trailing_same_line_comments(
        &self,
        after_pos: u32,
        upper_bound: u32,
    ) -> impl Iterator<Item = &'a ast::Comment> {
        self.trailing_same_line_comments_through(after_pos, upper_bound, u32::MAX)
    }

    /// [`Self::trailing_same_line_comments`] over a printed tail that spans TWO source
    /// lines — the [`TrailingLineRef`] jump, [`u32::MAX`] for the one-line case every other
    /// caller has. That type states the rule; this is the **to-emit** axis of it.
    ///
    /// The jump fires only at or past `printed_tail`, so a comment the author wrote in the
    /// terminator gap ITSELF (`a()⏎/* c */;`) is unreached — that one is the gap's, and the
    /// list's seam places it ([`Printer::statement_comment_claim_end`]).
    pub(crate) fn trailing_same_line_comments_through(
        &self,
        after_pos: u32,
        upper_bound: u32,
        printed_tail: u32,
    ) -> impl Iterator<Item = &'a ast::Comment> {
        let mut line = TrailingLineRef::new(after_pos, printed_tail);
        self.comments_to_emit_between(after_pos, upper_bound)
            .take_while(move |comment| line.take(self, comment))
    }

    /// Build docs for trailing same-line comments after a node
    ///
    /// Line comments are wrapped in `line_suffix` so they don't affect width
    /// calculations for preceding groups (matches Prettier behavior).
    /// Block comments are inline and do affect width.
    ///
    /// Returns the docs to append to the current parts — for a caller that emits them
    /// later than it asks (the switch consequent, which builds the run ahead of the
    /// statement it follows). A caller that appends them at once takes
    /// [`Self::push_trailing_same_line_comment_docs`], which mints no buffer.
    pub(crate) fn build_trailing_same_line_comment_docs(
        &self,
        after_pos: u32,
        upper_bound: u32,
        printed_tail: u32,
    ) -> DocBuf {
        let mut docs = DocBuf::new();
        self.push_trailing_same_line_comment_docs(&mut docs, after_pos, upper_bound, printed_tail);
        docs
    }

    /// [`Self::build_trailing_same_line_comment_docs`] into the caller's buffer.
    pub(crate) fn push_trailing_same_line_comment_docs(
        &self,
        parts: &mut DocBuf,
        after_pos: u32,
        upper_bound: u32,
        printed_tail: u32,
    ) {
        for comment in
            self.trailing_same_line_comments_through(after_pos, upper_bound, printed_tail)
        {
            parts.push(self.build_trailing_comment_doc(comment));
        }
    }

    /// The clause-tail spelling of [`Self::build_trailing_same_line_comment_docs`] —
    /// the same claim, each comment emitted own-line with its break inside the suffix,
    /// dedented `dedent` levels ([`Printer::build_clause_tail_comment_doc`]). For a
    /// statement whose own terminator gap already deferred a `//`
    /// ([`Self::terminator_defers_line_comment`]), nothing may share the flush line, so
    /// the `;`-line run lands one comment per line at the enclosing construct's level
    /// — the switch case's last statement is the caller (dedent 1, consequent →
    /// case-label level).
    pub(crate) fn build_deferred_tail_same_line_comment_docs(
        &self,
        after_pos: u32,
        upper_bound: u32,
        dedent: u8,
    ) -> DocBuf {
        let mut docs = DocBuf::new();
        for comment in self.trailing_same_line_comments(after_pos, upper_bound) {
            docs.push(self.build_clause_tail_comment_doc(comment, false, dedent));
        }
        docs
    }

    /// Build the leading-comment run before `target_start` — the member, statement, or
    /// element the comments lead.
    ///
    /// A thin adapter over the shared leading-comment emitter
    /// ([`Printer::push_leading_comment_run`]), for the callers holding their run as a
    /// slice rather than a range (each applies a per-site filter — dropping the previous
    /// statement's same-line trailing comments, or the ones pulled onto the delimiter
    /// line). The separator after each comment is prettier's `printLeadingComment`
    /// (space / soft `line` / blank-preserving hardline), keyed on the source around
    /// *that* comment.
    ///
    /// Every caller is an already-broken context — an expanded pattern, a multiline
    /// member prefix, a class/interface body, a statement list — so the soft `line`
    /// renders as a break here. That is why this reads as "hardline between own-line
    /// comments" at every site; it is the general rule landing in a broken group, not a
    /// policy of its own. A caller that ever measures this run inside a group that can
    /// *fit* gets prettier's collapse for free, which is the point of routing here.
    ///
    /// Used by: class body members, interface/enum members, block statement bodies,
    /// type literals, expanded object patterns. The orphaned-comment sibling is
    /// [`Self::push_orphaned_comment_run`]. Pushes into the caller's buffer
    /// (usually pooled) rather than returning a fresh `DocBuf` — a long run
    /// would spill the intermediate on every call just to be `extend`ed away.
    pub(crate) fn push_leading_comments_before(
        &self,
        parts: &mut DocBuf,
        comments: &[&ast::Comment],
        target_start: u32,
    ) {
        self.push_leading_comment_run(
            parts,
            comments.iter().copied(),
            target_start,
            LeadingGlue::Adjacent,
        );
    }

    /// Build the run for comments **orphaned by a dropped statement** — a bare `;`
    /// (`EmptyStatement`) never prints in a body list, so the comments in its gap have
    /// no node to lead. `gap_end` is a source position, not something that will be
    /// emitted.
    ///
    /// So the last comment must not glue to `gap_end`, and takes no separator at all —
    /// the caller's own next emission supplies it. Only an author blank line is recorded
    /// (a bare `literalline`, which the caller's hardline completes), because the
    /// caller's gap check starts later in the source and cannot rediscover it.
    ///
    /// Every *other* comment in the run leads the next comment, which is an ordinary
    /// leading run — so it routes through the shared emitter unchanged, and only the
    /// last comment is special-cased here.
    ///
    /// A sibling of [`Self::push_leading_comments_before`] rather than a flag on it:
    /// what differs is not a separator policy but whether the run has a target at all.
    pub(crate) fn push_orphaned_comment_run(
        &self,
        parts: &mut DocBuf,
        comments: &[&ast::Comment],
        gap_end: u32,
    ) {
        let Some((last, leading)) = comments.split_last() else {
            return;
        };
        self.push_leading_comment_run(
            parts,
            leading.iter().copied(),
            last.span.start,
            LeadingGlue::Adjacent,
        );
        parts.push(self.build_comment_doc(last));
        if self.has_blank_line_between(last.span.end, gap_end) {
            parts.push(self.d().literalline());
        }
    }

    /// Build docs for trailing comments at the end of a body (before closing `}`).
    ///
    /// Handles comments that appear after the last member/statement in a body,
    /// with blank line preservation between them. Returns a Vec of docs to append.
    ///
    /// The separator is emitted **before** every comment (`hardline`, preceded by a
    /// `literalline` when the author left a blank line) rather than after it. Keying it on
    /// the *following* comment's existence is what makes the rule uniform: the closing `}`
    /// supplies its own break. The mirror-image formulation — emit the separator *after*
    /// each non-last comment — has to ask what KIND the comment was, and answering "a block
    /// needs no break, the `}` follows immediately" welds whatever comes next onto its line
    /// (`/* c1 *//* c2 */`, `/* c1 *///  c2` — the second comment becomes text of the
    /// first).
    ///
    /// The one thing the separator asks is whether the author **glued** this comment to the
    /// previous one ([`Self::trailing_run_hugs_previous`]), in which case the pair keeps the line
    /// it was written on. That is not the weld above — a space keeps both comments distinct,
    /// and a line comment never hugs, so nothing lands behind a `//`. Prettier keeps the
    /// glue here and splits it in an EMPTY body, which is why
    /// [`Self::push_dangling_comment_run`]'s separator stays unconditional.
    ///
    /// Used by every end-of-body run: class body, interface body, enum body, type literal,
    /// namespace body, block-statement bodies (function and bare blocks, via
    /// [`Self::build_block_body_doc`]), the object literal (via
    /// [`Self::push_trailing_closer_comments`], the only caller whose container may
    /// still collapse), and the `}`-less one — the end of the **program**, where `body_end`
    /// is the source length.
    ///
    /// `claims_trailing` says this run owns the comments sharing `prev_end`'s source line.
    /// Normally the last item's trailing emitter took them, so they are skipped here; a
    /// caller whose last item deferred a line comment past its own `;`
    /// ([`Self::terminator_defers_line_comment`]) trailed nothing, so it passes `true` and
    /// this run claims them. Skipping them in BOTH places is a dropped comment — and with
    /// no further item in the list, this emitter is the last chance to print them.
    pub(crate) fn push_trailing_body_comments(
        &self,
        parts: &mut DocBuf,
        prev_end: u32,
        body_end: u32,
        claims_trailing: bool,
    ) -> bool {
        self.push_trailing_closer_comments(
            parts,
            prev_end,
            body_end,
            claims_trailing,
            self.d().hardline(),
        )
    }

    /// [`Self::push_trailing_body_comments`] with the run's separator supplied, for
    /// the one container that may still COLLAPSE around its trailing run — the object
    /// literal's inline form, whose separator is a soft `line` its group decides.
    ///
    /// It exists so that container does not keep a SECOND copy of this walk: the copy is
    /// what let the two drift, and the stripped-shell blank scan below then had to be
    /// fixed twice. Every other end-of-body run is already hard-broken, hence the
    /// `hardline` default.
    ///
    /// Pushes into the caller's buffer and reports whether it emitted anything: the run
    /// is empty after nearly every body, and a returned buffer is minted, moved and
    /// `extend`ed away on each of them.
    pub(crate) fn push_trailing_closer_comments(
        &self,
        parts: &mut DocBuf,
        prev_end: u32,
        body_end: u32,
        claims_trailing: bool,
        separator: DocId,
    ) -> bool {
        let d = self.d();
        let mut emitted = false;
        // The blank scan measures a DISTANCE, so it opens past the closers of a stripped
        // paren shell the last item's doc consumed but did not print
        // ([`Self::element_shell_end`]) — an enum member's `A = (⏎1⏎)⏎/* c */` otherwise
        // reads the shell's own line breaks as an author blank and FABRICATES one. Inert
        // for every caller whose `prev_end` is a `;`/`}`: the walk commits only when it
        // actually steps over a `)`, and `body_end` keeps it inside the body.
        //
        // ⚠️ **The `anchor` below keeps the unshifted `prev_end`**, which is the opposite
        // question — "did the last item's own emitter already trail this comment?" — asked
        // of the item's line. Shifting it past the `)` would call a comment on the closer's
        // line already-trailed and DROP it, since this run is the last chance to print one.
        let mut last_pos = self.element_shell_end(prev_end, body_end);
        // `prev_end == 0` is the one caller with no previous item at all: a comments-only
        // file, where the run IS the output. Nothing trailed, so nothing is claimed
        // ([`Self::comment_already_trailed`]'s `None` anchor), and the first comment opens
        // the document rather than breaking away from content above it. A real `{}` body's
        // cursor is at least its `{` plus one, so the two cases can't collide.
        let anchor = (prev_end > 0).then_some(prev_end);
        let mut needs_separator = anchor.is_some();
        // The comment this run emitted last, for the glue question below. `None` after a
        // skipped one: that comment is on the page but not on THIS run's line, so a
        // comment glued to it in source has nothing here to glue to.
        let mut prev_emitted: Option<&ast::Comment> = None;

        for comment in self.comments_to_emit_between(prev_end, body_end) {
            if self.comment_already_trailed(anchor, comment, claims_trailing, None) {
                // Already emitted as the last item's trailing run — but the cursor still
                // steps over its BYTES, since the blank-line scan below reads raw source
                // and would otherwise count a multi-line block's own newlines as a blank.
                last_pos = comment.span.end;
                prev_emitted = None;
                continue;
            }
            if needs_separator {
                // A pair the author GLUED onto one line keeps that line
                // ([`Self::trailing_run_hugs_previous`], the run's shared question).
                // The non-glue arm is this walk's own — the separator is the CALLER's, and
                // its blank scan reads the loose newline count from the already-peeled
                // `last_pos` — so it asks the predicate rather than routing through
                // [`Self::push_trailing_run_separator`].
                if self.trailing_run_hugs_previous(prev_emitted, comment.span.start) {
                    parts.push(d.text(" "));
                } else {
                    if self.has_blank_line_between(last_pos, comment.span.start) {
                        parts.push(d.literalline());
                    }
                    parts.push(separator);
                }
            }
            parts.push(self.build_comment_doc(comment));
            last_pos = comment.span.end;
            prev_emitted = Some(comment);
            needs_separator = true;
            emitted = true;
        }

        emitted
    }

    /// Append a **dangling** comment run — the comments alone inside an otherwise empty
    /// delimiter pair, with no node to lead or trail — joined by a `hardline` (prettier's
    /// `printDanglingComments`).
    ///
    /// The separator sits strictly BETWEEN comments: the delimiter pair supplies the break
    /// before the first and after the last. It is emitted before each comment but the
    /// first, never after each comment but the last, for the same reason
    /// [`Self::push_trailing_body_comments`] is — the "after" formulation has to ask
    /// what KIND the comment was, and "a block needs no break, the closer follows
    /// immediately" is false the moment another comment follows, welding the two together
    /// (`/* c1 *//* c2 */`).
    ///
    /// ⚠️ **Unconditional, unlike the trailing run's**, which lets an author-glued pair keep
    /// its line. Prettier draws that line between the two positions: it keeps the glue after
    /// a last item and splits the pair in an EMPTY container (`class A { /* c1 */ /* c2 */
    /// }`), so this emitter has no glue question to ask.
    ///
    /// The caller owns whether the run can stay inline: it picks the open/close separator
    /// (a collapsible `line`/`softline`, or a `hardline` for the always-exploded bodies).
    pub(crate) fn push_dangling_comment_run<'c>(
        &self,
        parts: &mut DocBuf,
        comments: impl IntoIterator<Item = &'c ast::Comment>,
    ) {
        let d = self.d();
        for (i, comment) in comments.into_iter().enumerate() {
            if i > 0 {
                parts.push(d.hardline());
            }
            parts.push(self.build_comment_doc(comment));
        }
    }

    /// Emit a **trailing** comment run: every comment preceded by its separator
    /// ([`Self::push_trailing_run_separator`]), so an author-glued pair keeps its line and
    /// everything else takes the blank-preserving break.
    ///
    /// The third member of the run-emitter family, beside
    /// [`Self::push_leading_comment_run`] and [`Self::push_dangling_comment_run`] — it is
    /// the *separator-before-each* rule, and the `(prev_pos, prev_comment)` bookkeeping it
    /// carries is exactly what every hand-rolled copy of this walk gets to restate. `scan_from`
    /// is the caller's cursor, which bounds the first comment's blank scan.
    pub(crate) fn push_trailing_comment_run<'c>(
        &self,
        parts: &mut DocBuf,
        comments: impl IntoIterator<Item = &'c ast::Comment>,
        scan_from: u32,
    ) {
        let mut prev_pos = scan_from;
        let mut prev_comment: Option<&ast::Comment> = None;
        for comment in comments {
            self.push_trailing_run_separator(parts, prev_comment, prev_pos, comment.span.start);
            parts.push(self.build_comment_doc(comment));
            prev_pos = comment.span.end;
            prev_comment = Some(comment);
        }
    }

    /// Compute the "delimiter-line prefix" for the open-delimiter trailing-comment
    /// divergence (object literals, array literals, and block bodies).
    ///
    /// A comment on the same source line as the opening delimiter at `delim_pos`
    /// is kept on that line — instead of being relocated to its own line as the
    /// first element's leading comment (prettier's behavior). Returns the emitted
    /// prefix doc (` /* c */` / ` // c`, leading-space convention) and, when the
    /// pull fired, `Some(delim_pos)` — the position the caller passes back to
    /// exclude those same-line comments from the first element's leading set
    /// (`None` when nothing was pulled, so there is no prefix).
    ///
    /// The prefix is an `Option`, never an empty doc: almost every delimiter has no
    /// comment on its line, and an `empty()` child sitting in the delimited body's
    /// concat is visited by every later walk (layout, fits, render) for nothing —
    /// see [`Self::build_delimited_doc`], which assembles the body without the slot.
    ///
    /// Gated on `should_force_expansion_for_comments`, so an inline block comment
    /// hugging the first element (`{ /* c */ a: 1 }`, `[/* c */ x]`) is left in
    /// place and the result is `(None, None)`. See conformance_prettier_ts_comments.md
    /// §Comment relocation.
    ///
    /// The call family asks the same question about its `(` and reaches the same rule
    /// from the other side — see `docs/comments.md` §The delimiter-line question. Its
    /// force-expanded builders spell this predicate identically
    /// (`PartitionedComments::has_trailing_comments` conjoined with
    /// `should_force_expansion_for_comments`); its collapse-capable path
    /// (`emit_first_arg_leading_comments`) asks the narrower
    /// `PartitionedComments::has_trailing_line` instead, which is load-bearing, not drift.
    pub(in crate::printer) fn delimiter_line_comment_prefix(
        &self,
        delim_pos: u32,
        first_elem_start: u32,
    ) -> (Option<DocId>, Option<u32>) {
        self.delimiter_line_comment_prefix_impl(delim_pos, first_elem_start, false)
    }

    /// Assemble a delimited body — `open`, the delimiter-line `prefix` when there is
    /// one, the `body`, the `closer_line` and `close` — as one concat with no empty
    /// slot. The one assembly for every consumer of
    /// [`Self::delimiter_line_comment_prefix`] whose body has this five-part shape, so
    /// the common no-prefix tree is four children, not four and an `empty()`.
    #[inline]
    pub(in crate::printer) fn build_delimited_doc(
        &self,
        open: DocId,
        prefix: Option<DocId>,
        body: DocId,
        closer_line: DocId,
        close: DocId,
    ) -> DocId {
        let d = self.d();
        match prefix {
            Some(prefix) => d.concat(&[open, prefix, body, closer_line, close]),
            None => d.concat(&[open, body, closer_line, close]),
        }
    }

    /// Object-literal variant of `delimiter_line_comment_prefix` that *also* pulls
    /// a block comment sharing the opening `{` line onto that line when the first
    /// property is on a later line (the object spans multiple lines). An object
    /// literal preserves its authored multi-line-ness, so a source newline before
    /// the first property means it will break, and the block trails `{` (like a
    /// line comment does) instead of dropping to the property's leading line.
    /// Collapsing containers (arrays, arg lists) keep the base behavior and call
    /// the plain form. The caller must treat a fired pull as forcing must-break
    /// (the prefix is only emitted on the break path).
    pub(in crate::printer) fn delimiter_line_comment_prefix_object(
        &self,
        delim_pos: u32,
        first_elem_start: u32,
    ) -> (Option<DocId>, Option<u32>) {
        self.delimiter_line_comment_prefix_impl(delim_pos, first_elem_start, true)
    }

    /// Assemble a computed `[…]` / `?.[…]` (or mapped-type `[K in T]`) that must BREAK
    /// because a line comment sits in the open→body gap: pull a `[`-line comment onto the
    /// open line (own-line ones keep their line, blank-preserving), emit `body`, and drop
    /// `]`. `body` is pre-built by the caller (key/index/interior plus any body→`]`
    /// trailing comments, per each printer's own rule), so this owns only the shared
    /// shell. `open` is the emitted bracket text (`[` or `?.[`); `bracket_char` is the
    /// source position of the `[` glyph (the scan/pull anchor), decoupled from `open` for
    /// the `?.[` form (`bracket_char + 1` is the first inside-bracket position). Shared by
    /// the computed-key, computed-member-access, and mapped-type break paths.
    ///
    /// Both edges take the shared obligation seam ([`Printer::obligated_break`], which
    /// carries the rule). The opening one this shell asks itself, over the whole
    /// delimiter→body gap — which covers a `//` the pull moved onto the `[`'s line as well,
    /// since a pulled comment is still physically in that gap. The closing one it cannot:
    /// `body` arrives pre-built, so `body_trailing_line_comment` is the caller's own
    /// body→`]` verdict, the one term not derivable here (and one each caller already holds,
    /// since it is half of the gate that routes to this shell at all).
    pub(in crate::printer) fn build_bracket_line_comment_break(
        &self,
        open: &'static str,
        bracket_char: u32,
        body_start: u32,
        body_trailing_line_comment: bool,
        body: DocId,
    ) -> DocId {
        let d = self.d();
        let (line_prefix, pull_pos) = self.delimiter_line_comment_prefix(bracket_char, body_start);
        let leading_line_comment = self.has_line_comments_between(bracket_char + 1, body_start);
        let mut inner = DocBuf::new();
        inner.push(self.obligated_break(leading_line_comment, d.softline()));
        inner.extend(self.build_leading_comments_multiline(bracket_char + 1, body_start, pull_pos));
        inner.push(body);
        d.group_break(self.build_delimited_doc(
            d.text(open),
            line_prefix,
            d.indent(d.concat(&inner)),
            self.obligated_break(body_trailing_line_comment, d.softline()),
            d.text("]"),
        ))
    }

    fn delimiter_line_comment_prefix_impl(
        &self,
        delim_pos: u32,
        first_elem_start: u32,
        pull_expanding_block: bool,
    ) -> (Option<DocId>, Option<u32>) {
        let pc = super::calls::PartitionedComments::new(self, delim_pos, first_elem_start);
        // The base rule gates the pull on forced expansion (a line comment, or a
        // block standalone on its own line) — the call family's own predicate, so the
        // two families cannot drift. `pull_expanding_block` adds the object case: a
        // block on the delimiter line with the first element on a later line — the
        // object will break, so the block trails the `{`. (Its `has_trailing_block`
        // implies the base rule's `has_trailing_comments`, which is why the added arm
        // sits beside the predicate rather than inside its conjunction.)
        let pull = pc.pulls_to_delimiter_line(self)
            || (pull_expanding_block
                && pc.has_trailing_block()
                && !self.is_same_line(delim_pos, first_elem_start));
        let prefix = pull.then(|| {
            let mut prefix = DocBuf::new();
            // The run, plus the author blank below it — one emitter for every
            // delimiter-line pull in both families.
            pc.emit_delimiter_line_pull(&mut prefix, self);
            self.d().concat(&prefix)
        });
        (prefix, pull.then_some(delim_pos))
    }

    /// Whether `comment` was pulled onto the opening delimiter's line by
    /// `delimiter_line_comment_prefix` — i.e. it shares a source line with the
    /// delimiter at `delim_pos`.
    ///
    /// The prefix helper emits these comments on the delimiter's line; every
    /// consumer must then drop the same comments from the first element's
    /// leading-comment set so they aren't emitted twice. Centralizing the test
    /// keeps that exclusion in lockstep with what the prefix actually pulls.
    pub(in crate::printer) fn comment_on_delimiter_line(
        &self,
        delim_pos: u32,
        comment: &ast::Comment,
    ) -> bool {
        self.is_same_line(delim_pos, comment.span.start)
    }

    /// A first element/member's leading comments with the delimiter-line
    /// comments removed.
    ///
    /// `delimiter_line_comment_prefix` emits the comments sharing the opening
    /// delimiter's line as a prefix on that line, so every member-loop consumer
    /// must drop the same comments from the first element's leading set to avoid
    /// emitting them twice (see `comment_on_delimiter_line`). Returns `comments`
    /// unchanged when `delimiter_pull_pos` is `None` (nothing was pulled).
    pub(in crate::printer) fn first_member_leading_comments<'c>(
        &self,
        comments: CommentVec<'c>,
        delimiter_pull_pos: Option<u32>,
    ) -> CommentVec<'c> {
        match delimiter_pull_pos {
            Some(dpos) => comments
                .into_iter()
                .filter(|c| !self.comment_on_delimiter_line(dpos, c))
                .collect(),
            None => comments,
        }
    }

    /// A list item's **leading** run: the comments in `[gap_start, item_start)`, minus any
    /// the opening delimiter pulled onto its own line ([`Self::first_member_leading_comments`]).
    ///
    /// ⚠️ `gap_start` is where the PREVIOUS item's **trailing run ended**
    /// (`TrailingComments::end_pos`) — never a position past the separator. The two runs
    /// partition one gap, so a scan that starts past the comma leaves the comments the
    /// author wrote on the other side of it (`a: 1⏎// c⏎, b`) with no emitter at all; that
    /// was a live DROP at four sites. The parameter is named for the cursor it wants.
    /// See [docs/comments.md](../../../../docs/comments.md) §The element-comma seam.
    ///
    /// `delimiter_pull` is `Some(pos)` **only for the first item** — a later item's gap can
    /// still be on the delimiter's line (a one-line list), and dropping there would delete
    /// a comment nothing else prints. Callers pass `if is_first { pull } else { None }`.
    pub(in crate::printer) fn collect_item_leading_comments(
        &self,
        gap_start: u32,
        item_start: u32,
        delimiter_pull: Option<u32>,
    ) -> CommentVec<'_> {
        let comments: CommentVec<'_> = self
            .comments_to_emit_between(gap_start, item_start)
            .collect();
        self.first_member_leading_comments(comments, delimiter_pull)
    }

    /// Build a Doc for an empty body (`{}`) that may contain comments.
    ///
    /// If comments exist between the braces, formats as:
    /// ```text
    /// {
    ///     // comment
    /// }
    /// ```
    ///
    /// If no comments, returns `{}`.
    ///
    /// Always breaks when a comment is present — used by the containers prettier
    /// keeps exploded (class body, interface body, namespace body). The
    /// containers that keep a fitting block comment inline (object literals and
    /// patterns, enum bodies, type literals) pass a collapsible `sep` to
    /// [`Self::build_empty_bracketed_with_comments_doc`] instead; "always breaks" is
    /// nothing more than that same emitter with a `hardline` separator, so both live on
    /// one dangling-comment rule.
    pub(crate) fn build_empty_body_with_comments_doc(&self, body_span: Span) -> DocId {
        let d = self.d();
        self.build_empty_bracketed_with_comments_doc(
            body_span.start,
            body_span.end,
            d.text("{"),
            d.text("}"),
            d.hardline(),
        )
    }

    /// Build a Doc for an empty `{}` body whose only content is a dangling
    /// comment, keeping a fitting block comment inline with bracket spacing
    /// (`{ /* c */ }`).
    ///
    /// tsv applies bracket spacing uniformly: object literals, destructuring
    /// patterns, enum bodies, and type literals all print a comment-only empty
    /// body as `{ /* c */ }`. Prettier tightens every one of these to
    /// `{/* c */}`, so this is a divergence — see conformance_prettier_ts.md
    /// §Empty-object comment bracket spacing. A truly empty `{}` (no comment)
    /// has no content to space and stays tight in both. See
    /// [`Self::build_empty_bracketed_with_comments_doc`].
    pub(crate) fn build_empty_braces_inline_with_comments_doc(&self, body_span: Span) -> DocId {
        let d = self.d();
        let sep = d.line();
        self.build_empty_bracketed_with_comments_doc(
            body_span.start,
            body_span.end,
            d.text("{"),
            d.text("}"),
            sep,
        )
    }

    /// Build a Doc for an empty bracket `[]` body whose only content is a
    /// dangling comment, keeping a fitting block comment inline (`[/* c */]`).
    ///
    /// Used by array literals/patterns and tuple types. See
    /// [`Self::build_empty_bracketed_with_comments_doc`].
    pub(crate) fn build_empty_brackets_inline_with_comments_doc(&self, span: Span) -> DocId {
        self.build_empty_brackets_inline_with_comments_doc_range(span.start, span.end)
    }

    /// Build a Doc for an empty bracket `[]` body with explicit bounds (e.g. an
    /// array pattern with a type annotation). See
    /// [`Self::build_empty_brackets_inline_with_comments_doc`].
    pub(crate) fn build_empty_brackets_inline_with_comments_doc_range(
        &self,
        body_start: u32,
        body_end: u32,
    ) -> DocId {
        let d = self.d();
        let sep = d.softline();
        self.build_empty_bracketed_with_comments_doc(
            body_start,
            body_end,
            d.text("["),
            d.text("]"),
            sep,
        )
    }

    /// Build a Doc for an empty paren list whose only content is a dangling
    /// comment, keeping a fitting block comment inline (`fn(/* c */)`).
    ///
    /// The paren counterpart of [`Self::build_empty_brackets_inline_with_comments_doc`],
    /// shared by every empty paren list: call and `new` arguments (including the
    /// member-chain and optional-call `?.(` forms, hence the `opening` prefix),
    /// value parameter lists (function, method, arrow), and signature-level type
    /// params. A line comment inside `()` cannot stay inline — `//` runs to the end
    /// of the line and would swallow the `)` — so it forces the break; this is the
    /// one delimiter pair where inlining is a correctness bug rather than a layout
    /// choice.
    ///
    /// The sibling swallow in CALLEE position — a line comment between the callee and
    /// its `(` (`call // c⏎()`, and the optional-call `call?. // c⏎()`) — is a different
    /// mechanism (callee-position trivia, not a dangling comment inside a delimiter
    /// pair) and is handled by this emitter's caller, `build_empty_args_parens_doc`, which drops the
    /// whole list to an indented continuation line.
    ///
    /// `paren_open` is the `(` position and `paren_close_after` the position past
    /// the `)` (as returned by `find_closing_paren`); `opening` is the emitted opener
    /// (`(`, or a call's `?.(`), built where its spelling is known.
    pub(crate) fn build_empty_parens_inline_with_comments_doc(
        &self,
        paren_open: u32,
        paren_close_after: u32,
        opening: DocId,
    ) -> DocId {
        let d = self.d();
        let sep = d.softline();
        self.build_empty_bracketed_with_comments_doc(
            paren_open,
            paren_close_after,
            opening,
            d.text(")"),
            sep,
        )
    }

    /// Build a Doc for an empty parameter list, preserving any dangling comments
    /// inside the parens (`fn(/* c */)`). Shared by every empty parameter list —
    /// value params (function, method, arrow) and signature-level type params — so
    /// the dangling rule of
    /// [`Self::build_empty_parens_inline_with_comments_doc`] reaches all of them.
    ///
    /// `search_limit` bounds the depth-tracked `)` search, which skips comment and
    /// string content so a `)` inside a comment can't be mistaken for the closer.
    /// Callers that know a tighter bound (an arrow's body start) pass it; the rest
    /// pass the source length. Yields a bare `()` when there is no `(` to anchor to.
    pub(crate) fn build_empty_params_with_comments_doc(
        &self,
        params_start: Option<u32>,
        search_limit: u32,
    ) -> DocId {
        if let Some(open) = params_start
            && let Some(close_after) = self.close_paren_after_params(open, None, search_limit)
        {
            return self.build_empty_parens_inline_with_comments_doc(
                open,
                close_after,
                self.d().text("("),
            );
        }
        self.d().text("()")
    }

    /// Build a Doc for an empty delimited container whose only content is a
    /// dangling comment, matching prettier 3.9's `printDanglingCommentsInList`
    /// (prettier PRs #18617 / #18615): a block comment that fits stays inline
    /// (`[/* c */]`, `{/* c */}`); a line comment can't be inlined and forces
    /// the break, and an overflowing or multi-line block comment breaks via the
    /// enclosing group. `sep` is the open/close separator — `softline` (no
    /// space) for brackets, object literals/patterns, enum bodies and the empty
    /// import-attribute clause (`with {}`), `line` (bracket spacing) for type
    /// literals. Containers that always break with a dangling comment (class,
    /// interface, and namespace bodies) pass a `hardline`
    /// ([`Self::build_empty_body_with_comments_doc`]).
    ///
    /// `opening` and `closing` are the delimiters' docs, built by the caller where
    /// their spelling is a literal (a constant there rather than a runtime match
    /// here); `opening` may carry a prefix, e.g. a parenthesized-intersection `(A & {`.
    /// The empty body stays delimiter-tight when comment-free (`{}` not `{ }`), so a
    /// union-member or paren-intersection object type that reaches the alignment path
    /// prints with no spurious bracket space and preserves any interior comment.
    pub(crate) fn build_empty_bracketed_with_comments_doc(
        &self,
        span_start: u32,
        span_end: u32,
        opening: DocId,
        closing: DocId,
        sep: DocId,
    ) -> DocId {
        let d = self.d();
        let body_start = span_start + 1; // After opening delimiter
        let body_end = span_end.saturating_sub(1); // Before closing delimiter

        // The common body holds no comment: answered before the run is collected, so the
        // empty run is never built.
        if self.gap_known_comment_free(body_start, body_end) {
            return d.concat(&[opening, closing]);
        }
        let comments: CommentVec<'_> = self
            .comments_to_emit_between(body_start, body_end)
            .collect();

        if comments.is_empty() {
            return d.concat(&[opening, closing]);
        }

        let mut comment_parts = DocBuf::new();
        self.push_dangling_comment_run(&mut comment_parts, comments.iter().copied());

        // A line comment can't be inlined, so it forces the break; a fitting
        // block comment stays inline (the group breaks on overflow / a multi-line
        // block comment's own hardlines).
        let has_line = comments.iter().any(|c| !c.is_block);
        let close_sep = if has_line { d.hardline() } else { sep };

        d.group(d.concat(&[
            opening,
            d.indent(d.concat(&[sep, d.concat(&comment_parts)])),
            close_sep,
            closing,
        ]))
    }

    /// Append the comments between a signature's last content token and the
    /// member's end (typically right before the printed `;`): after the return
    /// type, or after the params' closing `)` when there is no return type.
    /// Same-line comments stay with the member (a block inline, a line via
    /// `line_suffix`); an **own-line** comment is deferred to `deferred` (own line,
    /// blank preserved) for the caller to emit **after** the `;`, matching prettier
    /// (the member doc doesn't own the `;`). `deferred` is empty on the common
    /// no-comment path.
    ///
    /// Shared by method/call/construct signatures in interfaces and type literals
    /// and by declare functions (all use the type-member `;` binding —
    /// `split_member_terminator_gap_comments`).
    pub(crate) fn append_signature_end_comments(
        &self,
        parts: &mut DocBuf,
        return_type: Option<&ast::TSTypeAnnotation<'_>>,
        paren_pos: Option<u32>,
        span_end: u32,
        deferred: &mut DocBuf,
        clause_tail: Option<u8>,
    ) {
        let content_end = return_type.map_or_else(
            || {
                paren_pos
                    .and_then(|p| self.find_closing_paren(p, span_end))
                    .unwrap_or(span_end)
            },
            |rt| rt.span.end,
        );
        // `clause_tail` reaches only the statement caller (`declare function` — the
        // canonical parser accepts it as a clause body, where the gap must defer like
        // every other `;` tail there); the type members are always list-joined.
        let deferral = self.terminator_gap_deferral(clause_tail);
        self.push_gap_comments(
            parts,
            deferred,
            content_end,
            span_end,
            GapBinding {
                block_after: false,
                preserve_blank: true,
            },
            deferral,
        );
    }

    /// Partition the comments in a content→separator gap `[start, sep_pos)`, binding
    /// the separator (`,` / `;`) to the content the way prettier does:
    ///
    /// - a **same-line** comment is pushed to `parts` (before the separator) — a block
    ///   inline (`X /* c */<sep>`, preserved), a line via `line_suffix` (zero width, so
    ///   it floats past the separator to the next hardline → `X<sep> // c`) — *except*
    ///   that when `block_after_separator` is set a same-line **block** is instead
    ///   *returned* (deferred), so it trails **after** the separator (`X<sep> /* c */`);
    /// - an **own-line** comment is *returned* (not pushed), each on its own line
    ///   (`hardline` + comment), for the caller to emit **after** the separator so the
    ///   author's line break is kept and a `//` can't swallow the separator; when
    ///   `block_after_separator` (the `;`-terminator case), a single blank line before it
    ///   (relative to the content, then the previous comment) is also preserved
    ///   (`literalline`), matching prettier — the `,`-separator case keeps no blank
    ///   (prettier emits none in a list element→comma gap).
    ///
    /// `block_after_separator` is the prettier-3.9 behavior for the statement/member
    /// **`;` terminator** (the `;` is pure structure, so trailing a block past it is
    /// lossless — `expr; /* c */`); the list **`,` separator** passes `false` and keeps
    /// a same-line block before the comma (`X /* c */,`) — prettier did not change that.
    ///
    /// Caller idiom: `let after = self.split_comma_gap_comments(parts, elem_end,
    /// comma_pos); parts.push(","); parts.extend(after);`. Emitting an own-line comment
    /// *before* the separator would put the separator on the comment's line — a `//`
    /// swallows it (content loss), a block just diverges from prettier.
    ///
    /// The **comma's** binding of both axes: a same-line block stays before it, and a
    /// blank line above a deferred own-line comment does NOT survive it. Neither is a
    /// caller preference — the `;` terminators state their own through
    /// [`Self::push_semicolon_with_gap_comments`] (blank preserved at either block
    /// binding, since a `;` ends its line) and the type-member one through
    /// [`Self::split_member_terminator_gap_comments`].
    pub(crate) fn split_comma_gap_comments(
        &self,
        parts: &mut DocBuf,
        start: u32,
        sep_pos: u32,
    ) -> DocBuf {
        let mut deferred = DocBuf::new();
        self.push_gap_comments(
            parts,
            &mut deferred,
            start,
            sep_pos,
            GapBinding {
                block_after: false,
                preserve_blank: false,
            },
            GapDeferral::Break(self.d().hardline()),
        );
        deferred
    }

    /// The **for-header `;`** variant of
    /// [`split_comma_gap_comments`](Self::split_comma_gap_comments): the same
    /// binding (a same-line block stays before the `;`, no blank preserved), but the
    /// break onto the deferred run's **first** line is the header's own `line`.
    ///
    /// A statement or member terminator ends its line outright, so a `hardline` there
    /// states a fact about the construct. A `for` header does not: it is a group that
    /// decides its own width, and prettier reaches this run through the very `line` that
    /// follows the `;` in `printForStatement` — so a `hardline` answers a width question
    /// with a comment answer and forces open a header prettier keeps flat
    /// (`docs/comments.md` §Own-line-ness is a SOURCE question). Only the FIRST break is
    /// the caller's; every break *within* the run stays the shared site's, so two
    /// comments the author gave two lines still take two.
    ///
    /// A `//` in this gap is still safe from the flat rendering — it would swallow the
    /// clauses behind it — because any line comment inside the parens forces the header
    /// open through `build_for_header_doc`'s own `has_line_comment_in_header`, which
    /// covers the whole paren interior and so strictly contains this gap.
    pub(crate) fn split_for_header_gap_comments(
        &self,
        parts: &mut DocBuf,
        start: u32,
        sep_pos: u32,
    ) -> DocBuf {
        let mut deferred = DocBuf::new();
        self.push_gap_comments(
            parts,
            &mut deferred,
            start,
            sep_pos,
            GapBinding {
                block_after: false,
                preserve_blank: false,
            },
            GapDeferral::Break(self.d().line()),
        );
        deferred
    }

    /// The `;`-terminator family's deferral axis, from the statement CONTAINER's fact
    /// (`StatementContext::clause_tail`): in a statement LIST the joiner's break
    /// immediately follows the statement doc, so the gap's own-line run takes real
    /// breaks; a non-block CLAUSE body's tail line stays open to the enclosing
    /// construct, so the run rides in `line_suffix` docs (dedented to the flushing
    /// construct's level) and meets any later gap's suffix at the flush in source
    /// order.
    fn terminator_gap_deferral(&self, clause_tail: Option<u8>) -> GapDeferral {
        clause_tail.map_or_else(
            || GapDeferral::Break(self.d().hardline()),
            GapDeferral::LineSuffix,
        )
    }

    /// The gap-split caller idiom for a **`;` terminator**, in one call: the gap's pre-`;` comments, the `;`,
    /// then the comments that belong after it.
    ///
    /// The ordering is the reason this exists rather than three lines at each site: the
    /// returned docs must be pushed *after* the `;` text, and a site that inlines the
    /// idiom can invert it silently — an own-line comment emitted before the separator
    /// puts the `;` on the comment's line, where a `//` swallows it outright.
    ///
    /// `block_after_separator` is the terminator's own axis, not a caller preference:
    /// `true` for a statement/member `;` (prettier trails a same-line block past it —
    /// `expr; /* c */`), `false` where the operand keeps it (`import =` / `export =` /
    /// `export as namespace`, the ambient module shorthand). A caller whose split is
    /// *conditional* keeps the raw idiom.
    ///
    /// ⚠️ **The blank rule is the SEPARATOR's, not that axis's.** A `;` terminator ends
    /// its line, so an author blank above a deferred own-line comment survives it in
    /// prettier — at *both* block bindings, since where the same-line block sits says
    /// nothing about what an own-line comment two lines down is worth. Reading the blank
    /// off `block_after_separator` — which is the **comma's** rule
    /// ([`Self::split_comma_gap_comments`]), not a `;`'s — silently dropped it at every
    /// `false` site;
    /// this passes `preserve_blank` unconditionally, which is also what makes this and
    /// [`Self::split_member_terminator_gap_comments`] one answer rather than two.
    ///
    /// The gap's far end is derived from `span_end` — the node's own end — rather than
    /// taken from the caller, because "where is my `;`" has one answer and every
    /// terminator here is **optional under ASI**. Where the author wrote one the span
    /// runs through it, so the `;` is the byte before `span_end`; where ASI ended the
    /// statement the span stops at its content, and the subtraction every caller used to
    /// spell inline lands *inside* that content instead — the assumed-delimiter-position
    /// hazard, harmless only because the resulting range happens to be empty. Stating it
    /// once keeps it that way by construction.
    pub(crate) fn push_semicolon_with_gap_comments(
        &self,
        parts: &mut DocBuf,
        content_end: u32,
        span_end: u32,
        block_after_separator: bool,
        clause_tail: Option<u8>,
    ) {
        let semicolon_pos = Self::semicolon_pos(content_end, span_end);
        self.push_semicolon_gap_bounded(
            parts,
            content_end,
            semicolon_pos,
            block_after_separator,
            clause_tail,
        );
    }

    /// [`Self::push_semicolon_with_gap_comments`] over a gap whose far end the caller
    /// states, rather than the `;`'s own position.
    ///
    /// The two differ only for a statement that hands its terminator gap to the enclosing
    /// LIST ([`Self::push_statement_semicolon`]): there the node's claim stops at the start
    /// of the trailing trivia run, which is *not* the `;` whenever the printer keeps a `)`
    /// in between (`const a = (b /* c */);` — the comment is inside the shell and stays this
    /// node's, while anything past the `)` is the list's).
    fn push_semicolon_gap_bounded(
        &self,
        parts: &mut DocBuf,
        content_end: u32,
        gap_end: u32,
        block_after_separator: bool,
        clause_tail: Option<u8>,
    ) {
        if !self.has_comments_to_emit_between(content_end, gap_end) {
            // `push_gap_comments`' own zero-comment gate, asked here first: with nothing to
            // emit, the deferred run's buffer and the deferral need not exist, and the
            // terminator is the bare `;` — the common case by a wide margin.
            parts.push(self.d().text(";"));
            return;
        }
        let deferral = self.terminator_gap_deferral(clause_tail);
        let mut after = DocBuf::new();
        self.push_gap_comments(
            parts,
            &mut after,
            content_end,
            gap_end,
            GapBinding {
                block_after: block_after_separator,
                preserve_blank: true,
            },
            deferral,
        );
        parts.push(self.d().text(";"));
        parts.extend(after);
    }

    /// The `;` terminator for a **statement**, whose gap comments are the one kind a node
    /// does not print itself.
    ///
    /// [`Printer::statement_comment_claim_end`] (prettier's `__contentEnd`) ends a
    /// `;`-terminated statement at its CONTENT, so a comment the author left between that
    /// content and the `;` is not inside the statement at all — it falls in the gap BETWEEN
    /// two statements, where the ordinary own-line / same-line split decides whether it
    /// trails the statement before it or leads the one after
    /// ([`Self::comment_leads_next_item`]). In a statement LIST that seam is right there, so
    /// this emits the bare `;` and lets it claim the run: `a()⏎/* c */;⏎b();` prints
    /// `a();⏎/* c */ b();`, the comment leading `b()` glued to the pure separator it was
    /// written against.
    ///
    /// ⚠️ **The two sides must PARTITION the gap** (`docs/comments.md` §The element-comma
    /// seam states the rule for its own seam; this is the same obligation): emitting here as
    /// well is a DOUBLE-PRINT, and lowering the list's cursor without stopping here is what
    /// would cause it. The list's cursor is the same predicate
    /// ([`Self::statement_gap_scan_start`]), which is why neither side re-spells it.
    ///
    /// A **clause body** (`if (a) foo()⏎/* c */;`) is not a list member and has no such seam,
    /// so nothing downstream would ever emit the run: it keeps the node-owned split
    /// ([`Self::push_semicolon_with_gap_comments`]) and its `line_suffix` deferral. That is
    /// the whole of the axis — `clause_tail` already carries it.
    ///
    /// The KIND table is read on the list side rather than here, so a `;` prettier does not
    /// eject — a `TSImportEqualsDeclaration`, a class property, a type-literal member — never
    /// reaches this at all; those sites call the node-owned emitter directly.
    pub(in crate::printer) fn push_statement_semicolon(
        &self,
        parts: &mut DocBuf,
        content_end: u32,
        span_end: u32,
        gap: TerminatorGap,
    ) {
        let claim_end = self.node_terminator_claim_end(content_end, span_end, gap);
        self.push_semicolon_gap_bounded(parts, content_end, claim_end, true, gap.clause_tail());
    }

    /// The upper bound a **node's own** `;`-terminator gap emitter may claim to.
    ///
    /// `content_end` for a clause body, which owns its whole gap; otherwise the start of the
    /// trailing trivia run ([`Printer::trivia_run_start`]), because everything from there to
    /// the `;` is the enclosing statement LIST's ([`Self::push_statement_semicolon`]). The
    /// two emitters that ask are the only ones whose callers are statements prettier ejects.
    ///
    /// The `;` is located the way [`Self::semicolon_pos`] locates it, but from the source
    /// rather than from a span: one caller passes the `;`'s own position as `span_end` and
    /// the other the statement's end, and the trailing byte answers both.
    pub(in crate::printer) fn node_terminator_claim_end(
        &self,
        content_end: u32,
        span_end: u32,
        gap: TerminatorGap,
    ) -> u32 {
        if !gap.list_claims() {
            return span_end;
        }
        let semicolon_pos = if span_end > content_end
            && self.source.as_bytes().get(span_end as usize - 1) == Some(&b';')
        {
            span_end - 1
        } else {
            span_end
        };
        self.trivia_run_start(content_end, semicolon_pos)
    }

    /// Where a statement's `;` sits: the span's last byte when the span reaches past the
    /// content, else the content's end (a statement with no terminator of its own).
    fn semicolon_pos(content_end: u32, span_end: u32) -> u32 {
        if span_end > content_end {
            span_end - 1
        } else {
            content_end
        }
    }

    /// Whether the content→`;` gap holds no comment to emit — a caller's PRE-CHECK, for the
    /// one that can skip assembling a buffer when it holds (the expression statement, whose
    /// value doc is already in hand).
    ///
    /// The terminator emitters ask their own bounded form
    /// ([`Self::push_semicolon_gap_bounded`]), because a statement that hands its gap to the
    /// enclosing list claims only part of it. This is the wider question — any comment at all
    /// before the `;` — so it is sound as a pre-check in either direction: it never reports
    /// bare where the emitter would print something.
    pub(crate) fn semicolon_gap_is_bare(&self, content_end: u32, span_end: u32) -> bool {
        !self.has_comments_to_emit_between(content_end, Self::semicolon_pos(content_end, span_end))
    }

    /// The **type-member `;`** variant of the gap split: a same-line
    /// block stays *before* the `;` (`a: A /* c */;`, like a list separator) **but** a
    /// blank line before an own-line comment IS preserved (like a statement terminator).
    /// This mixed binding is what prettier does for a type-literal / interface member
    /// terminator, which neither of its two siblings' bindings expresses. Same
    /// caller idiom, into the caller's `deferred` (the own-line docs are emitted by the
    /// type-element *joiner* after its `;`, since the member doc doesn't own the `;`).
    pub(crate) fn split_member_terminator_gap_comments(
        &self,
        parts: &mut DocBuf,
        deferred: &mut DocBuf,
        start: u32,
        sep_pos: u32,
    ) {
        self.push_gap_comments(
            parts,
            deferred,
            start,
            sep_pos,
            GapBinding {
                block_after: false,
                preserve_blank: true,
            },
            GapDeferral::Break(self.d().hardline()),
        );
    }

    /// Where a separator gap's ANCHOR-LINE run ENDS — the split
    /// [`Self::push_gap_comments`] partitions on, and the one every caller that has to
    /// reason about the run it produced must re-ask.
    ///
    /// Stated as a POSITION rather than a per-comment predicate, the way the array
    /// literal's element seam states its own ([`Printer::element_gap_split`]): the run is a
    /// **prefix** of the gap by construction — positions increase, so once a comment opens a
    /// later line every comment behind it does too — and one split shared by its three
    /// readers (the partition itself, the deferred run's end, the blank-line scan's
    /// terminal) cannot drift into handing a caller a run the emitter never produced.
    ///
    /// The run **follows a multi-line block to its closing `*/` line**, the same walk
    /// [`Self::trailing_same_line_comments`] and the element seam make: a comment the author
    /// glued past that `*/` trails the gap the block trails (`a: A /* x⏎y */ /* c */;`)
    /// rather than reading as own-line and deferring past the separator. Asking a bare
    /// `is_same_line(anchor, …)` instead put every gap that routes here — the type-member
    /// and class-member terminators, a statement's own `;`, and the comma seam's parameter
    /// lists — at odds with the array literal and with prettier, and the resulting form is
    /// not even a fixed point (the reprint has the comment leading the next item, where its
    /// own line reads as authored).
    ///
    /// The walk is the **in-source** axis: an owned comment's bytes sit on the page and
    /// carry the line reference like any other's, exactly as
    /// [`Self::comment_leads_next_item`]'s glue chain does.
    ///
    /// ⚠️ **Scoped to the region BEFORE the comma.** Past the comma the anchor is the
    /// comma itself ([`Printer::comment_on_comma_line`]) — the author may have pushed the
    /// separator onto a line of its own, and the printer pulls it back, so an
    /// element-anchored reading there re-binds the comment to the next item.
    ///
    /// ⚠️ **An anchor reading, deliberately** — not the source reading
    /// ([`Printer::comment_follows_content_on_its_line`]) the element→comma SEAM asks.
    /// This gap's anchor is the element's own end and the question is which side of the
    /// separator the comment renders on, not which element it binds to.
    pub(in crate::printer) fn gap_anchor_line_end(&self, anchor: u32, upper_bound: u32) -> u32 {
        let mut line_ref = anchor;
        let mut end = anchor;
        for comment in self.comments_in_source_between(anchor, upper_bound) {
            if !self.is_same_line(line_ref, comment.span.start) {
                break;
            }
            // Follow multi-line block comments to their closing line
            if comment.is_block && !self.is_same_line(comment.span.start, comment.span.end) {
                line_ref = comment.span.end;
            }
            end = comment.span.end;
        }
        end
    }

    /// Core of the gap-comment partition, with the two policy axes decoupled:
    /// `block_after` moves a **same-line block** past the separator (deferred), and
    /// `preserve_blank` keeps a single blank line before a deferred **own-line** comment
    /// (`literalline`). A same-line line comment always uses `line_suffix` (zero width,
    /// floats past the separator); an own-line comment is deferred on its own
    /// `hardline`. `prev` tracks the content/prior-comment end for blank detection.
    ///
    /// ⚠️ **"Own-line" is per comment, so the deferred run asks the glue question**
    /// ([`Self::trailing_run_hugs_previous`]) like every other trailing run — a bare
    /// `hardline` between two comments the author wrote on ONE line splits the pair
    /// (`docs/comments.md` §Trailing and dangling runs: the separator is one question
    /// wherever a run is emitted). This gap is a run at five constructs at once — a
    /// statement's own `;`, a class member's, a type member's, a `for` head's, a
    /// declarator's — so the drift was five divergences from one line. The site keeps
    /// its own non-glue arm because its blank rule is the caller's (`preserve_blank`),
    /// which is the sanctioned shape for asking the predicate directly.
    ///
    /// The hug can only ever bind two comments the anchor-line split already put on the
    /// same side: a deferred comment sharing a source line with an anchor-line one is
    /// impossible, since [`Self::gap_anchor_line_end`] follows that line (a multi-line
    /// block included) to its end.
    ///
    /// `first_break` is the third axis, and the narrowest: the break onto the deferred
    /// run's **first** line, which is the one break this gap does not own — it belongs to
    /// whatever precedes the separator. A statement or member terminator ends its line
    /// outright and passes `hardline`; a `for` header is a group that decides its own
    /// width and passes its own `line`
    /// ([`Self::split_for_header_gap_comments`]). Every break *within* the run is this
    /// site's and stays a `hardline`, so the caller can only move the run's first line,
    /// never merge two lines the author wrote.
    ///
    /// The deferred run goes into the caller's `deferred` rather than a buffer of this
    /// function's own: every `;` and member terminator holds one already, and the run is
    /// empty at nearly all of them.
    fn push_gap_comments(
        &self,
        parts: &mut DocBuf,
        deferred: &mut DocBuf,
        start: u32,
        sep_pos: u32,
        binding: GapBinding,
        deferral: GapDeferral,
    ) {
        let GapBinding {
            block_after,
            preserve_blank,
        } = binding;
        let d = self.d();
        let mut prev = start;
        let mut gap = self.comments_to_emit_between(start, sep_pos).peekable();
        // Zero-comment fast gate: the split is a search of its own, and every `;`-gap
        // caller (a `const`'s terminator, a `for` head) asks on documents that mostly have
        // no comment here at all. Safe to skip when the to-emit range is empty even though
        // the split reads the IN-SOURCE axis: an all-owned gap classifies nothing, so the
        // value would go unused.
        let anchor_line_end = if gap.peek().is_some() {
            self.gap_anchor_line_end(start, sep_pos)
        } else {
            start
        };
        let mut prev_comment: Option<&ast::Comment> = None;
        // Whether the deferred run has been opened — the `first_break` axis is about the
        // break INTO the run, so it is spent once and never on a later comment. Tracked
        // rather than read off `prev_comment`, which the anchor-line arm also sets, or off
        // `deferred`, which `block_after` may already have pushed a trailing block into.
        let mut deferred_open = false;
        for comment in gap {
            if comment.span.start < anchor_line_end {
                if block_after && comment.is_block {
                    deferred.push(self.build_trailing_comment_doc(comment));
                } else {
                    parts.push(self.build_trailing_comment_doc(comment));
                }
            } else {
                // The author's blank above this comment — the one question BOTH deferrals
                // ask, which they then spell differently: `Break` as a `literalline` ahead
                // of the break, `LineSuffix` as the flag the suffix builder carries inside.
                let blank = preserve_blank && self.has_blank_line_between(prev, comment.span.start);
                match deferral {
                    GapDeferral::Break(first_break) => {
                        // The separator, BEFORE the comment — a space where the author
                        // glued the pair, otherwise a break: the caller's onto the run's
                        // first line, this site's own after that (the caller owns the
                        // blank rule).
                        if self.trailing_run_hugs_previous(prev_comment, comment.span.start) {
                            deferred.push(d.text(" "));
                        } else {
                            if blank {
                                deferred.push(d.literalline());
                            }
                            deferred.push(if deferred_open {
                                d.hardline()
                            } else {
                                first_break
                            });
                        }
                        deferred_open = true;
                        deferred.push(self.build_comment_doc(comment));
                    }
                    // Every member takes its own break, INSIDE the suffix, at the flushing
                    // construct's level.
                    //
                    // ⚠️ No glue arm here, unlike `Break` — the two deferrals want OPPOSITE
                    // answers on a run the author wrote on one line, and the asymmetry is the
                    // rule rather than an oversight. `Break` reaches gaps whose run is emitted
                    // ONCE (a `,` gap, a `for` head, a type member's `;`), where prettier keeps
                    // the author's gluing and so does tsv. This arm reaches only the clause
                    // bodies whose tail stays OPEN to a continuing construct — `if`+`else`,
                    // do-while, and a declaration in clause position (a `type` alias,
                    // `declare function`, shorthand `declare module 'm'`) — where the SAME gap
                    // is read again from the ejected seam once the `;` normalizes ahead of the
                    // run, and that seam breaks between members. Keeping the glue here gave one
                    // document two shapes: it printed on one line and split on the next pass.
                    // Cataloged in `docs/conformance_prettier_ts_comments.md` §Comment
                    // normalization (stable quirks).
                    GapDeferral::LineSuffix(dedent) => {
                        deferred.push(self.build_clause_tail_comment_doc(comment, blank, dedent));
                    }
                }
            }
            prev = comment.span.end;
            prev_comment = Some(comment);
        }
    }

    /// Append the leading block-comment run between two positions — the sole type
    /// argument's `<`→argument gap on its inline hug path.
    ///
    /// Only block comments; line comments are skipped (they were detected earlier and
    /// routed the list to its expansion path). Counterpart of
    /// [`Self::append_trailing_inline_block_comments`], but the run itself goes through the
    /// one leading emitter ([`Self::push_leading_comment_run`], `LeadingGlue::Adjacent`)
    /// rather than an unconditional space: a block the author broke after — here only one
    /// FOLLOWED by another comment, since a run whose last block breaks after declines the
    /// hug outright (`single_type_arg_run_breaks_after`) — takes prettier's soft `line`,
    /// which collapses while the enclosing group fits and breaks with it, always under a
    /// multi-line block. The space re-glued a run the author had split, which a shelled
    /// authoring of the same run — whose emitter keeps the split — then converged to only
    /// on its second pass.
    pub(crate) fn append_leading_inline_block_comments(
        &self,
        parts: &mut DocBuf,
        start: u32,
        end: u32,
    ) {
        self.push_leading_comment_run(
            parts,
            self.comments_to_emit_between(start, end)
                .filter(|c| c.is_block),
            end,
            LeadingGlue::Adjacent,
        );
    }

    /// One inline list-position block comment plus its separating space, as **one** part.
    ///
    /// One part, not two: a caller may be filling a `fill`, whose parts alternate content
    /// and separator, so a second `parts.push` would shift every pair after it. A `concat`
    /// is one `DocId`, which is what lets the indentable arm below exist at all.
    ///
    /// ⚠️ An **indentable** multi-line block does not reprint as its own source span — its
    /// continuation lines are re-indented to the emitting column
    /// ([`Printer::build_comment_doc`]), which is what prettier does at every one of these
    /// positions. Emitting the raw span left `A<T /** c⏎ */>` and the import-attribute key
    /// gap printing the author's original column, a divergence **no formatted corpus can
    /// see** — tsv's output is its own fixed point, so only an unformatted authoring
    /// separates the two. Every other shape (single-line, and a *preserved* multi-line
    /// block, whose interior is verbatim by definition) reprints as its span, so it keeps
    /// the one-text-node form and the space fuses into it.
    fn inline_block_comment_doc(&self, comment: &'a ast::Comment, side: InlineBlockSide) -> DocId {
        let d = self.d();
        if self.block_comment_is_indentable(comment) {
            let comment_doc = self.build_comment_doc(comment);
            let space = d.text(" ");
            return match side {
                InlineBlockSide::Leading => d.concat(&[comment_doc, space]),
                InlineBlockSide::Trailing => d.concat(&[space, comment_doc]),
            };
        }
        let mut w = d.pool_writer();
        if side == InlineBlockSide::Trailing {
            w.push(' ');
        }
        w.push_str(comment.span.extract(self.source));
        if side == InlineBlockSide::Leading {
            w.push(' ');
        }
        let doc = w.finish_text();
        // A comment emission that can't route through `build_comment_doc` (the space
        // must share the node), so it tags its own ledger node.
        #[cfg(feature = "_internal_comment_check")]
        d.tag_comment_doc(doc, comment.span, self.source);
        doc
    }

    /// Append trailing inline block comments (` /*content*/` format) between two positions.
    ///
    /// Only emits block comments; line comments are skipped (they would have been
    /// detected earlier and routed to the multiline path).
    pub(crate) fn append_trailing_inline_block_comments(
        &self,
        parts: &mut DocBuf,
        start: u32,
        end: u32,
    ) {
        for comment in self.comments_to_emit_between(start, end) {
            if comment.is_block {
                parts.push(self.inline_block_comment_doc(comment, InlineBlockSide::Trailing));
            }
        }
    }

    /// Split the last list-member's trailing inline block comments around a source
    /// comma (in `elem_end..end_boundary`): comments before the comma go to `before`,
    /// comments after it to `after`. Callers emit `after` past where the comma was
    /// (no trailing comma; trailingComma: 'none') so the comment is preserved after it
    /// rather than relocated before (see conformance_prettier_ts_comments.md §Comment relocation).
    pub(crate) fn append_last_trailing_block_comments_split(
        &self,
        before: &mut DocBuf,
        after: &mut DocBuf,
        elem_end: u32,
        end_boundary: u32,
    ) {
        // Zero-comment fast gate: with no comment in the window, both splits emit
        // nothing wherever the comma is — skip the comma scan entirely.
        if !self.has_comments_to_emit_between(elem_end, end_boundary) {
            return;
        }
        match self.find_comma_in_range(elem_end, end_boundary) {
            Some(comma_pos) => {
                self.append_trailing_inline_block_comments(before, elem_end, comma_pos);
                self.append_trailing_inline_block_comments(after, comma_pos, end_boundary);
            }
            None => self.append_trailing_inline_block_comments(before, elem_end, end_boundary),
        }
    }

    /// Emit comma with surrounding comments for a non-last element in a forced-multiline list.
    ///
    /// Handles comment positioning around the comma between `elem_end` and `next_start`:
    /// 1. Trailing comments before comma (multiline layout)
    /// 2. Comma text
    /// 3. Same-line trailing comments after comma (line comments)
    /// 4. Hardline separator
    ///
    /// Returns the new `prev_end` position.
    ///
    /// `blank_rule` keeps a blank line the author left *before* the next element (or its
    /// own-line leading comment, `A,⏎⏎/* c */⏎B`), and says from WHERE it is measured — a
    /// per-family fact, not a preference (see [`BlankRule`]). Prettier preserves the blank
    /// for **tuples** ([`BlankRule::AfterComma`], measured past the comma) and
    /// **function-type param lists** (function/constructor types, method/call/construct
    /// signatures — [`BlankRule::NextLineEmpty`], measured from the element's end, same as
    /// regular function params), and collapses it for type-parameter / type-argument lists
    /// ([`BlankRule::None`]).
    pub(crate) fn emit_multiline_comma_with_comments(
        &self,
        parts: &mut DocBuf,
        elem_end: u32,
        next_start: u32,
        blank_rule: BlankRule,
    ) -> u32 {
        let d = self.d();
        let comma_pos = self.find_list_comma(elem_end, next_start);

        // The comma binds to the element; same-line gap comments stay before it
        // (block inline, line via `line_suffix`), own-line ones defer to after it
        // (leading the next element). A same-line block stays *before* the comma
        // — prettier 3.9 only moved the `;` case. See `split_comma_gap_comments`.
        let deferred_own_line = self.split_comma_gap_comments(parts, elem_end, comma_pos);

        // This gap's anchor-line split ([`Self::gap_anchor_line_end`]), resolved ONCE for
        // the three readers below — the deferred run's last comment, and each of the two
        // blank-scan arms. It is the same question the emitter above partitioned on, and a
        // reader that re-asks it is a reader that can be given a different answer.
        //
        // The bound is the WIDER `next_start`: that is what the blank scan needs, and it
        // costs the before-comma readers nothing, since the run is a prefix — over
        // `[elem_end, comma_pos)` the two bounds classify identically.
        let anchor_line_end = self.gap_anchor_line_end(elem_end, next_start);
        let last_deferred = self
            .comments_to_emit_between(elem_end, comma_pos)
            .filter(|c| c.span.start >= anchor_line_end)
            .last();

        // A deferred run LEADS the next element, so its last comment takes the
        // leading-comment separator, not this emitter's element hardline: a space when the
        // author glued it to what follows on its line ([`Printer::comment_hugs_next`],
        // prettier's `printLeadingComment`), which for a list is the comma the comment sits
        // in front of (`[a⏎/* c */, b]`). Answering it with the element separator instead
        // drops such a comment onto a line of its own — a third form, and one that puts
        // this family at odds with the array literal, whose per-element group collapses
        // the same soft `line` (`docs/comments.md` §Array family vs params family).
        //
        // Not onto an honored directive leading the next element, which owns its line
        // ([`Printer::directive_follows`]): glued behind this run it would be inert.
        let deferred_hugs = !deferred_own_line.is_empty()
            && last_deferred.is_some_and(|c| self.comment_hugs_next(c))
            && !self.directive_follows(
                self.comments_to_emit_between(comma_pos + 1, next_start)
                    .next(),
            );
        parts.push(d.text(","));
        if deferred_hugs {
            // An author blank line belongs AHEAD of a hugging run, where it was written —
            // between the element and the comment. The element separator below can only
            // put it after, which for a glued run would split the comment from the item it
            // leads.
            //
            // ⚠️ **WHICH blank counts is still the caller's list kind**, exactly as it is
            // in the tail below: a hugging run moves where the `literalline` goes, not
            // which region is measured. Answering `NextLineEmpty` for every family
            // emitted a blank in the TUPLE (`[aaaa⏎⏎/* c */, bbbb]`) that prettier
            // collapses — and the fabricated form is stable, so F1, the ledger and
            // `blanks:audit` are all blind to it.
            if self.separator_gap_has_blank(
                blank_rule,
                elem_end,
                comma_pos + 1,
                next_start,
                anchor_line_end,
            ) {
                parts.push(d.literalline());
            }
            parts.extend(deferred_own_line);
            parts.push(d.text(" "));
            return comma_pos + 1;
        }
        parts.extend(deferred_own_line);

        // Trailing comments after the comma, claimed by kind. A line comment goes through
        // `line_suffix` (zero width) so it never forces the preceding element to break;
        // it flushes at the hardline below (prettier's `lineSuffix`). A block stays
        // inline, width counted.
        //
        // ⚠️ **The block arm asks the HUG question, not a trailing one.** A block the
        // author glued to the next item (`A, /* c */ B`) is that item's leading comment at
        // every other site and in prettier, so claiming it here tears it off the item it
        // was written against — which an anchor-line test does, since the next item sits
        // on a later line in this forced-multiline layout. `is_stranded_after_comma_block`
        // is the single spelling of the split (§Comment relocation): stranded stays
        // trailing the comma, hugging leads the next item. A block ahead of a same-line
        // `//` is stranded by that predicate and stays claimed — the line comment defers
        // through `line_suffix`, so a block left to lead the next item would render after
        // it and the authored pair would come back reversed.
        //
        // A **line** comment on the comma's line is claimed: nothing can follow a `//` on
        // its line, so it has no hug question to ask. Its anchor is the comma, not the
        // element — an author who pushed the comma onto its own line (`a⏎, // c⏎ b`) wrote
        // the comment against the comma, and the printer pulls the comma back onto the
        // element's line, so an element-anchored reading led it onto the NEXT item.
        //
        // ⚠️ **The claimed run ENDS at the first `//` this gap has already emitted** —
        // including one from *before* the comma (`a // c1⏎, // c2⏎ b` folds two source
        // lines onto one output line), which is why the scan opens at `elem_end` rather
        // than at the comma. See [`Printer::gap_emitted_line_comment_before`] for what a
        // claim past that point welds or reorders.
        let mut after_comma_end = comma_pos + 1;
        for comment in self.comments_to_emit_between(comma_pos + 1, next_start) {
            if self.gap_emitted_line_comment_before(elem_end, comment.span.start) {
                break;
            }
            let claimed = if comment.is_block {
                self.is_stranded_after_comma_block(comment, comma_pos, next_start)
            } else {
                self.comment_on_comma_line(comma_pos, comment)
            };
            if claimed {
                parts.push(self.build_trailing_comment_doc(comment));
                after_comma_end = comment.span.end;
            }
        }

        // Hardline to separate from next element, optionally preserving an author blank line
        // before the next own-line leading comment. WHICH blank counts is the caller's list
        // kind, not this emitter's business — see [`BlankRule`].
        if self.separator_gap_has_blank(
            blank_rule,
            elem_end,
            after_comma_end,
            next_start,
            anchor_line_end,
        ) {
            parts.push(d.literalline());
        }
        parts.push(d.hardline());

        after_comma_end
    }

    /// Whether this element→element gap holds an author blank line the list **preserves**,
    /// under the caller's family rule ([`BlankRule`]).
    ///
    /// Both of [`Self::emit_multiline_comma_with_comments`]'s separator arms ask it — the
    /// hugging one, which emits the `literalline` ahead of the deferred run, and the tail,
    /// which emits it after the comma. They differ only in where the region past the comma
    /// opens (`from`); the RULE is the list kind and must not change with the arm. Asking
    /// one arm's question in the other's spelling gave the TUPLE a blank prettier collapses
    /// — stable output, so F1, the ledger and `blanks:audit` were all blind to it.
    ///
    /// **in source**: `next_lead` bounds a raw blank-line scan, which cannot tell a
    /// comment's own newlines from an author's blank line — so it must stop at every
    /// comment in the gap, not just the ones this caller emits.
    ///
    /// `anchor_line_end` is the gap's anchor-line split ([`Self::gap_anchor_line_end`]),
    /// passed in rather than re-derived: the caller already resolved it for the deferred
    /// run's separator, and the comment this scan stops at must be the first one that
    /// emitter DEFERRED — a second derivation is a second chance to disagree about which
    /// that is.
    fn separator_gap_has_blank(
        &self,
        blank_rule: BlankRule,
        elem_end: u32,
        from: u32,
        next_start: u32,
        anchor_line_end: u32,
    ) -> bool {
        if blank_rule == BlankRule::None {
            return false;
        }
        let next_lead = self
            .comments_in_source_between(from, next_start)
            .find(|c| c.span.start >= anchor_line_end)
            .map_or(next_start, |c| c.span.start);
        match blank_rule {
            // Measured from the ELEMENT's end, so a blank the author put before the
            // comma still counts — and one after a comma pushed onto its own line
            // does not.
            BlankRule::NextLineEmpty => self.is_next_line_empty(elem_end, next_lead),
            // Measured from past the comma, prettier's array/tuple rule. **Strict**:
            // the next element's span can begin inside a paren shell the printer
            // strips (a tuple element's `[a,⏎(⏎/* c */⏎b)]`), and the newline before
            // that `(` plus the one after it read as an author blank line to the
            // table lookup — emitting a blank the reparse then reads back as real.
            //
            // Strict removes the FABRICATED blank, not every blank the shell touches:
            // a blank the author actually typed inside the shell (`[a,⏎(⏎⏎/* c */⏎b)]`)
            // still has a whitespace-only line to find, so it survives the strip and
            // leads the element, where prettier drops it. Defensible — the author did
            // write the blank, and the result is stable — but it is a divergence, not
            // an equivalence.
            BlankRule::AfterComma => self.has_blank_line_between_strict(from, next_lead),
            // Bailed out above; spelled here so the match stays total.
            BlankRule::None => false,
        }
    }
}