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
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
// Stripped-grouping-paren comment handling.
//
// When the parser strips redundant grouping parens, comments that lived inside
// them are orphaned in the source. These helpers preserve such comments in the
// user's position — trailing the expression, promoted before `=` / an operator,
// re-added with the parens when stripping would relocate them, or prepended at a
// chain base.

use super::{CommentSpacing, CommentVec, LeadingGlue, Printer, RunLeadingBlank, ShareSite};
use crate::ast;
use crate::printer::ParenContext;
use crate::printer::chain::{
    chain_mid_chain_paren_gaps, chain_paren_leading_gap, tag_paren_leading_start,
};
use crate::printer::expressions::conditional::ternary_test_needs_parens;
use crate::printer::expressions::operators::SeqLayout;
use crate::printer::ignore::FrozenOperandPair;
use crate::printer::needs_parens::needs_parens;
use crate::printer::statements::TerminatorGap;
use smallvec::{SmallVec, smallvec};
use tsv_lang::Span;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::arena::DocId;
use tsv_lang::range_too_narrow_for_a_comment;
use tsv_lang::source_scan::{
    TriviaProfile, find_char_skipping_comments, has_newline_after_position,
    has_newline_before_position, skip_trivia,
};

/// What follows a stripped grouping shell, and so whether a trailing block comment has a
/// statement terminator to defer past.
///
/// The distinction cannot be read off the source at the shell: both spellings put a `;`
/// there, and only the POSITION knows whether it TERMINATES a statement or SEPARATES a
/// clause. Reading the byte alone sent a `for` header's init comment past the header's
/// own separator, out of the declarator that owned it.
///
/// Two positions name the tail outright — the header's own declarator and sequence-operand
/// builders ([`Printer::build_for_init_value_doc`]) — and every other value shell asks
/// [`Printer::shell_closes_for_clause`], whose answer is a fact about the shell's own
/// BOUNDARY rather than about the value's kind or the frame it was reached through.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ShellTail {
    /// A statement value position — a declarator initializer, an assignment RHS, a
    /// `return` / `throw` argument, `export default`. A following `;` ends the statement,
    /// so a trailing block defers past it (see [`Printer::build_expression_doc_with_paren_comments`]).
    StatementTerminator,
    /// A `for` header CLAUSE's own value — the init declarator, the last operand of a
    /// clause that is a sequence, and every value whose shell closes where the clause does
    /// ([`Printer::shell_closes_for_clause`]). A following `;` separates clauses, so nothing
    /// defers.
    ForClauseSeparator,
}

/// Which leading runs [`Printer::leading_run_reparses_owned`] may call owned on the reparse:
/// a lone glued block of either line count (a REQUIRED pair, whose shell prints the block
/// glued to the operand whatever its lines), or only a single-line one (the ASI operand
/// shell, which an owned multi-line block keeps).
#[derive(Clone, Copy, PartialEq, Eq)]
enum ReparsedRun {
    SingleLine,
    AnyLines,
}

/// How [`Printer::build_paren_leading_value_doc`] splits a `(`→value gap: the run the
/// `(` line keeps, the value with the rest of the run prepended, and whether the caller
/// must open its parens.
///
/// A struct rather than a tuple because the three travel together to two callers (the
/// dynamic-import EXPRESSION and the TS import TYPE) and two of them are trivially
/// swappable at a call site.
pub(crate) struct ParenLeadingValue {
    /// Emitted by the caller directly after its `(`, before any break. Empty unless a
    /// comment the author left on the `(` line was pulled onto it.
    pub paren_line: DocBuf,
    /// `value_doc` with the leading run that does *not* ride the `(` line prepended.
    pub value: DocId,
    /// Whether the gap ends a line unconditionally.
    pub forces_break: bool,
}

/// Whether a REQUIRED paren pair around `expr` — at a call callee or a tagged
/// template's tag — keeps a leading run INSIDE it.
///
/// A function or arrow is the one operand kind prettier prints the comments inside
/// those parens for (`isIifeCalleeOrTaggedTemplateExpressionTag` feeding its
/// `printCommentsForFunction`, `src/language-js/print/index.js`); every other
/// required pair at those positions — a ternary, a sequence, a cast, a class
/// expression, a `new` callee (whose parent is not a call at all) — takes the run
/// out in front, and tsv matches. Read by the three positions that print such a
/// pair: the bare callee, the tag, and the chain's IIFE base.
/// The expression's left-side child — prettier's `getLeftSide` over the node kinds its
/// `hasNakedLeftSide` names: the one node whose first token is also this node's first token
/// (`a.b`'s `a`, `a ? b : c`'s `a`, `a + b`'s `a`, `(a, b)`'s `a`, `f()`'s `f`, `` t`x` ``'s
/// `t`, `a = b`'s `a`, `a!`'s `a`). `None` for a leaf, and for every node whose left side
/// is not naked.
///
/// The gap between a node's own start and its left child's holds only the grouping `(`s
/// the parser stripped from that child — and any comment inside them
/// (`(⏎// c⏎a as any).b` opens the member at the `(`, the `as` at `a`). The structural
/// half of [`Printer::hoisted_left_side_child`], which is what every walk asks: whether
/// the printer HOISTS such a run ahead of the node is a fact about the pair, not the
/// kind, and lives there.
///
/// Prettier's walk also descends a cast's and a postfix update's operand
/// (`isBinaryCastExpression`, `UpdateExpression && !prefix`); this one does not, on
/// purpose. Those two positions answer a shell whose leading gap holds a comment
/// themselves ([`Printer::build_asi_operand_shell_doc`] — RETAINED, the cataloged "a
/// leading comment alone still keeps the shell that holds it", or printed inline ahead of
/// the operand, [`AsiOperandShell::Bare`]) and never hoist it, so the hoisting walk takes
/// their operand only where it prints first and bare — a question about the printed form,
/// answered by `Printer::bare_cast_operand`, not by this structural table.
fn left_side_child<'e>(expr: &'e ast::Expression<'e>) -> Option<&'e ast::Expression<'e>> {
    use ast::ExpressionKind;
    Some(match &expr.kind {
        ExpressionKind::CallExpression(call) => call.callee,
        ExpressionKind::MemberExpression(member) => member.object,
        ExpressionKind::TSNonNullExpression(non_null) => non_null.expression,
        ExpressionKind::TaggedTemplateExpression(tagged) => tagged.tag,
        ExpressionKind::ConditionalExpression(cond) => cond.test,
        ExpressionKind::BinaryExpression(binary) => binary.left,
        ExpressionKind::AssignmentExpression(assign) => assign.left,
        ExpressionKind::SequenceExpression(seq) => seq.expressions.first()?,
        _ => return None,
    })
}

/// Whether the [`left_side_child`] `child` of `expr` PRINTS inside a paren pair — the
/// position half of the left-spine walk, where [`left_side_child`] is the structural half.
///
/// One table, because "which paren context does a naked left side sit in?" has one answer
/// per parent kind and two askers with opposite needs:
/// [`Printer::left_shell_paren_is_emitted`] adds a source-shell precondition and reads it as
/// "is the erased shell RE-EMITTED", while the printed-spine walk
/// ([`printed_left_spine_step`]) reads it bare, as "does the printed form open on a `(`",
/// and so must see a pair the printer SYNTHESIZES too. Split
/// into two matches, the two would answer one position two ways the first time a builder's
/// context moved.
///
/// Each arm is the context the corresponding builder passes for that child — a member's
/// object is a [`ParenContext::ChainBase`], a call's callee a [`ParenContext::Callee`], and
/// so on — except the ternary test, whose pair is its own printer's question
/// ([`ternary_test_needs_parens`], shared by the inline, line-comment and frozen layouts).
/// A sequence answers `false`: its operands ride the sequence's OWN envelope, so an operand
/// never prints a pair of its own — the sequence's envelope is the CALLER's to notice.
fn left_side_child_is_parenthesized(
    expr: &ast::Expression<'_>,
    child: &ast::Expression<'_>,
    in_for_init: bool,
) -> bool {
    use ast::ExpressionKind;
    let ctx = match &expr.kind {
        ExpressionKind::MemberExpression(_) => ParenContext::ChainBase,
        ExpressionKind::CallExpression(_) => ParenContext::Callee,
        ExpressionKind::TaggedTemplateExpression(_) => ParenContext::TaggedTemplateTag,
        ExpressionKind::TSNonNullExpression(_) => ParenContext::NonNull,
        ExpressionKind::AssignmentExpression(assign) => ParenContext::AssignmentTarget {
            operator: assign.operator,
        },
        ExpressionKind::BinaryExpression(binary) => ParenContext::BinaryLeft {
            parent_op: binary.operator,
        },
        ExpressionKind::ConditionalExpression(_) => return ternary_test_needs_parens(child),
        _ => return false,
    };
    needs_parens(child, ctx, in_for_init)
}

/// The regex literal `expr` PRINTS FIRST, at a position that adds no pair of its own — the
/// start of the literal whose opening `/` is the expression's first printed byte, or `None`
/// when a pair the printer keeps (or any other token) comes first.
///
/// The walk descends the left spine as it will be PRINTED ([`printed_left_spine_step`])
/// and stops at the first pair that stands. So `(/a/).test(s)` and `(/a/) ? b : c` reach
/// the literal — the author's pair is not printed — while `(/a/ + b).c` stops at the
/// member object's pair.
///
/// An embedder asks it where its own syntax gives a leading `/` another meaning: a Svelte
/// `{…}` tag in text position reads `{/` as a block close, so `{/a/.test(s)}` does not parse.
pub(crate) fn leading_regex_start(expr: &ast::Expression<'_>) -> Option<u32> {
    use ast::ExpressionKind;
    let mut node = expr;
    loop {
        match &node.kind {
            ExpressionKind::RegexLiteral(_) => return Some(node.span().start),
            // A sequence at a value position prints its own envelope (`build_sequence_doc`'s
            // default layout), so its `(` comes first.
            ExpressionKind::SequenceExpression(_) => return None,
            _ => {}
        }
        let (child, parenthesized) = printed_left_spine_step(node, false)?;
        if parenthesized {
            return None;
        }
        node = child;
    }
}

/// One step down `node`'s left spine as it will be PRINTED: the child whose printed form
/// opens `node`'s own, and whether that child prints inside a paren pair there — the
/// builder's own pair question for it ([`left_side_child_is_parenthesized`]; for a cast, an
/// instantiation and a postfix update, whose left side [`left_side_child`] leaves out, the
/// context their builders pass). `None` where `node` prints a token of its own first, or
/// has no children.
///
/// An instantiation is asked as if its operand's pair were not the author's: a pair it
/// keeps anyway only makes an asker's own wrap redundant, never wrong.
///
/// The walk every "what does this expression print FIRST" question makes —
/// [`leading_regex_start`], and the relational-chain rule's search for a kept shell
/// (`needs_parens`'s `relational_region_opens_on_a_kept_shell`).
pub(in crate::printer) fn printed_left_spine_step<'e>(
    node: &'e ast::Expression<'e>,
    in_for_init: bool,
) -> Option<(&'e ast::Expression<'e>, bool)> {
    use ast::ExpressionKind;
    Some(match &node.kind {
        ExpressionKind::TSAsExpression(cast) => (
            cast.expression,
            needs_parens(cast.expression, ParenContext::TypeAssertion, in_for_init),
        ),
        ExpressionKind::TSSatisfiesExpression(cast) => (
            cast.expression,
            needs_parens(cast.expression, ParenContext::TypeAssertion, in_for_init),
        ),
        ExpressionKind::TSInstantiationExpression(inst) => (
            inst.expression,
            needs_parens(
                inst.expression,
                ParenContext::InstantiationExpression { source_pair: false },
                in_for_init,
            ),
        ),
        ExpressionKind::UpdateExpression(update) if !update.prefix => (
            update.argument,
            needs_parens(
                update.argument,
                ParenContext::UpdateArgument { postfix: true },
                in_for_init,
            ),
        ),
        _ => {
            let child = left_side_child(node)?;
            (
                child,
                left_side_child_is_parenthesized(node, child, in_for_init),
            )
        }
    })
}

/// Where a `SequenceExpression`'s OPERANDS stop — its last operand's end, which its span
/// overshoots by the grouping shell the parser erased from that operand.
///
/// The trailing-side twin of the FIRST OPERAND's start, which the same emitters already
/// take for the leading edge: both edges lie inside the sequence's own span, so no
/// enclosing gap can see them and whoever prints the operands owes them.
///
/// ⚠️ **Not [`crate::ast::Expression::printed_end`], and the two are not
/// interchangeable.** That one answers the same shape of question — where does this node's
/// doc stop printing — over a DISJOINT node set (an `AssignmentPattern`, whose span
/// swallows the shell erased from its VALUE) and for a different consumer: it is the anchor
/// every list element's trailing-comment seam takes, so widening it with this case would
/// move that anchor at every one of them. The rule for choosing: ask `printed_end` where the
/// question is "how far did this ELEMENT print?" and this where it is "where do the OPERANDS
/// of a sequence end?" — the caller that then decides whether that region is the sequence's
/// own to print, or the enclosing shell's ([`Printer::shell_trailing_gap_start`]).
///
/// Not widening `printed_end` has its own cost, paid at the list families: an array element,
/// an object value or a call argument whose value is a sequence has no emitter for the shell
/// erased from its LAST operand, so the comment written there floats out of the pair
/// (`[(x, (y /* t */))]` → `[(x, y) /* t */]`).
fn shell_content_end(expr: &ast::Expression<'_>) -> u32 {
    match &expr.kind {
        ast::ExpressionKind::SequenceExpression(seq) => seq
            .expressions
            .last()
            .map_or_else(|| expr.span().end, |last| last.span().end),
        _ => expr.span().end,
    }
}

pub(crate) fn paren_pair_keeps_leading_run(expr: &ast::Expression<'_>) -> bool {
    matches!(
        expr.kind,
        ast::ExpressionKind::ArrowFunctionExpression(_)
            | ast::ExpressionKind::FunctionExpression(_)
    )
}

/// The index of the next byte in `source` that is neither whitespace nor a comment, at
/// or after `start` and before `end`; `None` when the range holds nothing else.
///
/// The "what actually comes next in the source?" step every shell question asks. A
/// comment occupies bytes even where nothing emits it, so a walk that stepped over
/// whitespace alone would stop on the `/` and answer about the wrong token.
///
/// A string or template literal is a TOKEN, not trivia: the walk stops on its opening
/// quote. Stepping over it answers about whatever follows the literal instead — a tag's
/// own template read as nothing, so the `)` of an enclosing call's argument list after
/// `` f<T><U>(x)`t` `` passed for a pair the author wrote around the tag
/// ([`paren_shell_close_after`]) — and a run of literals is walked again for every
/// operand that ends ahead of it.
///
/// A free function over the source because the chain LINEARIZER asks it too, before any
/// `Printer` method is reached — [`paren_shell_close_after`].
pub(crate) fn next_significant_byte(source: &str, start: u32, end: u32) -> Option<usize> {
    let bytes = source.as_bytes();
    let end = end as usize;
    let mut i = start as usize;
    while i < end {
        if let Some(next) = skip_trivia(bytes, i, end, TriviaProfile::COMMENTS) {
            i = next;
        } else if let Some(ws) = js_whitespace_at(source, i) {
            i += ws;
        } else {
            return Some(i);
        }
    }
    None
}

/// The byte length of the JavaScript whitespace code point at `i` — the lexer's class
/// ([`tsv_lang::is_js_whitespace`]: a no-break space, a byte-order mark, a line or paragraph
/// separator step over like a space) — or `None` where `i` holds anything else. `i` sits on
/// a char boundary.
pub(crate) fn js_whitespace_at(source: &str, i: usize) -> Option<usize> {
    let byte = *source.as_bytes().get(i)?;
    if byte < 0x80 {
        return tsv_lang::is_js_whitespace(char::from(byte)).then_some(1);
    }
    let c = source.get(i..)?.chars().next()?;
    tsv_lang::is_js_whitespace(c).then(|| c.len_utf8())
}

/// The index just past the `)` that closes a REQUIRED pair around an operand ending at
/// `operand_end`, when the author wrote that pair — `None` when the next thing in the
/// source is something else (a `(` of an argument list, a `` ` ``, a `.`), which means
/// the pair this position prints is tsv's own and the source has no trailing gap inside
/// it.
///
/// The distinction is load-bearing: `(fn /* t */)()` writes the pair around the callee
/// and the comment is INSIDE it, while `(/* t */ fn())` writes it around the whole call
/// and the comment belongs to the call, not to a pair the callee prints.
pub(crate) fn paren_shell_close_after(source: &str, operand_end: u32) -> Option<u32> {
    let bytes = source.as_bytes();
    let pos = next_significant_byte(source, operand_end, bytes.len() as u32)?;
    (bytes[pos] == b')').then_some(pos as u32 + 1)
}

/// Whether the left-spine shell region opening at `start` holds no comment, read off the
/// source bytes rather than the spine: the region runs to the leftmost leaf and holds
/// nothing but stripped grouping `(`s, whitespace and the comments among them, so past the
/// whitespace and `(`s at `start` the first other byte is a comment's `/` or the leaf's own.
/// `false` at a `/` (a comment, or a regex leaf) and at a non-ASCII byte (whitespace this
/// step does not read), so `true` is exact and `false` only sends the asker to its walk.
///
/// The zero-comment gate ahead of every left-spine walk that asks about a shell's comments
/// ([`Printer::left_spine_shell_has_own_line_comment`], [`Printer::left_spine_run_claim`]),
/// and ahead of the leading-edge reads of a built doc at a restricted production and at
/// `export default` (`DocArena::leading_comment_break`): almost every expression opens on
/// its leaf, so the walk is skipped after one byte. A SOURCE reading on purpose — a comment
/// the leaf owns is invisible to the gaps' emit axis and still prints ahead of it.
pub(crate) fn left_spine_shell_is_comment_free(source: &str, start: u32) -> bool {
    let bytes = source.as_bytes();
    let mut i = start as usize;
    while let Some(&byte) = bytes.get(i) {
        match byte {
            b'(' | b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C => i += 1,
            _ => return byte != b'/' && byte.is_ascii(),
        }
    }
    true
}

/// Whether `expr`'s left spine has no stripped shell at all: its first byte is not a `(`,
/// so every node down the spine starts where `expr` does and the leaf is the first thing
/// printed. Exact — a span opens on a token — so the structural left-spine walks skip
/// themselves on it ([`Printer::left_spine_printed_start`],
/// [`Printer::build_value_with_left_spine_owned_comment`]).
pub(super) fn left_spine_has_no_shell(source: &str, expr: &ast::Expression<'_>) -> bool {
    source.as_bytes().get(expr.span().start as usize) != Some(&b'(')
}

/// A left-spine shell region one expression CLAIMS for every node below it — the claim
/// [`Printer::left_spine_run_claim`] makes and [`Printer::with_left_spine_claim`] arms.
///
/// `claimer` is the span of the node whose hoist site prints the whole region's run;
/// `region` runs from that node's start to the start of the leaf its hoisted left spine
/// reaches, and holds nothing but stripped grouping `(`s and the comments among them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LeftSpineClaim {
    pub(crate) claimer: Span,
    pub(crate) region: Span,
}

/// The steps down an expression's left spine whose shell runs the printer HOISTS
/// ([`Printer::hoisted_left_spine`]): each a `(node, child)` pair of
/// [`Printer::hoisted_left_side_child`], ending where that does — or at a step whose shell
/// the chain the walk is inside prints MID-CHAIN ([`LeftSpineStep::mid_chain`]), since no
/// run is hoisted out of such a shell: its comment prints after the chain's first link
/// (`(/*c*/ (a).b).m()` prints `a /*c*/.b.m()`).
pub(crate) struct HoistedLeftSpine<'p, 'a, 'e>(Option<LeftSpineSteps<'p, 'a, 'e>>);

impl<'e> Iterator for HoistedLeftSpine<'_, '_, 'e> {
    type Item = (&'e ast::Expression<'e>, &'e ast::Expression<'e>);

    fn next(&mut self) -> Option<Self::Item> {
        let step = self.0.as_mut()?.next();
        match step {
            Some(step) if !step.mid_chain => Some((step.node, step.child)),
            _ => {
                self.0 = None;
                None
            }
        }
    }
}

/// One step of [`LeftSpineSteps`]: `node`, its [`Printer::hoisted_left_side_child`], and
/// whether the chain the step sits in prints the shell between them MID-CHAIN
/// ([`chain_mid_chain_paren_gaps`], the linearizer's own answer) rather than hoisting
/// its run ahead of the chain's head.
#[derive(Clone, Copy)]
pub(crate) struct LeftSpineStep<'e> {
    pub(crate) node: &'e ast::Expression<'e>,
    pub(crate) child: &'e ast::Expression<'e>,
    pub(crate) mid_chain: bool,
}

/// Every step down an expression's left spine through [`Printer::hoisted_left_side_child`],
/// each flagged with whether its shell prints mid-chain ([`LeftSpineStep`]) — the walk
/// [`HoistedLeftSpine`] ends at the first such step, and the readers that ask what the
/// chain's HEAD prints step over it ([`Printer::left_spine_steps`]).
///
/// A chain is linearized at most once per run of member / call steps, rooted at the first
/// of the run (a non-chain step, a non-null link included, ends the run), and only when a
/// step inside it has a comment in its shell to ask about.
pub(crate) struct LeftSpineSteps<'p, 'a, 'e> {
    printer: &'p Printer<'a>,
    node: Option<&'e ast::Expression<'e>>,
    chain_root: Option<&'e ast::Expression<'e>>,
    mid_chain_gaps: Option<SmallVec<[(u32, u32); 2]>>,
}

impl<'e> Iterator for LeftSpineSteps<'_, '_, 'e> {
    type Item = LeftSpineStep<'e>;

    fn next(&mut self) -> Option<Self::Item> {
        let node = self.node.take()?;
        let child = self.printer.hoisted_left_side_child(node)?;
        let mut mid_chain = false;
        if matches!(
            node.kind,
            ast::ExpressionKind::MemberExpression(_) | ast::ExpressionKind::CallExpression(_)
        ) {
            let root = *self.chain_root.get_or_insert(node);
            let (shell_start, child_start) = (node.span().start, child.span().start);
            mid_chain = shell_start < child_start
                && self
                    .printer
                    .comments_in_source_between(shell_start, child_start)
                    .next()
                    .is_some()
                && self
                    .mid_chain_gaps
                    .get_or_insert_with(|| {
                        chain_mid_chain_paren_gaps(root, self.printer.linearize_input())
                    })
                    .contains(&(shell_start, child_start));
        } else if !(self.chain_root.is_some()
            && matches!(node.kind, ast::ExpressionKind::TSNonNullExpression(_)))
        {
            // A `!` under a member or call is a link of the same chain (the linearizer
            // takes it as a `ChainNode::NonNull`), so the links below it are still read
            // against that chain's root: re-rooting at the next member linearized a
            // sub-chain without the calls above the `!`, whose scope decides what the
            // chain prints mid-chain (`(((// c⏎a[x])?.r!?.u() < p))[x]`).
            self.chain_root = None;
            self.mid_chain_gaps = None;
        }
        self.node = Some(child);
        Some(LeftSpineStep {
            node,
            child,
            mid_chain,
        })
    }
}

/// What an ASI-sensitive operand's grouping-paren shell comes to
/// ([`Printer::build_asi_operand_shell_doc`]).
pub(crate) enum AsiOperandShell {
    /// The shell is kept: the operand rendered inside it, both of its gaps emitted. It
    /// supplies whatever parens the operand needs, so the caller adds none.
    Shell(DocId),
    /// No shell: the caller takes its ordinary inline path. The run is the shell's
    /// leading gap when it holds a comment the bare form can still place — the caller
    /// prints it ahead of the operand, inside any pair it adds, and owes it: no other
    /// emitter covers that gap.
    Bare(Option<DocId>),
}

impl<'a> Printer<'a> {
    /// Split the comments between an opening `(` and the value that follows into the run
    /// the `(` LINE keeps and the run that LEADS the value, and report whether the caller
    /// must open its parens ([`Printer::push_leading_comment_run`]'s own report — tsv
    /// has no `propagateBreaks`, so a hardline in here is invisible to the group).
    ///
    /// ⚠️ **The `(`-line share is the call family's, and `import(…)` is a call shape.**
    /// A `//` the author parked after the `(` stays there in every other spelling —
    /// `fn( // c`, `new Foo( // c`, `obj.fn( // c`, `require( // c`, a cataloged
    /// divergence from prettier, which relocates it to the argument's leading line — and
    /// both `import(…)` spellings take the same answer (a dissent there would be an
    /// unconsidered difference, not a decision). Routing the share through
    /// [`Printer::delimiter_line_comment_prefix`] is what makes it one rule: the same
    /// pull, the same "only when the shell breaks anyway" gate, and the same
    /// pulled-comment exclusion. Pinned by
    /// `expressions/calls/import_open_paren_comment_prettier_divergence`, which carries
    /// both spellings because they share this seam.
    ///
    /// The gap is a call-argument leading run — `import(…)`'s first argument, for both
    /// the dynamic-import EXPRESSION and the TS import TYPE — so it takes the argument
    /// list's mode and the shared emitter decides its separators per comment.
    ///
    /// ⚠️ **The three-way rule cannot be approximated by a whole-range scan**, which is
    /// what this site did before: it asked "is there a newline anywhere between the `(`
    /// and this comment", so the second comment of a run the author GLUED
    /// (`import(⏎/* a */ /* b */⏎'./a')`) read as own-line, split the pair, and forced
    /// the parens open — where prettier keeps the pair and, for a run with no line
    /// comment, collapses the whole call. Own-line-ness is per comment and anchored on
    /// its own neighbours ([`Printer::is_own_line_comment`]), and the author blank the
    /// old loop's bare `hardline` deleted is likewise the emitter's to preserve.
    /// The expression's left-side child whose stripped shell's run the printer HOISTS
    /// ahead of the expression's whole doc — prettier's `getLeftSide` ([`left_side_child`])
    /// minus the nodes whose pair RETAINS its leading run, where nothing is hoisted:
    ///
    /// - a member, call or non-null whose base pair keeps the run
    ///   ([`chain_paren_leading_gap`] — the sealed optional chain, the IIFE callee, the
    ///   non-null operand that needs its parens or carries a trailing `//`);
    /// - a tagged template whose tag pair keeps it — a function tag or a sealed optional
    ///   chain ([`tag_paren_leading_start`]);
    /// - an assignment whose target needs its parens (a type-assertion target — the
    ///   cataloged "Assignment-target shell, leading comment").
    ///
    /// And plus the steps the PRINTED form takes past [`left_side_child`]'s shape: a chain
    /// link steps over a non-null the chain flattens
    /// ([`Self::chain_flattened_non_null_operand`]), a cast or a postfix update steps to
    /// its operand where that prints first and bare ([`Self::bare_cast_operand`]), and an
    /// instantiation steps to its operand where no pair stands around it
    /// ([`Self::instantiation_operand_prints_pair`]) — prettier's `getLeftSide` reaches it
    /// through `node.expression` too. The builder prints the stripped shell's run ahead of
    /// the operand, so the readers must walk on to see it: `x = (// c⏎a)<T>` hangs under
    /// the operator as `x = (// c⏎a)()` does.
    ///
    /// Askers that walk the whole spine take [`Self::hoisted_left_spine`], which also
    /// stops at a shell the chain prints mid-chain.
    ///
    /// Two askers, one definition: a restricted production must hold a hoisted run inside a
    /// hanging pair ([`Printer::build_restricted_production_paren_doc`]) — and must NOT wrap
    /// a second pair around one that survives — and an assignment must lay its value out
    /// under the operator so the hoisted run's hardline lands at the value's indent
    /// ([`Printer::build_assignment_layout`] and the declarator's twin). A walk that
    /// descended a retained pair told the declarator to hang a value whose run never left
    /// its shell (`const a = ( // c⏎x + y⏎)!` hung under `=`, then hugged it again on the
    /// reparse).
    pub(crate) fn hoisted_left_side_child<'e>(
        &self,
        expr: &'e ast::Expression<'e>,
    ) -> Option<&'e ast::Expression<'e>> {
        use ast::ExpressionKind;
        if let Some(operand) = self.bare_cast_operand(expr) {
            return Some(operand);
        }
        // An instantiation strips its operand's redundant shell and prints the run ahead of
        // the operand ([`Printer::build_shell_operand_doc`]), unless a pair stands there.
        if let ExpressionKind::TSInstantiationExpression(inst) = &expr.kind {
            return (!self.instantiation_operand_prints_pair(inst, expr.span))
                .then_some(inst.expression);
        }
        let child = left_side_child(expr)?;
        // A chain link's step lands past a non-null the chain flattens.
        let link_step = || {
            self.chain_flattened_non_null_operand(child)
                .unwrap_or(child)
        };
        match &expr.kind {
            ExpressionKind::MemberExpression(_) | ExpressionKind::CallExpression(_) => {
                chain_paren_leading_gap(expr, self.comments)
                    .is_none()
                    .then(link_step)
            }
            // The chain's base-pair answer covers the sealed optional chain and the
            // shell a trailing `//` retains; the non-null's own builder ALSO keeps the
            // pair — as the family's expanded shell, run inside — whenever the operand
            // needs its parens (`( // c⏎x + y⏎)!`), and that pair the linearizer never
            // sees.
            ExpressionKind::TSNonNullExpression(non_null) => {
                (chain_paren_leading_gap(expr, self.comments).is_none()
                    && !self.needs_parens(non_null.expression, ParenContext::NonNull))
                .then(link_step)
            }
            // The tag's required pair keeps its run at the call's two shapes — a function
            // tag and a sealed optional chain (`` ( // c⏎a?.b())`x` ``).
            ExpressionKind::TaggedTemplateExpression(tagged) => {
                tag_paren_leading_start(tagged, expr.span)
                    .is_none()
                    .then_some(child)
            }
            ExpressionKind::AssignmentExpression(assign) => (!self.needs_parens(
                assign.left,
                ParenContext::AssignmentTarget {
                    operator: assign.operator,
                },
            ))
            .then_some(child),
            _ => Some(child),
        }
    }

    /// The operand of a non-null `child` that a chain link above it FLATTENS: one whose
    /// operand needs its parens, so the linearizer prints that operand as the chain's
    /// parenthesized base with the `!` after it, and the run in the non-null's shell
    /// leads the chain's head, outside the pair (`((// c⏎(a) * 2)!).b` prints
    /// `// c⏎(a * 2)!.b`) — where the standalone non-null builder keeps it inside. Asked
    /// by [`Self::hoisted_left_side_child`] at a member, a call and a non-null parent
    /// (the three chain links), whose step then lands on the operand, its gap the chain
    /// head's whole window. `None` for any other `child`, and for a non-null whose own
    /// pair keeps the run ([`chain_paren_leading_gap`]).
    fn chain_flattened_non_null_operand<'e>(
        &self,
        child: &'e ast::Expression<'e>,
    ) -> Option<&'e ast::Expression<'e>> {
        let ast::ExpressionKind::TSNonNullExpression(non_null) = &child.kind else {
            return None;
        };
        (chain_paren_leading_gap(child, self.comments).is_none()
            && self.needs_parens(non_null.expression, ParenContext::NonNull))
        .then_some(non_null.expression)
    }

    /// The operand of a cast (`as` / `satisfies`) or a postfix update when it prints
    /// FIRST and BARE in that node's doc: no pair of its own there
    /// ([`printed_left_spine_step`]), and no comment in the operand's stripped shell or
    /// between it and the keyword, so the node keeps no shell
    /// ([`Printer::build_asi_operand_shell_doc`] is never reached with anything to hold).
    /// The run the operand's own spine hoists then leads the node's whole doc, which is
    /// why [`Self::hoisted_left_side_child`] descends it (`((// c⏎(a)).b) as T` prints
    /// `// c⏎a.b as T`). `None` for any other node, and wherever the shell or a pair
    /// stands — the operand's run is then held inside it.
    fn bare_cast_operand<'e>(
        &self,
        expr: &'e ast::Expression<'e>,
    ) -> Option<&'e ast::Expression<'e>> {
        use ast::ExpressionKind;
        let (operand, boundary) = match &expr.kind {
            ExpressionKind::TSAsExpression(cast) => {
                (cast.expression, cast.type_annotation.span().start)
            }
            ExpressionKind::TSSatisfiesExpression(cast) => {
                (cast.expression, cast.type_annotation.span().start)
            }
            ExpressionKind::UpdateExpression(update) if !update.prefix => {
                (update.argument, expr.span().end)
            }
            _ => return None,
        };
        let (_, parenthesized) = printed_left_spine_step(expr, self.in_for_init.get())?;
        let shell_free = |start: u32, end: u32| {
            start >= end || self.comments_in_source_between(start, end).next().is_none()
        };
        (!parenthesized
            && shell_free(expr.span().start, operand.span().start)
            && shell_free(operand.span().end, boundary))
        .then_some(operand)
    }

    /// Whether the grouping shell the parser erased between `expr` and its left-spine
    /// `child` is one the printer RE-EMITS — a pair `needs_parens` requires there.
    ///
    /// The two comment classes answer the enclosing "does this run reach the keyword's
    /// line?" question differently, and this is the whole of the difference. A `//`, or any
    /// comment on its own line, is emitted by the SHELL GAP and hoisted out in front of the
    /// pair at a cast, a ternary test and their siblings — prettier does the same and tsv
    /// matches — so a walk reading that class descends through an emitted pair. A comment
    /// the leftmost leaf OWNS does not travel: ownership prints it from that leaf's own doc,
    /// which is *inside* the pair, so a pair the printer emits holds it and it can never
    /// reach the keyword at all. A walk reading THAT class stops here
    /// ([`Self::stripped_left_side_child`]).
    ///
    /// Reading it the other way is what doubles a pair: the restricted production wraps a
    /// hanging pair around a run that never needed holding
    /// (`return (⏎ (/* a⏎b */ a as any).b⏎);` for `return (/* a⏎b */ a as any).b;`), pinned by
    /// `statements/return_throw/operand_paren_required_inner_pair_multiline_block_prettier_divergence`.
    pub(crate) fn left_shell_paren_is_emitted(
        &self,
        expr: &ast::Expression<'_>,
        child: &ast::Expression<'_>,
    ) -> bool {
        // No shell between them at all, so there is no pair to re-emit. The predicate below
        // asks only whether the CHILD prints parenthesized at its position, which is a
        // question about the printed form and not about the erased shell — the two differ
        // exactly where the printer SYNTHESIZES a pair the author never wrote, and this
        // caller wants only the re-emitted ones.
        expr.span().start != child.span().start
            && left_side_child_is_parenthesized(expr, child, self.in_for_init.get())
    }

    /// The walk down `expr`'s left spine through every shell whose run the printer hoists
    /// ([`HoistedLeftSpine`]) — the one walk each "what does the hoist print ahead of this
    /// expression" asker takes, so none of them reads a shell the chain prints mid-chain.
    pub(crate) fn hoisted_left_spine<'p, 'e>(
        &'p self,
        expr: &'e ast::Expression<'e>,
    ) -> HoistedLeftSpine<'p, 'a, 'e> {
        HoistedLeftSpine(Some(self.left_spine_steps(expr)))
    }

    /// Every step down `expr`'s left spine, a shell the chain prints mid-chain included and
    /// flagged ([`LeftSpineSteps`]) — the walk for "what does the doc open with", which a
    /// mid-chain shell's run does not answer but a shell below it still can: the chain's
    /// head is printed first, so the head's own shell run leads the doc even under a
    /// mid-chain shell (`(// d⏎ (// d⏎ a).b).m()` opens with the inner `// d`), and so
    /// does a comment the head's leaf OWNS, wherever on the spine it sits.
    pub(crate) fn left_spine_steps<'p, 'e>(
        &'p self,
        expr: &'e ast::Expression<'e>,
    ) -> LeftSpineSteps<'p, 'a, 'e> {
        LeftSpineSteps {
            printer: self,
            node: Some(expr),
            chain_root: None,
            mid_chain_gaps: None,
        }
    }

    /// Where the shells below a left-spine step start printing INSIDE a group that `node`
    /// wraps its left side in, or `None` when the step opens no such group.
    ///
    /// A binary chain prepends its own leading region outside its group, and that region
    /// runs to its LEFTMOST operand, past every link it flattens; the operand's doc, and
    /// every shell run hoisted inside it, prints inside the group. A glued block's soft
    /// `line` there collapses while the group fits (`return (/* d */⏎ a).b + 1` prints
    /// `return /* d */ a.b + 1`), so it does not give the run a line of its own
    /// ([`Self::comment_takes_line_in_group`]) — except a run an enclosing node CLAIMS
    /// ([`Self::left_spine_run_claim`]): an outer binary's claim prints the region ahead
    /// of its own chain, outside the inner group, so the run's line breaks with whatever
    /// the outer chain prints in (`return ((/* d */⏎ a) + 1) * 2` keeps `/* d */` on the
    /// keyword's line while it fits, and on a line of its own inside the return's pair
    /// once that breaks).
    pub(crate) fn left_spine_group_start(&self, node: &ast::Expression<'_>) -> Option<u32> {
        match &node.kind {
            ast::ExpressionKind::BinaryExpression(binary) => {
                let mut link = binary;
                while let Some(left) = self.flattenable_left(link) {
                    link = left;
                }
                Some(link.left.span().start)
            }
            _ => None,
        }
    }

    /// Whether a comment followed by a newline in a shell gap INSIDE a group
    /// ([`Self::left_spine_group_start`]) still breaks its line there: a `//`, a block the
    /// source opens a line for (the leading emitter's hardline), or a multi-line block,
    /// whose interior forces the group open. A glued single-line block takes the soft
    /// `line`, which the fitting group keeps flat.
    pub(crate) fn comment_takes_line_in_group(&self, comment: &ast::Comment) -> bool {
        !comment.is_block
            || comment.multiline
            || has_newline_before_position(self.source, comment.span.start)
    }

    /// [`Self::hoisted_left_side_child`] stopped at the first shell the printer re-emits —
    /// the walk for a comment the leftmost leaf OWNS, which a pair holds rather than hoists
    /// ([`Self::left_shell_paren_is_emitted`] states the difference).
    pub(crate) fn stripped_left_side_child<'e>(
        &self,
        expr: &'e ast::Expression<'e>,
    ) -> Option<&'e ast::Expression<'e>> {
        let child = self.hoisted_left_side_child(expr)?;
        (!self.left_shell_paren_is_emitted(expr, child)).then_some(child)
    }

    /// The leftmost node an expression's doc prints FIRST, for the OWNED-comment reading:
    /// `expr` itself, or the leaf past every grouping shell the parser erased from its left
    /// spine that the printer does not re-emit.
    ///
    /// The sibling of [`Self::left_spine_printed_start`], and deliberately not the same walk
    /// — the two answer the same shape of question for the two comment classes, so they take
    /// the two step functions. That one walks [`Self::hoisted_left_side_child`], because a
    /// gap-emitted run is hoisted out in front of a pair the printer re-emits; this one walks
    /// [`Self::stripped_left_side_child`], because an owned comment is printed from inside
    /// that pair and never travels ([`Self::left_shell_paren_is_emitted`]).
    pub(crate) fn stripped_left_spine_leaf<'e>(
        &self,
        expr: &'e ast::Expression<'e>,
    ) -> &'e ast::Expression<'e> {
        let mut node = expr;
        while let Some(child) = self.stripped_left_side_child(node) {
            node = child;
        }
        node
    }

    /// Whether a stripped shell on the expression's left spine holds a comment the hoist
    /// gives a line of its own — a `//`, or a block followed by a newline — so the
    /// expression's doc opens with that run and a hardline
    /// (`(⏎// c⏎a as any) ? b : c` prints as `// c⏎(a as any) ? b : c`).
    ///
    /// Walks [`Self::left_spine_steps`] to the leaf, reading each node→child gap in source.
    /// A shell the chain prints mid-chain counts only the comment the head's leaf OWNS —
    /// the leaf prints it ahead of the head, so it leads the doc
    /// (`x = (⏎/** @type {T} */⏎(f).b).c(zz)` opens with the cast's comment on its own
    /// line) — while the rest of its run does not; a shell below it still does. A comment in such a gap always LEADS the child
    /// (the gap holds nothing that could own a trailing comment), so the question is
    /// whether a newline follows it — prettier's `hasLeadingOwnLineComment`, asked of every
    /// node on the way down exactly as `returnArgumentHasLeadingComment` asks it — and,
    /// inside a group a step above opened ([`Self::left_spine_group_start`]), whether the
    /// comment breaks its line there at all. The member object→property gap is not this
    /// walk's: a comment there is the chain's own business
    /// (`Printer::has_line_comments_in_member_chain`).
    pub(crate) fn left_spine_shell_has_own_line_comment(&self, expr: &ast::Expression<'_>) -> bool {
        if left_spine_shell_is_comment_free(self.source, expr.span().start) {
            return false;
        }
        let mut group_start = None;
        self.left_spine_steps(expr).any(
            |LeftSpineStep {
                 node,
                 child,
                 mid_chain,
             }| {
                let shell_start = node.span().start;
                let child_start = child.span().start;
                let in_group = group_start.is_some_and(|start| shell_start >= start);
                if group_start.is_none() && !mid_chain {
                    group_start = self.left_spine_group_start(node);
                }
                shell_start < child_start
                    && self
                        .comments_in_source_between(shell_start, child_start)
                        .any(|c| {
                            (!mid_chain || c.owned_by_node)
                                && has_newline_after_position(self.source, c.span.end)
                                && (!in_group || self.comment_takes_line_in_group(c))
                        })
            },
        )
    }

    /// Whether an INDENTABLE block in a stripped shell on `value`'s left spine leads its
    /// doc — prettier's `chooseLayout` fourth disjunct one shell deeper than the operator
    /// gap the seam scans ([`Self::indentable_block_leads_value`]). The value's printer
    /// strips the shell and prints the comment ahead of its head, so the reparse finds it
    /// in the operator gap and hangs the value; the first pass must hang it too
    /// (`x = (/*⏎ */ a.b).m(1)`).
    ///
    /// Walks [`Self::left_spine_steps`]: every hoisted shell's comments count, and in a
    /// shell the chain prints mid-chain only the comment the head's leaf OWNS, which is
    /// printed from the leaf, ahead of the head (`x = (// c⏎/*⏎ */ a.b).m(1).n(2)` prints
    /// the block first and `// c` after `a`).
    ///
    /// Asked at every operator→value seam, so the common answer is one byte: a value that
    /// does not open on a `(` has no shell ([`left_spine_has_no_shell`]).
    #[inline]
    pub(crate) fn left_spine_indentable_leads_value(&self, value: &ast::Expression<'_>) -> bool {
        !left_spine_has_no_shell(self.source, value)
            && self.left_spine_indentable_leads_value_walk(value)
    }

    /// [`Self::left_spine_indentable_leads_value`] past its one-byte gate.
    #[inline(never)]
    fn left_spine_indentable_leads_value_walk(&self, value: &ast::Expression<'_>) -> bool {
        if left_spine_shell_is_comment_free(self.source, value.span().start) {
            return false;
        }
        self.left_spine_steps(value).any(|step| {
            let shell_start = step.node.span().start;
            let child_start = step.child.span().start;
            shell_start < child_start
                && self
                    .comments_in_source_between(shell_start, child_start)
                    .any(|c| {
                        (!step.mid_chain || c.owned_by_node) && self.block_comment_is_indentable(c)
                    })
        })
    }

    /// Where this expression's doc STARTS PRINTING: past every stripped grouping paren on
    /// its left spine, which is the leftmost leaf [`Self::hoisted_left_spine`] reaches.
    ///
    /// The start twin of [`ast::Expression::printed_end`], and the same difference read
    /// from the other end — a region holding nothing but the `(`s the printer erases,
    /// whitespace, and any comment inside them. Unlike `printed_end` it is not a pure AST
    /// question: whether a pair is stripped or RETAINED depends on `needs_parens` and on what
    /// the pair holds, so it is the walk that answers it, never a paren scan. A retained pair
    /// prints its own parens and keeps its run inside them, so the walk stops there and the
    /// printed start is the node's own span start.
    ///
    /// This is what an ENCLOSING gap must read as its far end. A comment in a stripped shell
    /// sits *inside* the expression's span, yet the hoist prints it ahead of the node — in
    /// exactly the position a comment in the gap *before* the span would land. A seam that
    /// bounds its scan at `span().start` is therefore blind to it and answers one question two
    /// ways by authoring (`docs/comments.md` §The left-spine shell run: the seam above the node
    /// must know the run is coming). ⚠️ For the **layout** half of that question only — an
    /// emitter must keep bounding its scan at `span().start`, since the node's own doc prints
    /// the hoisted run and claiming it again DOUBLE-PRINTS it.
    pub(crate) fn left_spine_printed_start(&self, expr: &ast::Expression<'_>) -> u32 {
        if left_spine_has_no_shell(self.source, expr) {
            return expr.span().start;
        }
        self.hoisted_left_spine(expr)
            .last()
            .map_or(expr, |(_, leaf)| leaf)
            .span()
            .start
    }

    /// The claim a hoist site at `node` makes over its left spine's shells, when a pair the
    /// printer prints on that spine holds a comment below it — `x = ((/*c*/ (a) ** 2) ** 2)
    /// ** 2`, whose `/*c*/` sits in the shell of the `**` operand that prints inside the
    /// outer chain's pair. `child` is `node`'s hoisted left-side child, and `child_in_pair`
    /// answers whether `node` prints it inside a pair — each site's own builder's
    /// question, asked only past the comment gate; the root conditional, `await` and `new`
    /// also answer yes for a child whose doc opens with a run on a line of its own
    /// ([`Self::left_spine_shell_has_own_line_comment`]), which they claim pair or no pair.
    /// `start` is where the region opens: `node`'s own start, past the keyword at a value
    /// head (`...`, `await`, `new`), and at the operand for the chain a non-null seals (the
    /// non-null's own shell is its builder's to print).
    ///
    /// Without the claim each hoist site prints only its OWN gap, ahead of its own doc —
    /// so a run in a shell below a printed pair lands just inside that pair, where the
    /// reparse reads it as the enclosing node's gap and hoists it one pair further, one
    /// pair per pass. The fixed point is the run leading `node`'s whole doc, which is
    /// where [`Self::left_spine_shell_has_own_line_comment`] and
    /// [`Self::left_spine_printed_start`] already tell the seams above it the run comes
    /// from: so `node` prints the whole region, and every site below declines it.
    ///
    /// `None` — each site prints its own gap, as before — when `node` lies inside a region
    /// an enclosing node already claims, when no printed pair has a comment below it, and
    /// when the region holds a comment that must stay with its own site
    /// ([`Self::left_spine_region_stays_per_site`]). The walk is
    /// [`Self::hoisted_left_spine`] — so it ends before a shell the chain prints
    /// mid-chain, and at every pair a construct keeps for its run — through the kinds
    /// whose hoist site honors the claim: a binary, a member, a call, a tagged template, a
    /// conditional, a sequence head, a cast's or postfix update's bare operand, an
    /// instantiation's stripped operand ([`Self::build_shell_operand_doc`]), and a
    /// non-null — a link of the member / call chain above it, whose head window holds the
    /// operand's shell, or a standalone one, whose leading run declines the claimed region
    /// like every other site's (`((/* c */ (x).a())! + 1).b` prints `/* c */ (x.a()! + 1).b`).
    /// It stops at an assignment target, whose shell keeps its own emitter.
    ///
    /// Asked at every hoist site, so the common answer is one byte: a claim needs a shell
    /// INSIDE `child` (the comment must sit below a printed pair, and the shallowest such
    /// pair is `child`'s own), and a `child` that does not open on a `(` has none
    /// ([`left_spine_has_no_shell`]). Only a `child` that does reaches the walk.
    #[inline]
    pub(crate) fn left_spine_run_claim(
        &self,
        node: Span,
        start: u32,
        child: &ast::Expression<'_>,
        child_in_pair: impl FnOnce() -> bool,
    ) -> Option<LeftSpineClaim> {
        if left_spine_has_no_shell(self.source, child) {
            return None;
        }
        self.left_spine_run_claim_walk(node, start, child, child_in_pair)
    }

    /// [`Self::left_spine_run_claim`] past its one-byte gate.
    #[inline(never)]
    fn left_spine_run_claim_walk(
        &self,
        node: Span,
        start: u32,
        child: &ast::Expression<'_>,
        child_in_pair: impl FnOnce() -> bool,
    ) -> Option<LeftSpineClaim> {
        if left_spine_shell_is_comment_free(self.source, child.span().start)
            || self
                .claimed_left_spine_run
                .get()
                .is_some_and(|claim| claim.region.start <= start && start < claim.region.end)
            || !self.has_comments_to_emit_between(start, child.span().end)
        {
            return None;
        }
        let mut below_pair = child_in_pair().then(|| child.span().start);
        let mut leaf = child;
        for (node, next) in self.hoisted_left_spine(child) {
            // A non-null is a hoist site either way: a link of the member / call chain
            // above it, its operand's shell inside that chain's head window, or a
            // standalone one, whose own leading run declines the claimed region
            // (`Printer::build_ts_non_null_doc`).
            if !matches!(
                node.kind,
                ast::ExpressionKind::MemberExpression(_)
                    | ast::ExpressionKind::CallExpression(_)
                    | ast::ExpressionKind::TSNonNullExpression(_)
                    | ast::ExpressionKind::BinaryExpression(_)
                    | ast::ExpressionKind::TaggedTemplateExpression(_)
                    | ast::ExpressionKind::ConditionalExpression(_)
                    | ast::ExpressionKind::SequenceExpression(_)
                    | ast::ExpressionKind::TSAsExpression(_)
                    | ast::ExpressionKind::TSSatisfiesExpression(_)
                    | ast::ExpressionKind::UpdateExpression(_)
                    | ast::ExpressionKind::TSInstantiationExpression(_)
            ) {
                break;
            }
            if below_pair.is_none()
                && left_side_child_is_parenthesized(node, next, self.in_for_init.get())
            {
                below_pair = Some(next.span().start);
            }
            leaf = next;
        }
        let leaf_start = leaf.span().start;
        let below_pair = below_pair?;
        (below_pair < leaf_start
            && self.has_comments_to_emit_between(below_pair, leaf_start)
            && !self.left_spine_region_stays_per_site(start, leaf_start))
        .then(|| LeftSpineClaim {
            claimer: node,
            region: Span::new(start, leaf_start),
        })
    }

    /// Whether a left-spine region holds a comment whose own site must keep printing it, so
    /// no claim is made over it ([`Self::left_spine_run_claim`]):
    ///
    /// - an honored format-ignore directive — each construct freezes its own child
    ///   (`Printer::left_spine_operand_frozen_span`), so a directive cannot move;
    /// - a bundler annotation (`/* @__PURE__ */`, [`tsv_lang::is_tree_shaking_annotation`],
    ///   matched anywhere in the comment, so `/** @__PURE__ */` too) — it marks the
    ///   call or function it is printed in front of, and the claim would print it in front
    ///   of the whole region's pairs instead, where it marks nothing.
    fn left_spine_region_stays_per_site(&self, start: u32, end: u32) -> bool {
        self.comments_in_source_between(start, end).any(|c| {
            self.is_honored_directive(c)
                || (c.is_block && tsv_lang::is_tree_shaking_annotation(c.content(self.source)))
        })
    }

    /// Run `build` with `claim` armed ([`Printer::claimed_left_spine_run`]); a plain call
    /// when there is none. The claimer's hoist site must sit INSIDE `build`, since it
    /// reads the armed claim to print the region.
    ///
    /// `build` is called from one place, so it inlines into the site whole: every hoist
    /// site wraps its builder in this, and almost none arms a claim. Forced: under a plain
    /// `#[inline]` the release build retired 0.50% more TS format instructions (0.25%
    /// Svelte) for a 656 B smaller binary.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(crate) fn with_left_spine_claim<T>(
        &self,
        claim: Option<LeftSpineClaim>,
        build: impl FnOnce() -> T,
    ) -> T {
        let saved = claim.map(|claim| self.claimed_left_spine_run.replace(Some(claim)));
        let out = build();
        if let Some(saved) = saved {
            self.claimed_left_spine_run.set(saved);
        }
        out
    }

    pub(crate) fn build_paren_leading_value_doc(
        &self,
        open_paren_end: u32,
        value_start: u32,
        value_doc: DocId,
    ) -> ParenLeadingValue {
        // The `(`-LINE share, on the shared delimiter-line rule: pull a comment the author
        // left on the `(` line onto that line only when the shell is breaking anyway, so a
        // call that would have fit still fits (`docs/comments.md` §The delimiter-line
        // question). `pull_pos` is the exclusion every consumer of that prefix owes.
        let (paren_line, pull_pos) = match self.paren_line_share_anchor(open_paren_end, value_start)
        {
            Some(paren) => {
                let (prefix, pull_pos) = self.delimiter_line_comment_prefix(paren, value_start);
                // The field stays a buffer (its two consumers read a slice and gate on
                // `is_empty`); the `Option` collects into it only at this cold site.
                (prefix.into_iter().collect(), pull_pos)
            }
            None => (DocBuf::new(), None),
        };
        let run = self.build_leading_comment_run_with_break(
            open_paren_end,
            value_start,
            LeadingGlue::AdjacentStrippedParen,
            pull_pos,
        );
        let (value, run_breaks) = match run {
            Some((run, force_break)) => (self.d().concat(&[run, value_doc]), force_break),
            None => (value_doc, false),
        };
        ParenLeadingValue {
            // A pull is only ever made on the break path, so it reports the break itself —
            // the pulled run is no longer in `value` for the run's own report to see.
            forces_break: run_breaks || pull_pos.is_some(),
            paren_line,
            value,
        }
    }

    /// The `(` a `(`-line share would be claimed against, or `None` when this gap has no
    /// share to claim.
    ///
    /// ⚠️ **The share is what the author wrote AFTER the `(`, so the anchor is the paren
    /// and not the gap's start.** The gap deliberately spans the `(` — one slot, one
    /// emitter, which is what keeps `import /* c */ ('m')` from being dropped — but a
    /// comment written *before* the paren belongs to the head, and the claim has to stay a
    /// **PREFIX** of the gap's comments (`docs/comments.md` §The element-comma seam):
    /// claiming only the after-`(` tail would render it AHEAD of the head comment it was
    /// written under. So a run that begins before the `(` is not split — it stays whole in
    /// the leading position, which is where both formatters already put it
    /// (`import /* pre */ ( // post`, the null control in
    /// `expressions/calls/import_open_paren_comment_prettier_divergence`).
    fn paren_line_share_anchor(&self, gap_start: u32, value_start: u32) -> Option<u32> {
        let paren = find_char_skipping_comments(
            self.source.as_bytes(),
            gap_start as usize,
            value_start as usize,
            b'(',
        )? as u32;
        self.comments_to_emit_between(gap_start, value_start)
            .next()
            .is_some_and(|first| first.span.start > paren)
            .then_some(paren)
    }

    /// Append the trailing comments in an operand's closing gap to a parts vec.
    ///
    /// The gap holds comments that belong to no node, so some caller has to place them.
    /// It arises both ways round: the parser *strips* grouping parens (`await (x /* c */)`
    /// → the arg is `x`, orphaning `/* c */` before the expression's span end), and the
    /// restricted-production hanging layout *retains* them (the comment prints inside the
    /// parens, bounded by the `)` rather than the span end). Layout per comment:
    /// - Glued to the operand's line, block: inline with leading space (`x /* c */`)
    /// - Own line: deferred via `line_suffix` with a hardline, keeping an author blank
    ///   above it (`x;\n\n/* c */`) — prettier's `printTrailingComment`, its
    ///   `hasNewline(…, { backwards: true })` + `isPreviousLineEmpty` arm
    /// - Anything else: deferred via `line_suffix` on the previous comment's line
    ///   (`x; // c`, `x;\n/* c1 */ /* c2 */`)
    ///
    /// ⚠️ **The question is the SOURCE, asked per comment, and only then the kind.** The
    /// anchor advances over every comment emitted here, so the second half of a run the
    /// author glued (`x⏎/* c1 */ /* c2 */`) is not own-line and keeps that line; a fixed
    /// `argument_end` anchor read it across `c1` and split the pair. Asking the KIND
    /// first is the mirror-image formulation `docs/comments.md` §Trailing and dangling
    /// runs names: it gave an own-line `//` the inline suffix, WELDING it onto the
    /// previous comment's output line (`x; // c1 // c2` — the second delimiter becomes
    /// text inside the first, and the comment stops existing).
    ///
    /// ⚠️ **A comment glued BEHIND a deferred one is deferred too.** Deferral is what
    /// carries this run past the terminator, so an inline block emitted after the run has
    /// started renders *ahead* of it and the authored pair comes out REORDERED. Unlike
    /// [`Printer::push_trailing_comments_in_range`], where only a `//` can open the run
    /// (and nothing can follow one on its line), an own-line **block** opens it here —
    /// this gap floats own-line comments out rather than keeping them inline — so the
    /// glued-behind case is reachable and needs its own arm.
    ///
    /// Keeps a same-line block comment with its operand (before any terminator) — the
    /// expression-level operand callers (await, yield, binary, sequence) where the
    /// comment is inside the stripped operand parens, plus `export =` (which, like
    /// `import =`, keeps a same-line trailing block before the `;`).
    ///
    /// Statement terminators that move the block *after* the `;` — `export default`, and
    /// the return/throw paths that print no pair around the run — use
    /// `split_terminator_gap_comments` instead. The pairs a return/throw argument prints —
    /// the hanging layout's retained parens, and a binary argument's conditional pair when
    /// a run holds it open — use **both**: this method for the region inside the pair,
    /// then that one for anything past the `)`.
    ///
    /// ⚠️ **A run that DEFERS is counted** ([`Printer::deferred_paren_runs`]). The pair this
    /// gap sat in is gone from the output (or, for a sequence, closes before the run), so
    /// nothing here ends the line: the suffix rides to wherever the ENCLOSING line ends. A
    /// statement's line ends past its `;` (`const r = x + y * z; // c`, prettier's fixed
    /// point too), and so does a chain or a `return` hang inside it — every layout there
    /// is the one the comment-free operand takes. A comma list's line would end past the
    /// list's `)` and whatever follows it, outside the construct the run was written in
    /// (`docs/comments.md` §Trailing and dangling runs), so the list reads the count
    /// around each element ([`Self::build_list_element_doc`]) and breaks, flushing the run
    /// at the element's comma: `f(⏎\tx + y * z, // c⏎\t1⏎)`.
    ///
    /// Returns whether the run deferred — the report a caller reads when its own layout
    /// has to hold the run (the `return` / `throw` binary operand, whose conditional pair
    /// is printed open around one).
    pub(crate) fn append_trailing_paren_comments(
        &self,
        parts: &mut DocBuf,
        argument_end: u32,
        span_end: u32,
    ) -> bool {
        // Whether anything has been deferred yet — a `//`, or an own-line comment.
        let mut deferred_run = false;
        // What physically precedes the next comment: an **in-source** cursor, so it
        // advances over every comment in the gap (docs/comments.md §the three axes).
        let mut prev_end = argument_end;
        for comment in self.comments_to_emit_between(argument_end, span_end) {
            // The *comment* line-break table, never the layout one: this decides whether
            // a `//` is followed by a break, so it must stay real under the canonical
            // reprint, where an erased read would weld the run.
            let own_line = self.comment_has_newline_between(prev_end, comment.span.start);
            parts.push(if own_line {
                self.build_trailing_comment_doc_own_line_blank(
                    comment,
                    self.previous_line_is_empty(
                        self.blank_scan_start(prev_end, comment.span.start),
                        comment.span.start,
                    ),
                )
            } else if deferred_run || !comment.is_block {
                self.build_trailing_line_comment_doc(comment)
            } else {
                self.build_trailing_comment_doc(comment)
            });
            deferred_run |= own_line || !comment.is_block;
            prev_end = comment.span.end;
        }
        if deferred_run {
            self.deferred_paren_runs
                .set(self.deferred_paren_runs.get() + 1);
        }
        deferred_run
    }

    /// Build one element of a comma LIST, and end it with a flush-scoped break when its
    /// build deferred a run out of a stripped grouping pair
    /// ([`Self::append_trailing_paren_comments`], counted in
    /// [`Printer::deferred_paren_runs`]).
    ///
    /// The deferred `//` rides a `line_suffix` to wherever its line ends, and a list that
    /// stays flat ends it past the list's `)` / `]` — outside the construct it was written
    /// in (`docs/comments.md` §Trailing and dangling runs). The break placed AFTER the
    /// element arms in the `fits` walk and fails the list's own next line opportunity —
    /// the separator behind the element, or the closer's softline — so the list breaks and
    /// the run flushes at the element's comma, where the reparse finds it as the element's
    /// trailing comment. That is prettier's shape too: its trailing line comment carries a
    /// `breakParent` to the list. Content inside the element stays flat when it fits, since
    /// the break arms only past it.
    ///
    /// `element_start` records the element as one that forces its list
    /// ([`Self::span_holds_forced_list_break`]), for a layout that has to know it before
    /// measuring. The count is restored once read, so an enclosing list does not break for
    /// a run this one already flushes.
    pub(crate) fn build_list_element_doc(
        &self,
        element_start: u32,
        build: impl FnOnce() -> DocId,
    ) -> DocId {
        let before = self.deferred_paren_runs.get();
        let doc = build();
        if self.deferred_paren_runs.get() == before {
            return doc;
        }
        self.deferred_paren_runs.set(before);
        self.forced_list_elements.borrow_mut().push(element_start);
        let d = self.d();
        d.concat(&[doc, d.flush_break()])
    }

    /// Push an **embed end** behind `value` when its doc may defer a run to its own end — a
    /// stripped pair's interior comment, a hugged arrow's body — for a caller about to print
    /// the comments the author wrote AFTER the value inline, ahead of its closer's break
    /// (a computed bracket's key→`]` run, a template interpolation's `${…}` run). Left
    /// pending, the deferred run rides past them to that break and lands behind them on one
    /// line, where two `//` weld into one comment (`a || b // d // c`). At the embed end it
    /// flushes first, in authored order, and the written run follows on the next line
    /// (`tsv_lang::doc::arena::DocArena::embed_end`).
    pub(crate) fn push_deferred_run_end(&self, parts: &mut DocBuf, value: DocId) {
        let d = self.d();
        if d.holds_line_suffix(value) {
            let pending = d.pending_run_at_end(value, self.source);
            parts.push(d.embed_end(pending, false).doc());
        }
    }

    /// Whether `span` holds a list element that breaks its list
    /// ([`Self::build_list_element_doc`]) — the element itself, or one nested at any depth
    /// inside it (`o.aaaa().bbbb(g(x + (y // c⏎)), 1)`, whose `g(…)` argument carries the
    /// forced break of its own inner list). Asked after the doc covering `span` is built.
    ///
    /// The break is a `flush_break`, which `DocArena::will_break` does not see and which
    /// fails a flat measure only past the element: a layout that picks a state by
    /// measuring the WHOLE list flat reads the list as unable to fit anywhere, where the
    /// reparse — the comment then sitting in the element's comma gap, a real break —
    /// reads it as broken. The member chain is that layout: its one-line state is the
    /// reparse's answer (`o.aaaa().bbbb(⏎\tx + y, // c⏎\t1⏎)`), and it asks this to see
    /// the break the reparse sees.
    pub(crate) fn span_holds_forced_list_break(&self, span: Span) -> bool {
        self.forced_list_elements
            .borrow()
            .iter()
            .any(|&start| span.start <= start && start < span.end)
    }

    /// Run `build` and discard any run count it added: the construct it builds ends its
    /// own line, so a run deferred inside it flushes there and no enclosing list owes it a
    /// break ([`Self::build_list_element_doc`]). A statement is that construct.
    pub(crate) fn with_line_ending_construct<T>(&self, build: impl FnOnce() -> T) -> T {
        let before = self.deferred_paren_runs.get();
        let built = build();
        self.deferred_paren_runs.set(before);
        built
    }

    /// Split the trailing comments in a statement terminator's content→`;` gap
    /// the way prettier 3.9 does, returning the docs to emit **after** the `;`.
    ///
    /// A same-line **block** comment trails *after* the `;` (`return x; /* c */`) —
    /// *unless* it is still enclosed by a grouping paren around the operand that this
    /// caller PRINTS (`return (a = b /* c */);`), in which case it stays inline before
    /// the `;` (it is attached to the operand, not the statement). `operand_parens_printed`
    /// is that caller fact, and it must be a fact about the OUTPUT, never about the source:
    /// a shell the caller strips leaves a `)` in the source and none in the output, so a
    /// source-keyed carve-out has no fixed point — the next pass sees no shell, reads the
    /// same comment as statement-trailing, and moves it. Line comments (`line_suffix`) and
    /// own-line block comments also trail after the `;`. The inline (operand-attached)
    /// comments are pushed into `parts`; the rest are returned.
    ///
    /// Caller idiom: `let after = self.split_terminator_gap_comments(parts, arg_end,
    /// span_end, operand_parens_printed, gap); parts.push(";"); parts.extend(after);`.
    /// Used by return/throw, `export default`, and `export =` — the terminator callers
    /// whose argument may be parenthesized (unlike the expression-statement/var/
    /// class-property terminators, whose operand parens are consumed by inner printers —
    /// they use `push_semicolon_with_gap_comments`).
    ///
    /// A **line** comment is never held back: one written inside a grouping paren the
    /// caller prints is that caller's to keep inside the pair, ahead of this split — the
    /// hanging form and the binary operand's conditional pair both open around it and
    /// start this split at their `)` (`return (⏎\ta && b // c⏎);`).
    ///
    /// `clause_tail` is the statement CONTAINER's deferral fact
    /// (`StatementContext::clause_tail`): `Some(dedent)` when the statement is a
    /// non-block clause body, whose tail line stays open to the enclosing construct —
    /// there each own-line member's interior break is wrapped in `dedent` levels
    /// ([`Printer::build_clause_tail_comment_doc`]), so the freed comment renders at
    /// the flushing construct's level in one pass instead of settling on the reparse.
    /// The same-line arms are indent-free (no interior break), so only the own-line
    /// arm reads it.
    pub(in crate::printer) fn split_terminator_gap_comments(
        &self,
        parts: &mut DocBuf,
        argument_end: u32,
        span_end: u32,
        operand_parens_printed: bool,
        gap: TerminatorGap,
    ) -> DocBuf {
        let clause_tail = gap.clause_tail();
        let d = self.d();
        let mut deferred = DocBuf::new();
        // What physically precedes each comment — an **in-source** cursor that ADVANCES
        // over every comment emitted, because own-line-ness is a question about a
        // comment's own neighbours (docs/comments.md §Trailing and dangling runs). Held
        // at `argument_end` it read the second half of an author-glued run across the
        // first, called it own-line, and split the pair onto two lines.
        let mut prev_end = argument_end;
        // Whether anything is already buffered in a `line_suffix`. Once it is, a
        // same-line block must buffer too: an inline emission renders at its doc
        // position — right after the `;` — while the buffer flushes at the line's end,
        // so the pair comes out REORDERED.
        let mut run_deferred = false;
        // ⚠️ The statement's own claim stops where the trailing TRIVIA run begins: past that
        // point the comments are the enclosing statement LIST's, and every caller here is one
        // of the kinds prettier ejects (`return` / `throw` / `export default` — see
        // [`Printer::statement_hands_off_terminator_gap`]). Emitting them as well is a
        // DOUBLE-PRINT; the list places them by the ordinary own-line / same-line split.
        // A non-block CLAUSE body has no such list, so it claims the whole gap as before.
        let claim_end = self.node_terminator_claim_end(argument_end, span_end, gap);
        for comment in self.comments_to_emit_between(argument_end, claim_end) {
            let same_line = !self.has_newline_between(prev_end, comment.span.start);
            let operand_enclosed =
                same_line && self.gap_has_close_paren(comment.span.end, span_end);
            if comment.is_block && operand_enclosed && operand_parens_printed {
                // Operand-attached (inside stripped parens): `return (x /* c */);`.
                parts.push(d.text(" "));
                parts.push(self.build_comment_doc(comment));
            } else if same_line {
                // Statement-trailing, on the line it was written on: a block trails
                // inline after the `;` (prettier 3.9), a line comment via `line_suffix`
                // (`return x; // c`).
                deferred.push(if run_deferred {
                    self.build_trailing_line_comment_doc(comment)
                } else {
                    self.build_trailing_comment_doc(comment)
                });
                run_deferred |= !comment.is_block;
            } else {
                // Own-line — of EITHER kind. The break rides *inside* the `line_suffix`
                // so it replays in run order after the `;`; a bare `hardline` here would
                // render ahead of an already-buffered line comment and reorder the pair,
                // and it dropped an author blank the terminator's own line survives.
                let blank = self.has_blank_line_between(prev_end, comment.span.start);
                deferred.push(match clause_tail {
                    Some(dedent) => self.build_clause_tail_comment_doc(comment, blank, dedent),
                    None => self.build_trailing_comment_doc_own_line_blank(comment, blank),
                });
                run_deferred = true;
            }
            prev_end = comment.span.end;
        }
        deferred
    }

    /// Whether a (comment-skipping) `)` appears in `[start, end)` — i.e. a stripped
    /// grouping paren follows a trailing comment before the terminator, marking the
    /// comment as operand-enclosed rather than statement-trailing.
    pub(crate) fn gap_has_close_paren(&self, start: u32, end: u32) -> bool {
        find_char_skipping_comments(self.source.as_bytes(), start as usize, end as usize, b')')
            .is_some()
    }

    /// Append the NODE's share of a stripped-paren interior — a spread's
    /// ([`ast::SpreadElement::paren_interior`]) or a destructuring-assignment rest's
    /// ([`ast::RestElement::paren_interior`]) — excluding own-line comments, which
    /// are the parent list's share (array/call/object literal, array/object pattern).
    ///
    /// The node's doc prints only what shares the argument's line: same-line blocks
    /// inline, and the same-line `//` deferred via `line_suffix` so text the parent
    /// appends inline (a comma, an after-comma block) still lands ahead of it. Every
    /// own-line comment — block or line — needs a line of its own that only the parent
    /// can give (a `line_suffix` raised here would escape past the enclosing `]`/`)`),
    /// so the parent picks them up via [`Self::paren_interior_own_line_comments`], in
    /// source order.
    ///
    /// At most ONE comment can defer: a `//` ends its line, so everything after it in
    /// the interior is own-line by construction — which is also what makes the deferred
    /// run structurally weld-free here.
    pub(crate) fn append_paren_interior_trailing_comments(
        &self,
        parts: &mut DocBuf,
        interior: Span,
    ) {
        let d = self.d();
        let argument_end = interior.start;
        for comment in self.comments_to_emit_between(argument_end, interior.end) {
            if self.has_newline_between(argument_end, comment.span.start) {
                // Own-line comments (line or block): skip — the parent's share.
                continue;
            }
            if comment.is_block {
                // Same-line block comment: `...x /* c */`
                parts.push(d.text(" "));
                parts.push(self.build_comment_doc(comment));
            } else {
                // Same-line line comment: defer past the argument's own text.
                parts
                    .push(d.line_suffix(d.concat(&[d.text(" "), self.build_comment_doc(comment)])));
            }
        }
    }

    /// The PARENT's share of a stripped-paren interior.
    ///
    /// When the parser strips grouping parens from a spread's or a destructuring rest's
    /// argument (`...(x⏎/* c */)`) the comments land in `[argument end, node end)` — the
    /// node's `paren_interior` — and that region has **two** emitters which must
    /// partition it exactly once (the seam in `docs/comments.md` §The element-comma seam,
    /// applied to a node's own interior rather than to a list gap). The split is the
    /// source's own-line question — the same question every other trailing seam asks:
    ///
    /// - [`Self::append_paren_interior_trailing_comments`] — the node's own doc — prints
    ///   what shares the argument's line: the same-line blocks inline, and the same-line
    ///   `//` deferred through `line_suffix`.
    /// - the parent (array element loop, call/`new`/member-chain last-argument emitter,
    ///   object property loop, array/object pattern loop) prints the **own-line
    ///   comments** — block or line — which need a line of their own that only the parent
    ///   can give (a `line_suffix` raised from inside the node would escape past the
    ///   enclosing `]`/`)`), each on its own line in source order.
    ///
    /// This function is the ONLY spelling of that share — the emitting form,
    /// [`Self::push_paren_interior_own_line_comments`], reads it from here rather than
    /// re-deriving the predicate. Expressing it as an *anchor shift* instead — scanning
    /// the parent's trailing gap from the argument's end rather than from the node's own
    /// end — reads as equivalent and is not: it hands the parent the node's share too, so
    /// every same-line block and same-line `//` prints twice.
    ///
    /// `interior` is `None` for an element with no stripped-paren interior (anything but a
    /// spread or a rest — [`ast::Expression::paren_interior`]), whose share is empty.
    pub(crate) fn paren_interior_own_line_comments(
        &self,
        interior: Option<Span>,
    ) -> CommentVec<'_> {
        let Some(interior) = interior else {
            return CommentVec::new();
        };
        let arg_end = interior.start;
        self.comments_to_emit_between(arg_end, interior.end)
            .filter(|c| self.has_newline_between(arg_end, c.span.start))
            .collect()
    }

    /// Whether a spread's or rest's stripped-paren interior stands between the element's
    /// own text and the comments written after its `)` — the element's trailing **run**.
    ///
    /// Two things put a line between them on the page, and both come from the interior:
    ///
    /// - the parent's **share** ([`Self::paren_interior_own_line_comments`]) — own-line
    ///   comments the parent prints on lines of their own below the element;
    /// - a same-line `//` the element's own doc defers
    ///   ([`Self::paren_interior_defers_line_comment`]) — it ends the element's line.
    ///
    /// Either way the run cannot trail the element's text, which is what it does when the
    /// parens are absent, so it follows the interior instead: the source order, and the
    /// order the same authoring without the parens prints in. At an element the list
    /// continues past the element's comma therefore moves up against the element, ahead of
    /// the interior and the run ([`Self::push_element_share_and_run`]). `None` has no
    /// interior.
    pub(crate) fn paren_interior_separates_run(&self, interior: Option<Span>) -> bool {
        !self.paren_interior_own_line_comments(interior).is_empty()
            || self.paren_interior_defers_line_comment(interior)
    }

    /// Emit an element's stripped-paren share, then its trailing run — the one emitter of
    /// that order, for every list family: the argument lists, the array and object
    /// literals, and the array and object patterns, at the last element and between two.
    ///
    /// The share prints first because it was written first: the interior lies inside the
    /// parens, the run behind the `)`. Every authoring is ordered as it would be without
    /// the parens (`...b⏎/* i */ /* t */`, `...b⏎// i⏎/* t */`, `...b // i⏎/* t */`),
    /// where both the comment inside the parens and the one written after them simply
    /// trail the element in source order.
    ///
    /// `run` is the element's trailing run in source order, as its list family collects it:
    /// blocks that follow content on their source line, ending at most at one `//` (a `//`
    /// ends its line, so it is always the run's last member). A caller between two
    /// elements has already emitted the comma against the element
    /// ([`Self::paren_interior_separates_run`]), and its run holds what does not lead the
    /// next element ([`Self::run_leads_next_item`]): a run ending in a `//`, or blocks
    /// above an author blank.
    ///
    /// Where the run lands is decided here, once, for every family:
    ///
    /// - behind a line ending in a `//` — the share's last comment, or with no share the
    ///   element's own deferred one — the run opens the next line: a second deferred `//`
    ///   WELDS with the first into one comment, the second `//` becoming text inside it, and
    ///   a block placed ahead of the deferred one reverses the pair;
    /// - [`ShareSite::NextElement`], a run of blocks alone — which reaches here only above
    ///   an author blank, since without one it leads the next element
    ///   ([`Self::run_leads_next_item`]) — opens the next line too, the blank below it;
    /// - otherwise the run trails the line: each block glued on with a space, the `//`
    ///   deferred through `line_suffix` (`...b⏎/* i */ /* t */`, `...b,⏎/* i */ // t⏎c`).
    ///
    /// A run on a fresh line keeps the glue the author gave its members.
    ///
    /// Returns whether the share printed anything — an own-line comment, which a list that
    /// may still collapse must force open (the call-argument loop's `force_expansion`).
    pub(crate) fn push_element_share_and_run<'c>(
        &self,
        parts: &mut DocBuf,
        interior: Option<Span>,
        site: ShareSite,
        run: impl IntoIterator<Item = &'c ast::Comment>,
    ) -> bool {
        self.push_element_share_and_run_with_blanks(parts, interior, site, true, run)
    }

    /// [`Self::push_element_share_and_run`] with the share's author-blank policy named — see
    /// [`Self::push_paren_interior_own_line_comments`], whose array-elision case
    /// is the one caller that passes `false`.
    pub(crate) fn push_element_share_and_run_with_blanks<'c>(
        &self,
        parts: &mut DocBuf,
        interior: Option<Span>,
        site: ShareSite,
        preserve_blanks: bool,
        run: impl IntoIterator<Item = &'c ast::Comment>,
    ) -> bool {
        let share = self.paren_interior_own_line_comments(interior);
        let line_ends_in_line_comment = share.last().map_or_else(
            || self.paren_interior_defers_line_comment(interior),
            |last| !last.is_block,
        );
        let pushed =
            self.push_paren_interior_own_line_comments(parts, interior, site, preserve_blanks);
        let run: CommentVec<'_> = run.into_iter().collect();
        let Some(first) = run.first() else {
            return pushed;
        };
        let run_has_line_comment = run.last().is_some_and(|c| !c.is_block);
        let fresh_line =
            line_ends_in_line_comment || (site == ShareSite::NextElement && !run_has_line_comment);
        if fresh_line {
            // Scanned from the run's own first comment: the run shared its source line with
            // the `)` or the comma, so no author blank sits above it.
            let scan_from = first.span.start;
            self.push_trailing_comment_run(parts, run.iter().copied(), scan_from);
        } else {
            let d = self.d();
            for comment in &run {
                if comment.is_block {
                    parts.push(d.text(" "));
                    parts.push(self.build_comment_doc(comment));
                } else {
                    parts.push(self.build_trailing_line_comment_doc(comment));
                }
            }
        }
        pushed
    }

    /// Whether a comment ending at `comment_end` sits on the next item's line — the item at
    /// `next_pos`, reached across nothing but whitespace, other comments and the grouping
    /// `(`s the parser strips from it. The question every list family asks of a block the
    /// author wrote after a separating comma: glued to the next item it LEADS that item
    /// (`a, /* c */ b`), even behind an element whose stripped parens displaced its trailing
    /// run past the comma, so run membership is one answer in every family — the call
    /// family's routing (`PartitionedComments::route_after_comma_hugging_to_leading`), the
    /// shared element-comma collector's displaced run
    /// ([`Self::collect_element_trailing_comments`]) and the array literal's
    /// `element_gap_split` all ask it here.
    pub(crate) fn comment_hugs_next_item(&self, comment_end: u32, next_pos: u32) -> bool {
        self.is_same_line(comment_end, next_pos)
            || super::calls::has_stripped_paren_gap(self.source, comment_end, next_pos)
    }

    /// Whether an author blank line sits between `from` and the next item past it — the
    /// first comment in source before `next_start`, else the item itself. A true empty
    /// line, not two line breaks: behind a stripped-paren interior the comma is emitted up
    /// against the element, so a comma the author gave a line of its own is not a line of
    /// the output, and neither is the break around it.
    pub(crate) fn blank_before_next_item(&self, from: u32, next_start: u32) -> bool {
        let next = self
            .comments_in_source_between(from, next_start)
            .next()
            .map_or(next_start, |c| c.span.start);
        tsv_lang::printing::has_blank_line_between_strict(self.source, from, next)
    }

    /// Whether a run displaced past an element's comma
    /// ([`Self::paren_interior_separates_run`]) LEADS the next item rather than following
    /// the interior on a line of its own. An own-line block of the run — read with the
    /// stripped `)` absent — keeps the line break the author wrote after it; otherwise the
    /// run leads, and the comma, which now sits behind the element, is asked nothing. Three
    /// conditions, all read from the source:
    ///
    /// - a run of blocks alone: a `//` ends its line, so a run holding one trails the
    ///   interior;
    /// - no author blank between the run and the next item: above one it keeps a line of
    ///   its own, the blank below it;
    /// - no own-line block the author broke after. After the comma the run holds only
    ///   blocks not glued to the next item (a glued one is that item's own leading run, by
    ///   [`Self::comment_hugs_next_item`]), so a run there ends a line and keeps it:
    ///   `…), /* t */⏎c`. Before the comma the comma itself is what usually follows, and a
    ///   break after the comma is not about the run: `…) /* t */, c` and `…) /* t */,⏎c`
    ///   lead, and so does `…/* i */) /* t */⏎, c`, whose run shares a line with the
    ///   interior's comment and so is not own-line — its break is dropped. What keeps its
    ///   line is a run the author gave a line of its own apart from the stripped `)` and
    ///   broke after (`…⏎) /* t */⏎, c`).
    ///
    /// A run that keeps its line takes one below the share — the share-pair rule, not the
    /// paren-free spelling's own placement, which differs by list family.
    /// `next_start` is the next item's start.
    pub(crate) fn run_leads_next_item(
        &self,
        run: &[&ast::Comment],
        comma: Option<u32>,
        next_start: u32,
    ) -> bool {
        let (Some(first), Some(last)) = (run.first(), run.last()) else {
            return false;
        };
        if !run.iter().all(|c| c.is_block) || self.blank_before_next_item(last.span.end, next_start)
        {
            return false;
        }
        if self.comment_hugs_next(last) {
            return true;
        }
        // The author broke after the run: after the comma, or with nothing but the
        // stripped `)` ahead of it on its line, that break is theirs to keep.
        let before_comma = comma.is_some_and(|comma| last.span.start < comma);
        before_comma && !self.line_holds_only_closers_before(first.span.start)
    }

    /// Whether the source line holding `pos` has nothing ahead of `pos` but whitespace and
    /// `)`s — the closers of a stripped paren shell, which the output does not print, so a
    /// comment there reads as one the author gave a line of its own.
    fn line_holds_only_closers_before(&self, pos: u32) -> bool {
        self.source.as_bytes()[..pos as usize]
            .iter()
            .rev()
            .take_while(|&&b| b != b'\n' && b != b'\r')
            .all(|&b| matches!(b, b' ' | b'\t' | b')'))
    }

    /// Emit a displaced run that leads the next item ([`Self::run_leads_next_item`]) — the
    /// one rendering every list family gives it, ahead of that item's own leading run:
    /// each block followed by a space, so the item (or its first leading comment) follows
    /// on the block's line. The one exception is an honored format-ignore directive next,
    /// which keeps its line ([`Self::directive_follows`]).
    pub(crate) fn push_run_leading_next_item(
        &self,
        parts: &mut DocBuf,
        run: &[&ast::Comment],
        next_start: u32,
    ) {
        let d = self.d();
        for (i, comment) in run.iter().enumerate() {
            parts.push(self.build_comment_doc(comment));
            let next = run.get(i + 1).copied().or_else(|| {
                self.comments_to_emit_between(comment.span.end, next_start)
                    .next()
            });
            parts.push(if self.directive_follows(next) {
                d.hardline()
            } else {
                d.text(" ")
            });
        }
    }

    /// Whether a stripped-paren interior holds a comment the enclosing list must EXPAND
    /// around. Two kinds, for two different reasons:
    ///
    /// - an **own-line comment** — block or line, the parent's share above — the parent
    ///   prints it, and it needs a line of its own that only a broken list has;
    /// - a **same-line `//`** — the node's own doc defers it through `line_suffix`, and
    ///   on a list that stays collapsed that buffer flushes past the closer — for a call,
    ///   past its `)` *and* its `;`, re-binding the comment from the argument to the
    ///   statement (`fn(a, ...(b // c⏎))` → `fn(a, ...b); // c`). A deferred run must not
    ///   leave the construct it was written in — `docs/comments.md`. The array literal
    ///   has no such hazard: its brackets already break around a spread carrying a
    ///   comment. The array and object PATTERNS ask it of a rest element for both reasons.
    ///
    /// The predicate below spells the union as "any line comment, or any own-line
    /// comment" — the same set (a line comment is either same-line, forcing via the
    /// deferral, or own-line, forcing as the parent's share). `None` has no interior.
    pub(crate) fn paren_interior_forces_expansion(&self, interior: Option<Span>) -> bool {
        interior.is_some_and(|interior| {
            let arg_end = interior.start;
            self.comments_to_emit_between(arg_end, interior.end)
                .any(|c| !c.is_block || self.has_newline_between(arg_end, c.span.start))
        })
    }

    /// [`Self::paren_interior_forces_expansion`] asked of a whole element list — the
    /// **entry-gate** form, and the only one an argument-list builder should use to decide
    /// whether it must run its comment-aware path at all.
    ///
    /// Asked of EVERY element, not just the last: an interior lies *before* its own
    /// element's end, so no gap scan in any of these builders can see it, and a non-last
    /// spread's interior is exactly as invisible as a last one's. Spelling the gate on
    /// `arguments.last()` is what dropped it at three of the call family's entry points
    /// (the same reach `any_comment_forces_expansion` already has per argument).
    pub(crate) fn any_paren_interior_forces_expansion(
        &self,
        elements: &[&ast::Expression<'_>],
    ) -> bool {
        elements
            .iter()
            .any(|e| self.paren_interior_forces_expansion(e.paren_interior()))
    }

    /// Whether an element's own doc ends in a DEFERRED line comment — a spread or rest
    /// whose stripped grouping parens held a **same-line** `//` (`...(b // c⏎)`), which
    /// [`Self::append_paren_interior_trailing_comments`] emits through `line_suffix` (an
    /// own-line `//` is the parent's share and defers nothing). `None` has no interior.
    ///
    /// Nothing the gap *after* such a node holds may share that output line: a second
    /// deferred `//` welds with it into ONE comment, the second `//` becoming text inside
    /// the first (`// c1 // c2`) — the merge prettier performs here and tsv refuses — and a
    /// block placed there reverses the pair. [`Self::push_element_share_and_run`] reads it
    /// for that reason, giving the run a fresh line; see `docs/comments.md` §Trailing and
    /// dangling runs.
    pub(crate) fn paren_interior_defers_line_comment(&self, interior: Option<Span>) -> bool {
        interior.is_some_and(|interior| {
            let arg_end = interior.start;
            self.comments_to_emit_between(arg_end, interior.end)
                .any(|c| !c.is_block && !self.has_newline_between(arg_end, c.span.start))
        })
    }

    /// Emit the parent's share of a stripped-paren interior
    /// ([`Self::paren_interior_own_line_comments`], empty for `None`) into `parts`: the
    /// first comment on a line of its own below the element, and every later one either
    /// on its own line too or — at a [`ShareSite::Closer`] only — glued to the one before
    /// it where the author glued the pair ([`Printer::trailing_run_hugs_previous`]).
    /// Before a next element ([`ShareSite::NextElement`]) the pair is split: the next pass
    /// reads the share as that element's leading run, where a comment glued behind another
    /// holds nothing open, and the list collapsed around it on the second pass.
    ///
    /// Returns whether anything was emitted — which is also the caller's signal to force
    /// its list open, since an own-line comment is a sibling of the element rather than a
    /// trailer on its line.
    ///
    /// Its one caller is [`Self::push_element_share_and_run_with_blanks`], which orders the
    /// share against the element's trailing run — the share first, as it was written. The
    /// caller does NOT carry a `prev_end` out of here: the run's own gap starts at the
    /// node's end, which already lies past every interior comment, so its blank scan cannot
    /// double-count a blank this loop already consumed.
    ///
    /// Every caller is a hard-broken (or comment-force-expanded) layout: an own-line
    /// comment is exactly the thing that forces one. A `//` in the share is always
    /// last-on-its-line (nothing can share a line behind it), so the hardline before
    /// the next comment — or the caller's own break after the run — is what keeps it
    /// from swallowing what follows.
    ///
    /// `preserve_blanks` keeps an author blank line above a comment. It is `false` for a
    /// share the caller emits **past an elision comma** (the array element loop, when holes
    /// follow the spread). The blank was authored between the argument and the comment, a
    /// gap the share no longer occupies once a structural comma sits in front of it — and
    /// the array's own rule is that a hole carries **no** blank line after it
    /// (`has_blank_line_after_slot`, prettier's `node &&`), so the reprint drops it.
    /// Preserving it here would print a blank the next pass removes.
    pub(crate) fn push_paren_interior_own_line_comments(
        &self,
        parts: &mut DocBuf,
        interior: Option<Span>,
        site: ShareSite,
        preserve_blanks: bool,
    ) -> bool {
        let Some(interior) = interior else {
            return false;
        };
        let comments = self.paren_interior_own_line_comments(Some(interior));
        let mut prev_end = interior.start;
        let mut prev_comment: Option<&ast::Comment> = None;
        for comment in &comments {
            // The glue question and the author-blank question are separate, so the
            // predicate is asked directly rather than through `push_trailing_run_separator`,
            // whose non-glue arm is always blank-preserving.
            if site == ShareSite::Closer
                && self.trailing_run_hugs_previous(prev_comment, comment.span.start)
            {
                parts.push(self.d().text(" "));
            } else if preserve_blanks {
                self.push_blank_preserving_hardline(parts, prev_end, comment.span.start);
            } else {
                parts.push(self.d().hardline());
            }
            parts.push(self.build_comment_doc(comment));
            prev_end = comment.span.end;
            prev_comment = Some(comment);
        }
        !comments.is_empty()
    }

    /// Check if a grouping pair in `[expr_end, boundary_end)` holds trailing comments —
    /// comments the author wrote INSIDE the pair, between the operand and its `)`.
    ///
    /// True when the gap holds a grouping `)` at all (confirming the parser stripped a
    /// `ParenthesizedExpression`; without that check this would false-positive on normal
    /// operator comments, e.g. ternary `? c /* comment */ :`) **and** at least one
    /// comment lies before it.
    ///
    /// ⚠️ The window is `[expr_end, ')')`, not the caller's whole gap
    /// ([`Self::collapsed_grouping_close`]). Stated the other way round — "is there a `)`
    /// after the LAST comment" — one comment written *outside* the pair flipped the whole
    /// question false, and the shell that asked it then emitted **nothing** for the gap,
    /// dropping the run inside the pair along with it (`( // c⏎g // c9⏎) /* t */++` printed
    /// `( // c⏎g⏎)++`). A gap that spans the `)` holds two runs belonging to two emitters,
    /// so the predicate has to be about one of them.
    ///
    /// The existence check is **on page**, not *to emit*: every caller is a layout gate —
    /// does this gap's content force the shell open, keep the pair, break the arrow — and
    /// an owned comment still occupies the page it is not this gap's job to print
    /// (`docs/comments.md` §the three axes). No owned comment can reach one of these gaps
    /// today (ownership needs a node starting after the comment, and every shell gap ends
    /// at a delimiter), so the axis is stated for the reader and for the next boundary
    /// that widens, not for a behaviour it changes.
    ///
    /// The narrow-gap test is inline at the site — a shell gap is a `)` or nothing in
    /// nearly every ask — and only a gap that could hold a comment pays the call below.
    #[inline]
    pub(crate) fn has_trailing_paren_comments(&self, expr_end: u32, boundary_end: u32) -> bool {
        !range_too_narrow_for_a_comment(expr_end, boundary_end)
            && self.has_trailing_paren_comments_wide(expr_end, boundary_end)
    }

    /// The search half of [`Self::has_trailing_paren_comments`] — one outlined copy.
    #[inline(never)]
    fn has_trailing_paren_comments_wide(&self, expr_end: u32, boundary_end: u32) -> bool {
        // The wide window first: it is a binary search over `self.comments` (trivially
        // false in a comment-free document) and a strictly weaker precondition, so the
        // source walk below never runs for the overwhelmingly common gap.
        self.has_comments_on_page_between(expr_end, boundary_end)
            && self
                .collapsed_grouping_close(expr_end, boundary_end)
                .is_some_and(|close| self.has_comments_on_page_between(expr_end, close))
    }

    /// The **outermost** grouping `)` a self-parenthesizing value's shells collapse into.
    ///
    /// A sequence supplies its own required parens, so the printer emits ONE pair where
    /// the source may hold several — those parens plus every redundant shell the parser
    /// stripped around them. The single emitted `)` stands in for all of them, and no
    /// enclosing emitter can see inside a paren pair
    /// ([`Self::trailing_paren_comment_parts`]), so every comment up to the LAST close
    /// has to be emitted inside. Scanning to the FIRST one bounded the range at the
    /// innermost paren and dropped the comment that sits past it outright
    /// (`const k = ((a, b) /* c */);` → `const k = (a, b);`).
    ///
    /// The walk steps over `)` and trivia only, so it stops at the shell run's end rather
    /// than at the caller's boundary — an enclosing construct's own `)` is unreachable
    /// even where that boundary is loose (an `as` cast's operand shell, whose boundary
    /// spans the keyword and its type).
    ///
    /// `None` when the gap holds no `)` at all, leaving the caller its own fallback.
    pub(in crate::printer) fn collapsed_grouping_close(
        &self,
        expr_end: u32,
        boundary_end: u32,
    ) -> Option<u32> {
        let bytes = self.source.as_bytes();
        let mut i = expr_end;
        let mut close = None;
        while let Some(pos) = self.next_significant_byte(i, boundary_end) {
            if bytes[pos] != b')' {
                break;
            }
            close = Some(pos as u32);
            i = pos as u32 + 1;
        }
        close
    }

    /// A sequence value sitting inside a stripped grouping shell: its own required parens
    /// ARE the pair the printer emits, and a trailing comment stays inside them
    /// (`const x = (a, b /* c */)`) rather than floating out after `)` or doubling the
    /// shell ([`Printer::build_sequence_doc_value`], prettier #19263).
    ///
    /// The one seam both shell builders route through, because locating that pair's close
    /// is one question with one answer: they held separate copies of the scan and both
    /// were wrong the same way, dropping the comment of a doubly-shelled value at every
    /// position they serve (`const k = ((a, b) /* c */);`, `() => ((a, b) /* c */)`).
    ///
    /// The `boundary_end` fallback is defensive: a value only reaches a *shell* builder
    /// with a grouping pair around it in source, so the walk has a `)` to find. The
    /// restricted-production site answers this differently and keeps its own scan —
    /// there a bare `return a, b;` has no pair at all, and sweeping to the boundary
    /// would pull the statement's own terminator-gap comments inside the parens.
    fn build_shell_sequence_doc(
        &self,
        seq: &ast::SequenceExpression<'_>,
        span: Span,
        expr_end: u32,
        boundary_end: u32,
        layout: SeqLayout,
    ) -> DocId {
        let grouping_close = self
            .collapsed_grouping_close(expr_end, boundary_end)
            .unwrap_or(boundary_end);
        self.build_sequence_doc_value(seq, span, grouping_close, layout)
    }

    /// The index of the next byte that is neither whitespace nor a comment, at or after
    /// `start` and before `end`; `None` when the range holds nothing else (the free
    /// [`next_significant_byte`], which says why a literal is not stepped over).
    ///
    /// The "what actually comes next in the source?" step both shell questions ask —
    /// [`Self::collapsed_grouping_close`] takes it once per `)`, and
    /// [`Self::shell_meets_statement_terminator`] once. A comment occupies bytes even
    /// where nothing emits it, so a walk that stepped over whitespace alone would stop
    /// on the `/` and answer about the wrong token.
    pub(in crate::printer) fn next_significant_byte(&self, start: u32, end: u32) -> Option<usize> {
        next_significant_byte(self.source, start, end)
    }

    /// Whether a comment in `[expr_end, boundary_end)` forces the operand's grouping
    /// parens to **survive**, at a gap the grammar marks `[no LineTerminator here]`.
    ///
    /// Two gaps qualify, and both are ASI-sensitive: an `as`/`satisfies` cast's
    /// operand→keyword gap and a postfix `++`/`--`'s operand→operator gap (tsc breaks
    /// out of each construct on `scanner.hasPrecedingLineBreak()`). A comment that
    /// occupies more than one line — a `//`, which runs to end of line, or a multi-line
    /// block — therefore cannot be inlined here, because inlining **rewrites the
    /// program**: the `//` swallows the tail (`(1 // c⏎) as const;` → `1 // c as const;`,
    /// which parses as a bare `1`), and the multi-line block puts a real line break
    /// before the keyword (output that does not reparse at all).
    ///
    /// Such a comment can only ever have been authored *inside* a grouping paren shell,
    /// since the bare form is unparseable — so the shell is what holds it in place, and
    /// stripping it is not available the way it is at the sibling keyword→value gaps
    /// ([`Self::build_expression_doc_with_paren_comments`]). A shell is redundant only
    /// when the stripped form can still express the comment's position.
    ///
    /// A single-line block comment inlines as before (`x /* c */ as A`, `x /* c */++`),
    /// matching prettier. Finding the `)` is what keeps this keyed on a real shell, and
    /// the window it bounds — the pair's INTERIOR, not the caller's whole gap — is the
    /// one this question is about: only a comment the pair actually HOLDS can need the
    /// pair kept, and a comment past the `)` belongs to the enclosing gap
    /// ([`Self::append_shell_outside_run`]).
    ///
    /// The multi-line predicate is asked LAST: the two steps before it are a binary
    /// search over `self.comments` and a short source walk, both false on nearly every
    /// cast and update in a real file.
    pub(crate) fn asi_gap_needs_parens(&self, expr_end: u32, boundary_end: u32) -> bool {
        if !self.has_comments_on_page_between(expr_end, boundary_end) {
            return false;
        }
        let Some(close) = self.collapsed_grouping_close(expr_end, boundary_end) else {
            return false;
        };
        self.has_line_spanning_comments_to_emit_between(expr_end, close)
    }

    /// Whether a REDUNDANT shell's leading gap holds a comment the operand OWNS whose own
    /// text spans a line — the second way that shell becomes load-bearing.
    ///
    /// The gap's ordinary trigger is a comment it EMITS, which stripping would drop
    /// outright. An owned comment is never dropped — it travels inside the operand's doc —
    /// so it needs no shell for its own sake. It needs one for ASI's: a `MultiLineComment`
    /// holding a `LineTerminator` *is* one for the syntactic grammar (ecma262 sec-comments),
    /// so stripping the shell puts a line terminator immediately before an `as` / `satisfies`
    /// keyword or a postfix `++`, none of which may start a line — and where the cast sits in
    /// a restricted production, before that keyword's argument as well
    /// (`throw (/* a⏎b */ a) as B;` printed bare is a DEAD document). It is the same
    /// question [`Self::asi_gap_needs_parens`] answers on the trailing side, asked on the
    /// leading one, so the `//` spelling and this one keep one shell between them.
    ///
    /// ⚠️ **Only where the pair is REDUNDANT.** A pair the operand needs anyway already holds
    /// the comment and prints flat around it (`const a = (/* c⏎d */ b + c + d) as T;`,
    /// `typescript/syntax/comments/required_pair_multiline_leading_comment_prettier_divergence`);
    /// retaining there would expand a pair that is not the ASI question at all. A SEQUENCE is
    /// the case `needs_parens` cannot answer for us — it reports false because the sequence's
    /// own printer emits the pair rather than because there is none — so it is named.
    fn redundant_shell_holds_line_spanning_owned_comment(
        &self,
        leading_start: u32,
        expr: &ast::Expression<'_>,
        operand_ctx: ParenContext,
    ) -> bool {
        // A SEQUENCE's own parens ARE the grouping — `needs_parens` says false because the
        // sequence's printer emits them itself, not because the pair is redundant — so the
        // comment is already inside a pair that prints flat around it and nothing is at risk
        // (`const s1 = (/* c⏎d */ b, c) as T;`).
        !matches!(expr.kind, ast::ExpressionKind::SequenceExpression(_))
            && !self.needs_parens(expr, operand_ctx)
            && self
                .comments_in_source_between(leading_start, expr.span().start)
                .any(|c| c.multiline)
    }

    /// The operand of an ASI-sensitive gap (an `as`/`satisfies` keyword, a postfix
    /// `++`/`--`) rendered inside the grouping-paren shell that holds its comments,
    /// emitting **both** of the shell's gaps — `(`→operand and operand→`)`.
    ///
    /// `None` when no shell needs keeping, so the caller falls through to its ordinary
    /// inline path.
    ///
    /// The trailing gap is what makes the shell load-bearing ([`Self::asi_gap_needs_parens`]):
    /// the keyword may not start a line, so a comment spanning lines has nowhere else to go.
    /// The **leading** gap keeps the shell for a different reason — nothing else emits it.
    /// A comment there that is neither glued to the operand (which would make it
    /// `owned_by_node`, printed from the operand's own doc) nor inside the operand's span
    /// belongs to no node at all, so stripping the shell **drops** it outright
    /// (`( // c⏎x) as A` → `x as A`, the comment gone). Retaining on either gap is one
    /// rule for one shell rather than two half-rules that disagree about `( // b⏎x // c⏎)`.
    ///
    /// A **sequence** operand's own required parens are the grouping, so re-wrapping
    /// would double them: with no leading run it delegates to the value builder, which
    /// keeps the trailing run inside the pair
    /// ([`Self::build_expression_doc_keep_paren_comments`]); with one, the pair is built
    /// HERE — the leading gap is the pair's and the value builder's window opens at the
    /// operand, so delegating dropped the run outright (`(// c⏎x, y) as A` →
    /// `(x, y) as A`). The sequence rides the expanded shell BARE
    /// ([`Printer::build_sequence_doc_bare`]), the same one-shell-for-both-gaps layering
    /// every required pair in the family takes.
    ///
    /// ⚠️ `boundary_end` is the KEYWORD / operator, so the gap it bounds spans the pair's
    /// `)` and holds **two** runs: the pair's own trailing run and, past the `)`, the
    /// enclosing gap's. The shell claims the whole window, so it emits both — the first
    /// inside the pair, the second after `close` — and the split is
    /// [`Self::collapsed_grouping_close`], the same `)` every window that opens after an
    /// operand takes its start from (`docs/comments.md` hazard 3). Emitting the window as
    /// one run instead would have carried the outside comment *into* the parens, and the
    /// all-or-nothing gate that preceded this dropped both runs outright.
    ///
    /// ⚠️ **Whether the shell exists may not turn on OWNERSHIP**, which is what the third
    /// answer ([`AsiOperandShell::Bare`] carrying a run) is for. A single-line block the
    /// author glued to a paren the printer strips (`(/* c */ (x)) as A`) is not owned — no
    /// node begins at that `(` — so the EMIT axis sees it and the shell above would open
    /// for it; but the shell's own output glues the comment to the operand, where the
    /// reparse OWNS it, the emit axis goes blind, and the second pass prints the bare form
    /// ([`Self::leading_run_reparses_owned`]). So that run takes the bare form at
    /// once: the caller prints it ahead of the operand, inside any pair the operand needs —
    /// the bytes the owned spelling `(/* c */ x) as A` already reaches. Returning the run
    /// rather than `None` is what keeps the gap's one emitter from forgetting it: the gap
    /// "belongs to no node at all", so a caller that drops the run DROPS the comment.
    pub(crate) fn build_asi_operand_shell_doc(
        &self,
        node_start: u32,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        operand_ctx: ParenContext,
    ) -> AsiOperandShell {
        let expr_start = expr.span().start;
        // The trailing gap opens where the operand's doc stops printing, which for a
        // sequence is its last operand ([`shell_content_end`]).
        let expr_end = shell_content_end(expr);
        let open = find_char_skipping_comments(
            self.source.as_bytes(),
            node_start as usize,
            expr_start as usize,
            b'(',
        )
        .map(|p| p as u32);

        let leading_start = open.map_or(node_start, |p| p + 1);
        let has_leading = open.is_some()
            && (self.has_comments_to_emit_between(leading_start, expr_start)
                || self.redundant_shell_holds_line_spanning_owned_comment(
                    leading_start,
                    expr,
                    operand_ctx,
                ));
        let needs_trailing = self.asi_gap_needs_parens(expr_end, boundary_end);
        if !has_leading && !needs_trailing {
            return AsiOperandShell::Bare(None);
        }
        // A shell the TRAILING gap keeps holds this run either way — glued inside it, the
        // comment is owned on the reparse and the same shell prints the same bytes.
        if !needs_trailing
            && self.leading_run_reparses_owned(leading_start, expr_start, ReparsedRun::SingleLine)
        {
            let run = self
                .build_inline_comments_between_doc_trailing_space_opt(leading_start, expr_start);
            // A SEQUENCE's own pair is the one that survives, and the run is inside it —
            // ahead of the first operand, where the reparse's owner prints it. Left to the
            // caller it would lead the sequence's `(` instead, a form that holds only until
            // the cast takes a pair of its own (`y && (/* c */ (a, b) as T)` hoists the
            // comment out of that pair on the next pass). So this state composes the pair
            // itself, flat, with the operands riding bare — the expanded shell's layering.
            if let (ast::ExpressionKind::SequenceExpression(seq), Some(run)) = (&expr.kind, run) {
                let d = self.d();
                let mut pair: DocBuf = smallvec![
                    d.text("("),
                    run,
                    self.build_sequence_doc_bare(seq, expr.span, expr_end),
                    d.text(")"),
                ];
                // The operand→keyword window holds single-line blocks at most here (the
                // trailing gap needed no shell), and the sequence's own envelope floats
                // those out past its `)` — so they trail the pair, wherever the author
                // put them relative to the closers this state collapses.
                if let Some(trailing) =
                    self.build_inline_comments_between_doc_opt(expr_end, boundary_end)
                {
                    pair.push(trailing);
                }
                return AsiOperandShell::Shell(d.concat(&pair));
            }
            return AsiOperandShell::Bare(run);
        }

        // The pair's `)` splits the window into the run it holds and the run the
        // enclosing gap holds. `None` is the shell kept for its LEADING run alone with no
        // `)` reachable past the operand, where the whole window is the pair's. The
        // interior window ends PAST the `)` (`close + 1`) — it is what proves a pair is
        // there, and [`Self::has_trailing_paren_comments`] looks for it inside the range
        // it is given.
        let close = self.collapsed_grouping_close(expr_end, boundary_end);
        let inner_end = close.map_or(boundary_end, |c| c + 1);

        if matches!(expr.kind, ast::ExpressionKind::SequenceExpression(_)) && !has_leading {
            let seq =
                self.build_expression_doc_keep_paren_comments(expr, inner_end, SeqLayout::Aligned);
            return AsiOperandShell::Shell(self.append_shell_outside_run(seq, close, boundary_end));
        }

        // The shell's `(` is the statement's first token whenever the statement's leftmost
        // node is inside the operand, so it already discharges what the expression-statement
        // wrap exists for — keeping the statement from starting with `{` / `function` /
        // `class`. Clearing the target stops the operand adding a second pair inside this
        // one (`(⏎\t({ a: 1 }) // c⏎) as const`). Not restored afterwards: a rebuild under a
        // conditional group must reach the same answer, and the target is cleared per
        // statement by `build_expression_statement_doc` regardless. A nested cast never
        // owns the target (it is set for the statement's leftmost node only), so this is a
        // no-op there.
        self.expr_stmt_paren_target.set(None);

        // The opening-delimiter rule at this shell's `(`: a `//` the author glued to it
        // keeps that line ([`Self::split_located_paren_glued_run`]), as at every other
        // opening delimiter. The doc carries its own leading space.
        let (paren_trailing, run_start) =
            self.split_located_paren_glued_run(leading_start, open, expr_start);
        let leading_run = self.build_rhs_comments_opt(run_start, expr_start);

        let mut body = DocBuf::new();
        if let Some(run) = leading_run {
            body.push(run);
        }
        body.push(match &expr.kind {
            // Bare: the shell composed below IS the sequence's required pair. Its own
            // printer takes the owned-comment claim ([`Self::build_sequence_doc_bare`] →
            // the run form), so this arm needs none.
            ast::ExpressionKind::SequenceExpression(seq) => {
                self.build_sequence_doc_bare(seq, expr.span, expr_end)
            }
            // A MULTI-LINE block the operand OWNS prints just inside this shell's `(`,
            // outside the operand's own group
            // ([`Printer::build_value_with_outermost_owned_comment`]). This shell is the
            // required pair at the seams that reach it, so it owes the family's rule like
            // every other emitter of one — and it is the arm the plain
            // `(/* c⏎d */ x) as T` path never reaches, since the shell is built only when
            // the gap holds a comment the EMIT axis can see (an un-owned run member) or
            // the operand→keyword gap needs the parens for ASI.
            // An alone-on-line format-ignore directive in the run just emitted freezes the
            // operand ([`Printer::build_left_spine_operand_doc`]): this pair is RETAINED, so
            // the directive keeps the line the author gave it inside it and the reparse
            // reads it in the very same place — a first pass that did not freeze would
            // normalize the author's bytes and then hold that form for good.
            _ => self.build_left_spine_operand_doc(
                leading_start,
                expr,
                FrozenOperandPair::Emitted,
                || self.build_expression_doc_claiming_outermost(expr),
            ),
        });
        if let Some((trailing, _needs_break)) =
            self.trailing_paren_comment_parts(expr_end, inner_end)
        {
            body.extend(trailing);
        }

        let shell = self.compose_expanded_shell_doc(paren_trailing, &body, ")");
        AsiOperandShell::Shell(self.append_shell_outside_run(shell, close, boundary_end))
    }

    /// Whether a paren pair's leading gap holds exactly the run the REPARSE would hand to
    /// the operand: one single-line block comment the author glued to what follows it,
    /// with nothing between it and the operand's first token but the grouping `(`s the
    /// printer strips (and whatever whitespace the author left inside them).
    ///
    /// Printed, that comment lands glued to the operand, which is the parser's ownership
    /// rule (`bind_leading_comment`) — so the next pass finds no comment this gap EMITS, and
    /// whatever the gap decides for it now has to be what the owned spelling gets then, or
    /// the two passes disagree. Every pair whose rendering turns on "does this gap emit a
    /// comment" asks it: the ASI operand shell ([`Self::build_asi_operand_shell_doc`]) and
    /// the required pairs' expand-or-fold ([`Self::build_required_pair_leading_shell_doc`]).
    ///
    /// The glue is the comment's own ([`Self::comment_hugs_next`]), never a distance to the
    /// operand: a line break the author put INSIDE a stripped `(` is erased with it, so
    /// `(/* c */ (⏎x))` reaches the operand glued all the same. Deliberately no wider: a
    /// second comment in the gap stays emit-visible on the reparse too (only the LAST one
    /// can glue to the operand), and a comment the author broke after is not glued at all —
    /// each of those is stable as it stands.
    ///
    /// A MULTI-LINE block is the one shape the two callers answer differently, which is
    /// what `lines` says. At the ASI shell it keeps the shell
    /// ([`Self::redundant_shell_holds_line_spanning_owned_comment`]: an owned multi-line
    /// block is a line terminator ahead of the operand), so it does not fold there
    /// ([`ReparsedRun::SingleLine`]). A REQUIRED pair prints the glued block glued to the
    /// operand whatever its line count, and the reparse owns it and folds — so the
    /// interior newline the shell gate counts is the comment's own, not the run's, and the
    /// shell was a first pass the second one undid ([`ReparsedRun::AnyLines`]).
    fn leading_run_reparses_owned(
        &self,
        gap_start: u32,
        operand_start: u32,
        lines: ReparsedRun,
    ) -> bool {
        let mut run = self.comments_in_source_between(gap_start, operand_start);
        let (Some(comment), None) = (run.next(), run.next()) else {
            return false;
        };
        comment.is_block
            && (!comment.multiline || lines == ReparsedRun::AnyLines)
            && !comment.owned_by_node
            && self.comment_hugs_next(comment)
    }

    /// Append the run written PAST a shell's `)` — the enclosing gap's, not the pair's —
    /// inline before the keyword / operator the caller adds next.
    ///
    /// Both arms of [`Self::build_asi_operand_shell_doc`] need it, and for the same
    /// reason: the shell claims the whole `[operand_end, keyword)` window, so whatever it
    /// does not emit is DROPPED. Only a single-line block can be here — anything
    /// occupying a second line would put a line terminator before an ASI-sensitive token,
    /// which is unparseable — so this is the same emitter the shell-LESS path uses for
    /// the whole gap, and the two agree on the one shape they share.
    fn append_shell_outside_run(
        &self,
        shell: DocId,
        close: Option<u32>,
        boundary_end: u32,
    ) -> DocId {
        let Some(start) = close.map(|c| c + 1).filter(|&start| {
            start < boundary_end && self.has_comments_to_emit_between(start, boundary_end)
        }) else {
            return shell;
        };
        self.d().concat(&[
            shell,
            self.build_inline_comments_between_doc(start, boundary_end),
        ])
    }

    /// The expanded paren-shell rendering every shell emitter shares — the
    /// leading-gap builders (via [`Self::build_leading_run_expanded_shell_doc`])
    /// and the anchored trailing-run shell
    /// ([`Self::build_paren_operand_comment_doc`]'s line arm): `( // c` when the
    /// author glued a `//` to the `(` (the comment runs to end of line and the
    /// indent's hardline supplies the break, so nothing following it is
    /// swallowed; the space is the glued split's), the body one indent in, the
    /// closer back out on its own line. `close` is `")"` where a separate node
    /// prints what follows, `")!"` where this doc owns the non-null's `!`.
    pub(in crate::printer) fn compose_expanded_shell_doc(
        &self,
        paren_trailing: Option<DocId>,
        body: &DocBuf,
        close: &'static str,
    ) -> DocId {
        let d = self.d();
        let open_doc = match paren_trailing {
            Some(comment) => d.concat(&[d.text("("), comment]),
            None => d.text("("),
        };
        d.concat(&[
            open_doc,
            d.indent_hardline(d.concat(body)),
            d.hardline(),
            d.text(close),
        ])
    }

    /// The family's expanded shell for a LEADING run — the one emission every
    /// required-pair leading gap shares: split the `(`-glued `//` (the
    /// opening-delimiter rule), emit the rest of the run above the operand with
    /// its authored own-line placements kept, close with `close`. Callers: the
    /// assignment-target / instantiation-head operand shell
    /// ([`Self::build_shell_operand_doc`]), the non-null's needs-parens arm, and
    /// the sealed optional chain (both `build_ts_non_null_doc` /
    /// `build_sealed_non_null_paren_doc`, whose `close` is `")!"`).
    ///
    /// A commented TRAILING gap rides the SAME shell rather than a second one — the
    /// pair is already expanded, so the operand→`)` run simply follows the operand
    /// inside it ([`Self::push_shell_trailing_run`]). Declining instead and folding both
    /// runs flat, which is what a shell that bailed on a commented trailing gap forced,
    /// left the one authoring that commented both gaps rendering with no shell at all:
    /// the `//` glued to a `(` that never broke, the operand at the ENCLOSING indent,
    /// and the `)` welded to it — the family's shape at neither gap, and prettier's at
    /// neither either.
    pub(in crate::printer) fn build_leading_run_expanded_shell_doc(
        &self,
        gap_start: u32,
        operand_start: u32,
        trailing_gap: Option<(u32, u32)>,
        inner_doc: DocId,
        close: &'static str,
    ) -> DocId {
        let (paren_trailing, run_start) =
            self.split_open_delimiter_glued_run(gap_start, operand_start);
        let mut body = DocBuf::new();
        if let Some(run) = self.build_rhs_comments_opt(run_start, operand_start) {
            body.push(run);
        }
        body.push(inner_doc);
        if let Some((start, end)) = trailing_gap {
            self.push_shell_trailing_run(&mut body, start, end);
        }
        self.compose_expanded_shell_doc(paren_trailing, &body, close)
    }

    /// The operand→`)` run inside a pair the LEADING run already expanded — the same
    /// two arms [`Self::build_paren_operand_comment_doc`] takes when it builds the shell
    /// itself, minus the shell (this body is already inside one).
    ///
    /// A `//` takes the anchored emitter, since every comment here was authored AFTER
    /// the operand and the closer's hardline below ends the line the run defers onto; a
    /// block-only run trails the operand inline.
    fn push_shell_trailing_run(&self, body: &mut DocBuf, start: u32, end: u32) {
        if self.has_line_comments_between(start, end) {
            self.push_anchored_trailing_run(body, start, end, RunLeadingBlank::Keep);
        } else if self.has_comments_to_emit_between(start, end) {
            body.push(self.build_chain_block_comments_doc(start, end, CommentSpacing::Leading));
        }
    }

    /// The family's answer for a REQUIRED pair's LEADING gap — the one rule every
    /// position that prints such a pair asks, rather than five spellings of it.
    ///
    /// `Some` is the expanded shell ([`Self::build_leading_run_expanded_shell_doc`]):
    /// the run occupies a line, so the `(`-glued `//` keeps the `(` line, the operand
    /// takes one indent and `close` comes back out. `None` says this gap does not take
    /// the shell and the caller folds the run flat above the operand instead — the run
    /// fits on one line (a glued single-line block run), which is the only reason left,
    /// and the one run whose newlines are not its own folds with it
    /// ([`Self::leading_run_reparses_owned`]).
    ///
    /// `trailing_gap` is `[operand_end, boundary_end)`, `None` at a position whose pair
    /// has no trailing gap of its own. A commented one does NOT decline the shell: it
    /// rides inside it, after the operand.
    pub(in crate::printer) fn build_required_pair_leading_shell_doc(
        &self,
        gap_start: u32,
        operand_start: u32,
        trailing_gap: Option<(u32, u32)>,
        inner: DocId,
        close: &'static str,
    ) -> Option<DocId> {
        self.required_pair_takes_leading_shell(gap_start, operand_start)
            .then(|| {
                self.build_leading_run_expanded_shell_doc(
                    gap_start,
                    operand_start,
                    trailing_gap,
                    inner,
                    close,
                )
            })
    }

    /// The gate of [`Self::build_required_pair_leading_shell_doc`], for a caller that builds
    /// the shell's body only once the shell is known to be taken
    /// ([`Self::build_shaped_owned_required_pair_doc`]).
    fn required_pair_takes_leading_shell(&self, gap_start: u32, operand_start: u32) -> bool {
        self.has_comments_to_emit_between(gap_start, operand_start)
            && self.has_newline_between(gap_start, operand_start)
            // A newline AROUND a glued block — ahead of it, inside a `(` stripped from
            // behind it, or inside the block itself — is not the run's: the expanded shell
            // would print the comment glued to the operand, which the reparse owns and folds.
            && !self.leading_run_reparses_owned(gap_start, operand_start, ReparsedRun::AnyLines)
    }

    /// The index just past the `)` that closes a REQUIRED pair around an operand
    /// ending at `operand_end`, when the author wrote that pair — `None` when the next
    /// thing in the source is something else (a `(` of an argument list, a `` ` ``),
    /// which means the pair this position prints is tsv's own and the source has no
    /// trailing gap inside it.
    ///
    /// The distinction is load-bearing: `(fn /* t */)()` writes the pair around the
    /// callee and the comment is INSIDE it, while `(/* t */ fn())` writes it around the
    /// whole call and the comment belongs to the call, not to a pair the callee prints.
    pub(in crate::printer) fn paren_shell_close_after(&self, operand_end: u32) -> Option<u32> {
        paren_shell_close_after(self.source, operand_end)
    }

    /// The operand→`)` gap a REQUIRED pair owns, when the pair KEEPS ITS INTERIOR at
    /// this position **and** the author wrote it.
    ///
    /// Both halves matter. `keeps_interior` is the **position's** answer — a pair keeps
    /// its interior at a function/arrow callee or tag (prettier's
    /// `printCommentsForFunction` covers leading and trailing alike) and at a **sealed
    /// optional chain**, where the pair is what stops the chain and both formatters keep
    /// the comment between the operand and the `)`. It is deliberately a parameter and
    /// never re-derived from the operand's KIND here: a kind is a property of the
    /// subtree and holds wherever that subtree appears, while a gap belongs to exactly
    /// one seam, which is a property of the position — `(() => 1 /* c */).p` prints the
    /// same pair as an IIFE callee but its trailing gap is the member seam's, and
    /// claiming it here double-printed the comment. The position-shaped predicates are
    /// [`chain_paren_leading_gap`]'s
    /// family, and the leading half reads the same ones.
    /// The second half is the author's pair, since `(fn /* t */)()` writes it around the
    /// callee while `(/* t */ fn())` writes it around the whole call, where the comment
    /// belongs to the call and to no pair printed here
    /// ([`paren_shell_close_after`]).
    ///
    /// Every window that opens AFTER the operand — the type-argument gap, an argument
    /// list's own leading scan, a tag→`` ` `` gap, a member seam's `object_end` — takes
    /// its start from the returned `)` rather than from the operand's span end, so a
    /// comment emitted inside the parens is not emitted a second time outside them
    /// (`docs/comments.md` hazard 3).
    pub(in crate::printer) fn owned_pair_trailing_gap(
        &self,
        operand_end: u32,
        keeps_interior: bool,
    ) -> Option<(u32, u32)> {
        keeps_interior
            .then(|| self.paren_shell_close_after(operand_end))
            .flatten()
            .map(|close| (operand_end, close))
    }

    /// Whether neither gap of a paren pair holds a comment on the page: `leading` is the
    /// `(`→operand window, `trailing` the operand→`)` one (`None` where the pair has no
    /// trailing gap of its own). What a callee pair's caller hands
    /// `CalleeParens::build_body_doc`, and the chain base's twin of it — a curried arrow
    /// chain's callee shape opens the pair from inside the operand's doc, so a comment in
    /// either gap leaves the pair to the shell builders.
    pub(in crate::printer) fn pair_gaps_are_comment_free(
        &self,
        leading: (u32, u32),
        trailing: Option<(u32, u32)>,
    ) -> bool {
        !self.has_comments_on_page_between(leading.0, leading.1)
            && trailing.is_none_or(|(start, end)| !self.has_comments_on_page_between(start, end))
    }

    /// Where the window AFTER an operand opens: past the `)` of a pair that emitted its
    /// own trailing gap, or the operand's own span end where there is no such pair.
    ///
    /// `trailing_gap` is that operand's [`Self::owned_pair_trailing_gap`], passed in
    /// rather than re-derived so the offset and the claim come off ONE lookup. The one
    /// spelling of it, so the three positions that print such a pair — the bare callee,
    /// a member chain's callee, a tagged template's tag — and every window they open
    /// (type arguments, an argument list's leading scan, the tag→`` ` `` gap) cannot
    /// disagree about where the pair ends.
    pub(in crate::printer) fn gap_start_after_owned_pair(
        operand_end: u32,
        trailing_gap: Option<(u32, u32)>,
    ) -> u32 {
        trailing_gap.map_or(operand_end, |(_, close)| close)
    }

    /// A REQUIRED pair that owns BOTH of its gaps — `(`→operand and operand→`)` — around an
    /// operand with one rendering: the frozen chain base, the bare IIFE callee, a tagged
    /// template's function tag, the sealed `new` callee / tag
    /// ([`Self::build_sealed_non_null_paren_doc`]). The unshaped form of
    /// [`Self::build_shaped_owned_required_pair_doc`], which carries the layering.
    pub(in crate::printer) fn build_owned_required_pair_doc(
        &self,
        leading_gap: (u32, u32),
        trailing_gap: Option<(u32, u32)>,
        body: DocId,
        close: &'static str,
    ) -> DocId {
        self.build_shaped_owned_required_pair_doc(
            leading_gap,
            trailing_gap,
            || body,
            |lead, trailing| self.concat_pair_runs(lead, body, trailing),
            close,
        )
    }

    /// `content` between a folded pair's leading run and its inline trailing run — the
    /// unshaped fold every [`Self::build_shaped_owned_required_pair_doc`] caller shares.
    pub(in crate::printer) fn concat_pair_runs(
        &self,
        lead: Option<DocId>,
        content: DocId,
        trailing: Option<DocId>,
    ) -> DocId {
        match (lead, trailing) {
            (None, None) => content,
            (Some(lead), None) => self.d().concat(&[lead, content]),
            (None, Some(trailing)) => self.d().concat(&[content, trailing]),
            (Some(lead), Some(trailing)) => self.d().concat(&[lead, content, trailing]),
        }
    }

    /// A REQUIRED pair that owns BOTH of its gaps — `(`→operand and operand→`)` — where the
    /// position may SHAPE the operand's folded rendering (the chain's sealed / IIFE base:
    /// the expanding-parens hang, a ternary's `)`-dropping group).
    ///
    /// The one emission for every position where the pair the printer emits is the
    /// author's own and nothing outside it can reach between the parens. Layering, which is
    /// the family's convention rather than this function's choice:
    ///
    /// - a leading run that occupies a line takes the expanded shell
    ///   ([`Self::build_required_pair_leading_shell_doc`]) — and a commented TRAILING
    ///   gap rides that SAME shell, after the operand, rather than declining it;
    /// - otherwise the leading run folds flat above the operand, and a line-spanning
    ///   TRAILING run then builds the shell around that
    ///   ([`Self::build_trailing_run_expanded_shell_doc`]), while an inline block run
    ///   trails the operand inside the shape;
    /// - with neither, the pair is bare.
    ///
    /// So exactly ONE shell is built however many of the two gaps hold comments. Two
    /// nest; none leaves the `//` glued to a `(` that never breaks and the operand at
    /// the enclosing indent.
    ///
    /// ⚠️ **A shape is a shell too, which is why this function — not its caller — decides
    /// which arm gets which body.** The expanding-parens hang is a paren-body layout of its
    /// own (`group([indent([softline, x]), softline])`), so the two expanded shells print
    /// `plain`, the operand's UNSHAPED doc: inside a hard-expanded shell no width is left
    /// to decide, and a hang nested there breaks with the body into a blank line plus a
    /// second indent on each side, which the next pass keeps as an author blank — a
    /// format that grew a line per pass. The fold is the one arm that keeps the shape, and
    /// the shape goes OUTSIDE the runs: `fold_shaped` receives the folded leading run and an
    /// inline (block-only) trailing run and returns `shape(concat([lead, content, trailing]))`,
    /// so a breaking hang carries the lead down onto the operand's line with it, and the
    /// trailing block stays beside the operand's last line. Left outside the hang, the lead
    /// stayed on the `(` line with a newline behind it, and the reparse read that as a run
    /// occupying a line and took the shell. `plain` is lazy — built only by a shell, so a
    /// caller whose folded content is a different doc (a binary base's chain-for-parens)
    /// never pays for both.
    pub(in crate::printer) fn build_shaped_owned_required_pair_doc(
        &self,
        leading_gap: (u32, u32),
        trailing_gap: Option<(u32, u32)>,
        plain: impl FnOnce() -> DocId,
        fold_shaped: impl FnOnce(Option<DocId>, Option<DocId>) -> DocId,
        close: &'static str,
    ) -> DocId {
        let d = self.d();
        let (gap_start, operand_start) = leading_gap;
        if self.required_pair_takes_leading_shell(gap_start, operand_start) {
            return self.build_leading_run_expanded_shell_doc(
                gap_start,
                operand_start,
                trailing_gap,
                plain(),
                close,
            );
        }
        let lead = || self.build_rhs_comments_opt(gap_start, operand_start);
        let mut trailing = None;
        if let Some((start, end)) = trailing_gap {
            if self.has_line_spanning_comments_to_emit_between(start, end) {
                // The trailing emitter's line arm is the other expanded shell, so it takes
                // the unshaped body too.
                let body = plain();
                let body = lead().map_or(body, |lead| d.concat(&[lead, body]));
                return self.build_trailing_run_expanded_shell_doc(start, end, body, close);
            } else if self.has_comments_to_emit_between(start, end) {
                // An inline block run trails the operand INSIDE the shape, as the lead leads
                // it: appended past a breaking hang, it landed behind the hang's closing
                // break, at the pair's own column plus a space.
                trailing =
                    Some(self.build_chain_block_comments_doc(start, end, CommentSpacing::Leading));
            }
        }
        d.concat(&[d.text("("), fold_shaped(lead(), trailing), d.text(close)])
    }

    /// An operand in a position that prints a REQUIRED pair around some operand
    /// kinds, with the node's `^`→operand gap emitted — the whole operand doc for
    /// an assignment expression's / assignment pattern's target
    /// ([`ParenContext::AssignmentTarget`]) and an instantiation expression's head
    /// ([`ParenContext::InstantiationExpression`]).
    ///
    /// The gap is `[node_start, operand.span().start)`, `node_start` being the
    /// enclosing node's own start — for a parenthesized operand, its authored `(`.
    /// Nothing else emits it: a comment there that is not glued to the operand
    /// (which would make it `owned_by_node`, printed from the operand's own doc)
    /// belongs to no node, so the bare `"(" + operand + ")"` spelling DROPPED it
    /// outright (`( // c⏎x as T) = 1;` → `(x as T) = 1;`).
    ///
    /// Where the position REQUIRES the pair — a type-assertion target (`x as T = 1;`
    /// is a parse error), an arrow instantiation head — the pair prints whatever the
    /// comment does, and tsv keeps the run INSIDE it, where the author wrote it;
    /// prettier hoists it out in front, re-binding it from the operand to the whole
    /// statement (cataloged: conformance_prettier_ts_comments.md §Comment
    /// relocation, "Assignment-target shell, leading comment"). A run that occupies
    /// a line — a `//`, an own-line block — expands the pair, with the `( // c` glue
    /// and the author's own-line placements kept
    /// ([`Self::build_asi_operand_shell_doc`]'s rendering one construct over); a
    /// glued single-line block run stays flat.
    ///
    /// Any other operand's pair is REDUNDANT and strips (`(// c⏎x) = 1;`,
    /// `(// c⏎fn)<string>;`), and the stripped form still expresses the run's
    /// position — it leads the statement, exactly where prettier lands it.
    pub(in crate::printer) fn build_shell_operand_doc(
        &self,
        node_start: u32,
        target: &ast::Expression<'_>,
        context: ParenContext,
    ) -> DocId {
        self.build_shell_operand_doc_with(node_start, target, context, || {
            self.build_expression_doc(target)
        })
    }

    /// [`Self::build_shell_operand_doc`] over the operand's doc from `build` — for an
    /// operand its position prints in a role of its own (a compound assignment's literal
    /// left, [`Printer::build_compound_target_doc`]), with the shell's gaps unchanged.
    pub(in crate::printer) fn build_shell_operand_doc_with(
        &self,
        node_start: u32,
        target: &ast::Expression<'_>,
        context: ParenContext,
        build: impl FnOnce() -> DocId,
    ) -> DocId {
        let d = self.d();
        let target_start = target.span().start;
        let needs_parens = self.needs_parens(target, context);
        // Zero-comment fast gate, emit-keyed on purpose: the layouts below differ
        // only in where EMITTED comments render — an owned (target-glued) block
        // prints identically inside the flat pair from the target's own doc, and
        // never asks the pair to expand.
        if !self.has_comments_to_emit_between(node_start, target_start) {
            let inner = build();
            return if needs_parens { d.parens(inner) } else { inner };
        }
        let open = find_char_skipping_comments(
            self.source.as_bytes(),
            node_start as usize,
            target_start as usize,
            b'(',
        )
        .map(|p| p as u32);
        let leading_start = open.map_or(node_start, |p| p + 1);
        // A comment that occupies a line expands the pair, on the family's shared
        // rule. The read is in-source over the whole gap, which cannot over-fire:
        // the gate above already found a comment to emit (a comment-free author
        // break never reaches here), a `//` always ends its line, and an own-line
        // block carries its break. This position's pair encloses the operand alone,
        // so it has no trailing gap to yield the shell to.
        //
        // The operand is built ONCE for whichever layout takes it: handed to the shell
        // eagerly and rebuilt for the flat tail when the shell declined, it cost two builds
        // a level, 2^depth for a commented pair nested in itself (`(/*c*/(…a)<T>)<T>`).
        let inner = build();
        if needs_parens
            && let Some(shell) = self.build_required_pair_leading_shell_doc(
                leading_start,
                target_start,
                None,
                inner,
                ")",
            )
        {
            return shell;
        }
        // The flat tail serves both regimes: a glued-block run leads the operand —
        // inside the pair where one prints, ahead of the bare operand where the
        // stripped run leads the statement (and there a line comment's hardline
        // separator is what keeps the statement after it on its own line). The bare
        // operand of an instantiation is a left-spine hoist site, so it declines a region
        // an enclosing claimer prints (`await ((// c⏎a))<T>`); no claim reaches an
        // assignment target, where this is the plain gap run. The span names no claimer.
        let lead = self.removed_paren_comments_opt(
            Span::new(node_start, target.span().end),
            leading_start,
            target_start,
        );
        let core = match lead {
            Some(lead) => d.concat(&[lead, inner]),
            None => inner,
        };
        if needs_parens { d.parens(core) } else { core }
    }

    /// Build expression doc, stripping a redundant grouping paren around a trailing
    /// comment and keeping the comment inline after the expression.
    ///
    /// When the parser strips parens from `(expr /* c */)`, comments between
    /// `expr.span().end` and `boundary_end` would be lost. For an inline same-line
    /// block comment we keep it trailing the expression (`expr /* c */`), matching
    /// prettier — stripping the redundant parens does not move the comment. Line /
    /// own-line comments need the parens (a bare line comment would swallow the
    /// following token), so those defer to `build_expression_doc_keep_paren_comments`.
    ///
    /// `position_parens` says the CALLING POSITION will parenthesize this value anyway
    /// (`const x = (a = b)`), which makes the shell **retained** rather than stripped —
    /// see [`Self::shell_value_keeps_own_parens`], the one predicate that answer is read
    /// through.
    ///
    /// Used for variable init, assignment RHS, and ternary branches. A `for` header's
    /// init declarator takes [`Self::build_for_init_value_doc`] instead — same handling,
    /// minus the statement-terminator deferral its `;` does not license; a value of one of
    /// these positions that IS a header clause's own gets that answer here, through
    /// [`Self::shell_closes_for_clause`].
    pub(crate) fn build_expression_doc_with_paren_comments(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        position_parens: bool,
    ) -> DocId {
        self.build_shell_value_doc(
            expr,
            boundary_end,
            self.shell_tail(boundary_end),
            position_parens,
            None,
        )
    }

    /// Which tail a value shell closing at `boundary_end` has, for the positions that do not
    /// name one ([`ShellTail`]).
    fn shell_tail(&self, boundary_end: u32) -> ShellTail {
        if self.shell_closes_for_clause(boundary_end) {
            ShellTail::ForClauseSeparator
        } else {
            ShellTail::StatementTerminator
        }
    }

    /// Whether a value shell closing at `boundary_end` is the one a `for` header CLAUSE ends
    /// at ([`Printer::for_clause_end`]).
    ///
    /// ⚠️ **One fact, two consequences, which is why the builder and its caller both ask
    /// it.** For the builder it is the tail: the `;` behind this shell separates clauses, so
    /// a trailing block stays inline instead of deferring out of the header (a `line_suffix`
    /// there drains past the loop's whole BODY, and the form it leaves is its own fixed
    /// point, so no gate sees it). For the caller it says the builder placed the header's
    /// `[~In]` pair ITSELF — inside the trailing comment, where the pair belongs
    /// (`a = ('k' in o) /* c */`) — so a position that wraps the shell's result again
    /// ([`Printer::wrap_for_init_in`] at the assignment RHS and the ternary branch) doubles
    /// it. Answering the two separately is how one site comes to print `((a in b))`.
    pub(crate) fn shell_closes_for_clause(&self, boundary_end: u32) -> bool {
        self.for_clause_end.get() == Some(boundary_end)
    }

    /// Whether the value shell closing at `boundary` has ALREADY supplied the `for` header's
    /// `[~In]` pair, so the position must not add one through
    /// [`Printer::wrap_for_init_in`] / [`Printer::wrap_frozen_for_init_in`].
    ///
    /// Two shapes, both stated by [`Printer::build_shell_value_doc`] and neither visible
    /// from the doc it hands back: it RETAINED the author's pair, which parenthesizes the
    /// `in` itself ([`Self::shell_value_keeps_own_parens`]), or the shell closes the header's
    /// own CLAUSE, where the builder places the pair inside the trailing comment
    /// ([`Self::shell_closes_for_clause`]) — a second pair outside it would read as the
    /// author's. Asked by the assignment RHS on both its frozen and unfrozen paths; a
    /// `boundary` of `None` is a position with no shell, which supplied nothing.
    pub(crate) fn shell_supplies_for_init_pair(
        &self,
        expr: &ast::Expression<'_>,
        boundary: Option<u32>,
    ) -> bool {
        boundary.is_some_and(|end| {
            self.shell_closes_for_clause(end) || self.shell_value_keeps_own_parens(expr, end, false)
        })
    }

    /// [`Self::build_expression_doc_with_paren_comments`] for a value the position froze
    /// (`prettier-ignore` in its `=`→value gap): the same shell, with the verbatim slice
    /// standing in for the expression doc.
    ///
    /// ⚠️ **The freeze does not take the value out of its shell.** The slice is the value's
    /// own node span, so the author's grouping parens lie OUTSIDE it and the gap between
    /// the slice and that `)` is the shell's, exactly as in the unfrozen form — a frozen
    /// arm that skipped this builder printed its own bare `parens()` and left that gap with
    /// no emitter at all, DROPPING every comment in it (`docs/comments.md` hazard 4; a
    /// printer that synthesizes its own `(`…`)` owns the gap inside it, per
    /// [`Self::trailing_paren_comment_parts`]). Routing through here is what keeps the
    /// frozen and unfrozen forms answering the gap identically — which shell is retained,
    /// where the comment renders, and when it defers past the terminator are all questions
    /// about the GAP, not about what renders between the parens.
    pub(crate) fn build_frozen_value_shell_doc(
        &self,
        expr: &ast::Expression<'_>,
        frozen: Span,
        boundary_end: u32,
        position_parens: bool,
    ) -> DocId {
        self.build_shell_value_doc(
            expr,
            boundary_end,
            self.shell_tail(boundary_end),
            position_parens,
            Some(frozen),
        )
    }

    /// Whether [`Self::build_expression_doc_with_paren_comments`] supplies the value's
    /// paren pair ITSELF, so the calling position must not add a second one.
    ///
    /// The single predicate both re-parenthesizing positions ask — a declarator
    /// initializer and a ternary branch. They each own a `needs_parens` question of their
    /// own (`position_parens`), but "did the callee already wrap?" is one question with
    /// one answer, and answering it twice is how the pair gets doubled at one site and
    /// dropped at the other (a ternary CONSEQUENT bounds this scan empty, so the callee
    /// never wraps there however the position answers `needs_parens`).
    pub(crate) fn shell_value_keeps_own_parens(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        position_parens: bool,
    ) -> bool {
        // The gap's own content forces the pair open, whatever the position does — the
        // stronger half, spelled once ([`Self::value_shell_forced_open`]) and read from here
        // so a shell this predicate reports as retained is exactly one that seam can act on.
        self.value_shell_forced_open(expr, boundary_end)
            // Or the calling position parenthesizes this value anyway, so the pair is in the
            // output whatever the builder does and nothing in the gap may cross it — a
            // same-line block included. That pair never OPENS, which is why the seams that
            // choose the operator's layout read the disjunct above instead of this.
            || (position_parens && self.value_shell_pair_in_question(expr, boundary_end))
    }

    /// Whether the author's grouping pair around this value is one the shell builder decides
    /// about at all: there is a comment in its trailing gap to decide for, and the value is
    /// not one that supplies its own pair regardless.
    ///
    /// A **sequence self-parenthesizes on every path**, so its shell is never the retained
    /// one — the builder claims it at its own arm ([`Self::build_shell_value_doc`]) and a
    /// caller that wraps reads `false` here rather than doubling the pair. The exclusion is
    /// spelled once, for both retention predicates: giving it to only one had a sequence
    /// value answer "the shell is forced open" where nothing had retained a shell, which
    /// changed the operator's layout under a comment that still deferred past the `;`.
    fn value_shell_pair_in_question(&self, expr: &ast::Expression<'_>, boundary_end: u32) -> bool {
        !matches!(expr.kind, ast::ExpressionKind::SequenceExpression(_))
            && self.has_trailing_paren_comments(expr.span().end, boundary_end)
    }

    /// Add a value position's clarity parens around a shell-built value — unless the shell
    /// builder already supplied the pair ([`Self::shell_value_keeps_own_parens`]).
    ///
    /// The two declarator positions (statement-level and `for`-header) resolve
    /// `position_parens` themselves, then hand it here with the doc the shell builder
    /// returned for it. `position_parens` must be the value the **builder received**: the
    /// two sides answer one question, and asking it twice is how the pair gets doubled at
    /// one site and dropped at the other. A ternary branch answers a different pair
    /// question than the flag it passes the builder, so it applies the predicate at its own
    /// seam (`parenthesize_ternary_branch`) rather than through here.
    pub(crate) fn wrap_value_position_parens(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        position_parens: bool,
        inner: DocId,
    ) -> DocId {
        if position_parens
            && !self.shell_value_keeps_own_parens(expr, boundary_end, position_parens)
        {
            self.d().parens(inner)
        } else {
            inner
        }
    }

    /// Whether the gap's own content forces the shell to be RETAINED — the layout half of
    /// [`Self::shell_value_keeps_own_parens`], asked by the builder that acts on it and by
    /// the caller that must not double the pair.
    ///
    /// ⚠️ **One question, one predicate, one AXIS.** Spelling this on the two sides
    /// separately AND on different axes — the caller counting comments **on page**, the
    /// builder only those it would **emit** — has an owned comment in the gap make
    /// the caller skip a wrap the builder never makes, stripping the value's clarity parens.
    /// This is a layout gate ("does anything occupy the page here?"), so the on-page axis is
    /// the correct one for both (`docs/comments.md` §the three axes).
    fn shell_gap_retains_parens(
        &self,
        expr_end: u32,
        boundary_end: u32,
        position_parens: bool,
    ) -> bool {
        // The calling position parenthesizes this value anyway, so the pair is in the
        // output whatever this builder does — nothing may cross it.
        position_parens || self.shell_gap_holds_unplaceable_comment(expr_end, boundary_end)
    }

    /// Whether the shell's trailing gap holds a comment with **no inline placement**: a
    /// line comment, which would swallow whatever the output puts behind it on that line,
    /// or a comment the author gave a line of its own.
    ///
    /// One cause, and the two things that follow from it are why both sides ask it. Read
    /// with the position's own answer ([`Self::shell_gap_retains_parens`]) it says the pair
    /// must SURVIVE the strip — a stripped shell has nowhere to put such a comment. Read
    /// alone, where the pair is not in question but its SHAPE is, it says a
    /// self-parenthesizing value may not print its own `Aligned` pair: only the expanded
    /// shell has a line to spare above its `)`.
    fn shell_gap_holds_unplaceable_comment(&self, expr_end: u32, boundary_end: u32) -> bool {
        self.comments_on_page_between(expr_end, boundary_end)
            .any(|c| !c.is_block || self.has_newline_between(expr_end, c.span.start))
    }

    /// Whether the value's own grouping shell is RETAINED **and forced open** by what sits
    /// in its trailing gap — a `//`, or a comment the author gave a line of its own
    /// ([`Self::shell_gap_holds_unplaceable_comment`]).
    ///
    /// **The assignment family's layout rule, stated once.** That break is the COMMENT's,
    /// not a break point inside the value, so the operator must not take one as well: the
    /// assignment HUGS the shell (`x = (⏎\ta?.b! // c⏎);`) rather than hanging it below the
    /// operator (`x =⏎\t(⏎\t\ta?.b! // c⏎\t);`), which spends two indents on one comment and
    /// puts the `(` on a line of its own. It is the answer the shapes that never reach a
    /// hang already give — an object-literal value, a fluid call, a ternary — and the one
    /// `return` / `throw` / `export default` / an arrow body / a bare expression statement
    /// give at the same authoring.
    ///
    /// ⚠️ **"Retained VALUE shell", never "the doc starts with `(`".** The question is about
    /// the pair the AUTHOR wrote around this value and the comment that keeps it; a doc that
    /// merely opens with a parenthesis — an arrow's parameter list, a call's arguments — is
    /// not this, and hugging on that reading moves layouts that have nothing to do with the
    /// shell.
    ///
    /// Read by the two seams that hang a value under an operator, so they cannot answer it
    /// differently: [`crate::printer::Printer::build_assignment_layout`] (assignment
    /// expressions, class fields, object values) and the declarator's hand-rolled twin
    /// (`statements/variable.rs`, through its `is_layout_eligible` gate). Deliberately NOT
    /// keyed on the value's kind — the shell's break belongs to the comment whatever the
    /// value is.
    ///
    /// This is the STRONGER half of [`Self::shell_value_keeps_own_parens`], which reads it as
    /// its first disjunct so the implication holds by construction: a forced-open shell is a
    /// retained one. What it drops is that predicate's `position_parens` arm — a pair the
    /// POSITION prints anyway survives a same-line block too (`const k = (a = b /* c */);`),
    /// and that shell never opens, so it is no reason to change the operator's layout. The
    /// value-kind exclusion is shared ([`Self::value_shell_pair_in_question`]): a sequence
    /// retains no shell here, so it forces none open either.
    pub(in crate::printer) fn value_shell_forced_open(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
    ) -> bool {
        self.value_shell_pair_in_question(expr, boundary_end)
            && self.shell_gap_holds_unplaceable_comment(expr.span().end, boundary_end)
    }

    /// The `for`-header init counterpart of
    /// [`Self::build_expression_doc_with_paren_comments`].
    ///
    /// A header init declarator's shell is followed by the header's **clause separator**,
    /// not by a statement `;`, so the deferral arm below must not fire: a comment sent
    /// past that separator leaves the declarator it was written in, and there is nothing
    /// out there to hold it — prettier, which does relocate it, cannot keep it either
    /// (its next pass carries a run's later comment clean out of the header, past the
    /// `)`, into the body's leading position). Everything else is shared with the
    /// statement-level path, which is the point: the block comment strips inline and the
    /// line comment retains the shell for exactly the same reasons there.
    ///
    /// `position_parens` carries the declarator's own clarity-paren answer
    /// (`ParenContext::VariableInit` — an assignment as a value takes a pair), exactly as
    /// the statement-level path carries it: a header declarator is a declarator, and the
    /// `for` exemption prettier applies is to the init **clause's own expression**
    /// (`for (a = b = c; ;)`), not to a value one binding deeper.
    ///
    /// ⚠️ **This is the declarator's own value, not "lexically under a for header".** The
    /// ambient `in_for_init` flag spans nested function and class bodies, where a real
    /// statement terminator does exist and the deferral is correct
    /// (`for (let i = (() => { const k = (a /* c */); })(); ;)` keeps `k`'s comment past
    /// its `;`) — so the distinction is threaded from the one builder that knows it
    /// rather than read from that flag. A value the header reaches through some OTHER
    /// position — a clause that is an assignment, whose RHS shell is the assignment's own —
    /// draws the same line from its shell's boundary
    /// ([`Self::shell_closes_for_clause`]), never from the flag either.
    ///
    /// `frozen` is the value-head freeze this position resolved, exactly as
    /// [`Self::build_frozen_value_shell_doc`] carries it for the statement-level twin: the
    /// slice replaces the expression doc and nothing else moves, because which shell is
    /// retained and where its comment renders are questions about the GAP, not about what
    /// renders between the parens.
    pub(crate) fn build_for_init_value_doc(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        position_parens: bool,
        frozen: Option<Span>,
    ) -> DocId {
        self.build_shell_value_doc(
            expr,
            boundary_end,
            ShellTail::ForClauseSeparator,
            position_parens,
            frozen,
        )
    }

    /// [`Self::build_for_init_value_doc`] at a `for` header sequence clause's **last
    /// operand**, whose erased grouping shell closes at the clause's own end.
    ///
    /// Every earlier operand's shell gap is claimed by the comma that follows it; the last
    /// operand's has no claimant at all, so without this the comments in it are DROPPED
    /// (`docs/comments.md` hazard 4). It is the clause's gap in every respect the shell
    /// builder decides — the block strips inline, a `//` or an own-line comment retains the
    /// shell, nothing defers past a separator that terminates no statement, and a
    /// self-parenthesizing operand takes the gap inside the pair it prints for itself —
    /// which is why it routes to the clause's own builder rather than growing an emitter or
    /// a tail of its own. `position_parens` is always false: nothing parenthesizes a
    /// sequence operand, so the `[~In]` wrap is the only pair the position adds, exactly
    /// the one the clause's `build_elem` would.
    pub(crate) fn build_for_clause_operand_doc(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        frozen: Option<Span>,
    ) -> DocId {
        self.build_for_init_value_doc(expr, boundary_end, false, frozen)
    }

    /// The value's own doc inside a shell arm that does NOT print the pair itself: the
    /// verbatim frozen slice where the position resolved a freeze, else the ordinary
    /// expression doc. Both spellings supply a self-parenthesizing value's own required
    /// pair ([`Self::build_frozen_expression_doc`] is `build_expression_doc`'s twin in
    /// exactly that), so the arms that return it need no sequence case of their own.
    fn build_shell_inner_doc(&self, expr: &ast::Expression<'_>, frozen: Option<Span>) -> DocId {
        match frozen {
            Some(frozen) => self.build_frozen_expression_doc(expr, frozen),
            None => self.build_expression_doc(expr),
        }
    }

    /// Where a grouping shell's TRAILING gap opens: the position past everything the
    /// value's own doc will print, so the shell's claim and the value's PARTITION the
    /// source between them (`docs/comments.md` §The element-comma seam — unclaimed is a
    /// DROP, doubly-claimed a DOUBLE-PRINT).
    ///
    /// Three answers, each keyed on who prints the region behind the value:
    ///
    /// - a FROZEN value prints its source verbatim, shell interior and all, so the gap
    ///   opens at the end of the SLICE ([`Self::element_claim_anchor`]). Anchored inside
    ///   it, the shell re-emits bytes the slice already printed — and, since the emitted
    ///   form still carries the directive and re-freezes, one more copy on every later
    ///   pass;
    /// - a `SequenceExpression` whose gap holds the shell's `)` hands its operands' own
    ///   trailing region to the single pair it prints ([`shell_content_end`]): that pair
    ///   stands in for the shell the strip removed, so the comment stays where the shell
    ///   held it (`const x = (fff, (aaa /* c */));` → `(fff, aaa /* c */)`, prettier #19263).
    ///   Anchored at `span.end` instead, the gap reads as empty, this builder hands back the
    ///   plain doc, and the sequence's own float-out envelope carries the comment OUT of the
    ///   pair, where the statement's terminator moves it again on the next pass;
    /// - everything else stops at the span end, the sequence with no `)` in its gap
    ///   included. That gap is the caller's whole window, and a caller that bounds it at the
    ///   value's own span — a ternary CONSEQUENT, whose scan stops where the `:` gap's
    ///   emitter starts — leaves no room for a shell `)`, which is the tell that the region
    ///   is the sequence's own tail rather than a shell's. Reaching into it there hands the
    ///   comment to the pair on pass 1 and to the consequent→`:` emitter on pass 2
    ///   (`c ? (x, (y /* t */)) : z` → `(x, y /* t */)` → `(x, y) /* t */`).
    ///
    /// `printer_owns_grouping` is what the source `)` scan is a proxy for: the second answer
    /// asks whether a pair will enclose this region in the OUTPUT, and a caller whose pair
    /// is the printer's own — the restricted productions' hanging parens, emitted whatever
    /// the author wrote ([`Self::build_restricted_production_paren_doc`]) — already knows it
    /// will, so it says so instead of looking for a shell that may not be there.
    pub(in crate::printer) fn shell_trailing_gap_start(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        frozen: Option<Span>,
        printer_owns_grouping: bool,
    ) -> u32 {
        let span_end = expr.span().end;
        let unfrozen = if matches!(expr.kind, ast::ExpressionKind::SequenceExpression(_))
            && (printer_owns_grouping
                || self
                    .collapsed_grouping_close(span_end, boundary_end)
                    .is_some())
        {
            shell_content_end(expr)
        } else {
            span_end
        };
        Self::element_claim_anchor(frozen, unfrozen)
    }

    fn build_shell_value_doc(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        tail: ShellTail,
        position_parens: bool,
        frozen: Option<Span>,
    ) -> DocId {
        let expr_end = self.shell_trailing_gap_start(expr, boundary_end, frozen, false);
        // The for-header's `[~In]` parens are applied HERE rather than by the caller,
        // because only the paths below know where they belong relative to the shell's
        // comment. They are tsv's parens, not the author's, so a comment written AFTER
        // the shell has to land outside them (`(a in b) /* c */`, not `(a in b /* c */)`)
        // — the same rule that keeps a synthesized paren from landing inside an owned
        // comment (`docs/comments.md`). The two paths that return early supply their own
        // pair: a sequence self-parenthesizes, and the keep-paren path RETAINS the shell,
        // which already parenthesizes the `in` — wrapping either would double it. A FROZEN
        // value takes the wrap in the same place, but asks the SLICE's question rather than
        // the node's ([`Printer::wrap_frozen_for_init_in`]) — a verbatim slice has no inner
        // positions to parenthesize a deeper `in` at — and skips it where the calling
        // POSITION already supplies a pair (`position_parens`, which is how
        // `for (let k = (a = b in c); ;)` keeps exactly one).
        let wrap_in = |doc: DocId| match (tail, frozen) {
            (ShellTail::ForClauseSeparator, Some(frozen)) => {
                self.wrap_frozen_for_init_in(expr, frozen, position_parens, doc)
            }
            (ShellTail::ForClauseSeparator, None) => self.wrap_for_init_in(expr, doc),
            (ShellTail::StatementTerminator, _) => doc,
        };

        // A shell that closes the enclosing statement's value hands its trailing region —
        // its own gap and a commented region inside the value that ends with it — to the
        // statement's terminator gap ([`Printer::with_statement_tail`]), which prints it past
        // the `;` in source order. Never a frozen value (its slice prints the region) nor a
        // sequence (its own pair stands in for the shell); a pair the shell keeps holds it.
        if tail == ShellTail::StatementTerminator
            && frozen.is_none()
            && self.statement_tail_may_take(boundary_end)
            && let Some(doc) =
                self.build_handed_shell_value_doc(expr, expr_end, boundary_end, position_parens)
        {
            return doc;
        }

        if !self.has_trailing_paren_comments(expr_end, boundary_end) {
            return wrap_in(self.build_shell_inner_doc(expr, frozen));
        }

        // Every position this serves — variable init, assignment RHS, ternary branch, a
        // `for` clause and its last operand — is prettier's default layout arm; the two
        // that hang (a `return`/`throw` argument, an arrow body) claim their sequence
        // before reaching here.
        if let ast::ExpressionKind::SequenceExpression(seq) = &expr.kind {
            // A FROZEN sequence prints verbatim, so the operand-per-line layout the
            // sequence builder chooses is not available to it — its required pair takes
            // the retained-shell rendering below instead, which is where this gap's
            // comment goes on either path.
            return match frozen {
                Some(frozen) => self.build_frozen_kept_paren_doc(frozen, boundary_end),
                // A comment that forces the pair OPEN cannot ride the sequence's own
                // `Aligned` pair at a CLAUSE separator: that layout has no line left before
                // its `)`, so a `//` takes the `line_suffix` out past the clause's `;` and
                // leaves the construct it was written in — and the next pass, reading it
                // from the header's clause gap, prints it somewhere else again. The pair is
                // the EXPANDED shell instead, with the sequence riding it BARE, since that
                // shell IS the required pair (the same one-shell-for-both-gaps layering the
                // ASI-sensitive operands take, [`Self::build_asi_operand_shell_doc`]). A
                // statement position keeps the `Aligned` pair: there the `;` is a terminator
                // and the comment deferring past it is prettier's answer and tsv's own.
                None if tail == ShellTail::ForClauseSeparator
                    && self.shell_gap_holds_unplaceable_comment(expr_end, boundary_end) =>
                {
                    let inner = self.build_sequence_doc_bare(seq, expr.span, expr_end);
                    self.build_kept_paren_shell_doc(inner, expr_end, boundary_end)
                        .unwrap_or_else(|| self.d().parens(inner))
                }
                None => self.build_shell_sequence_doc(
                    seq,
                    expr.span,
                    expr_end,
                    boundary_end,
                    SeqLayout::Aligned,
                ),
            };
        }

        // A FROZEN value inside a pair the trailing gap RETAINS (the two reasons are the
        // tail builder's, [`Self::build_stripped_shell_tail_doc_with`]) prints as its slice
        // inside that pair; the unfrozen twin of the same question is the tail builder's own
        // first arm.
        if let Some(frozen) = frozen
            && self.shell_gap_retains_parens(expr_end, boundary_end, position_parens)
        {
            return self.build_frozen_kept_paren_doc(frozen, boundary_end);
        }
        self.build_stripped_shell_tail_doc_with(
            expr,
            expr_end,
            boundary_end,
            tail,
            position_parens,
            || wrap_in(self.build_shell_inner_doc(expr, frozen)),
        )
    }

    /// A value shell's value built under the statement-tail claim its region hands over
    /// ([`Self::build_shell_value_doc`]) — out of line, since almost no shell takes it.
    ///
    /// `None` when the shell keeps its region after all: a sequence (its own pair stands in
    /// for the shell), a retained shell, or a region that is not a run of same-line blocks.
    #[cold]
    #[inline(never)]
    fn build_handed_shell_value_doc(
        &self,
        expr: &ast::Expression<'_>,
        expr_end: u32,
        boundary_end: u32,
        position_parens: bool,
    ) -> Option<DocId> {
        if matches!(expr.kind, ast::ExpressionKind::SequenceExpression(_)) {
            return None;
        }
        let retains = self.shell_gap_retains_parens(expr_end, boundary_end, position_parens);
        let region = self.shell_statement_tail_region(expr, boundary_end, retains)?;
        Some(self.with_statement_tail_claim(region, || self.build_expression_doc(expr)))
    }

    /// The trailing half of [`Self::build_shell_value_doc`] for a value whose doc the
    /// CALLER builds: a chained conditional in a ternary ALTERNATE (`: (aaa ? bbb : ccc /* t */)`),
    /// whose branch arm builds the nested conditional in its chained geometry and so cannot
    /// hand the whole value to the shell builder. `expr_end` is where the value's own
    /// printed content ends, `boundary_end` where the stripped shell closes; the caller's
    /// position supplies no pair of its own. The tail policy is the position's
    /// ([`Self::shell_tail`]), read here so the caller cannot name it wrong.
    pub(in crate::printer) fn build_stripped_shell_tail_doc(
        &self,
        expr: &ast::Expression<'_>,
        expr_end: u32,
        boundary_end: u32,
        inner: impl FnOnce() -> DocId,
    ) -> DocId {
        let tail = self.shell_tail(boundary_end);
        // The statement-tail hand-over [`Self::build_shell_value_doc`] makes, for this
        // caller-built value.
        if tail == ShellTail::StatementTerminator
            && self.statement_tail_may_take(boundary_end)
            && let Some(region) = self.shell_statement_tail_region(
                expr,
                boundary_end,
                self.shell_gap_retains_parens(expr_end, boundary_end, false),
            )
        {
            return self.with_statement_tail_claim(region, inner);
        }
        self.build_stripped_shell_tail_doc_with(expr, expr_end, boundary_end, tail, false, inner)
    }

    /// A stripped value shell's TRAILING gap — `expr_end` (the value's printed end) to
    /// `boundary_end` (the shell's close) — laid out around the value's doc, which `inner`
    /// builds on demand. One spelling for [`Self::build_shell_value_doc`] and the
    /// caller-built values ([`Self::build_stripped_shell_tail_doc`]): the drop the
    /// ternary's nested-alternate arm carried was exactly a value this builder never saw.
    ///
    /// Two reasons the shell is RETAINED rather than stripped, and either sends the
    /// comment inside the pair:
    ///
    /// - a line / own-line comment needs the parens on its own account (a bare line
    ///   comment would swallow the following `;`);
    /// - the calling POSITION parenthesizes this value anyway (`const x = (a = b)`),
    ///   so the pair is in the output whatever this builder does.
    ///
    /// The second is what stops the deferral below from marching a comment across a
    /// `)` the output still prints. That arm's licence is "this output erases the
    /// `)`" — true for a plain value (`const a = (x /* t */);` → `const a = x; /* t */`),
    /// false here, and a licence stops where its argument stops: the block comment of
    /// a parenthesized assignment was relocating out of a surviving pair
    /// (`const k = (x = y /* c */);` → `const k = (x = y); /* c */`) while the same
    /// construct one comma over — a non-last declarator, with no terminator to defer
    /// past — already kept it inside, and prettier keeps it inside in both. A retained pair
    /// prints the value afresh through the keep-paren builder — inside the author's pair a
    /// chained conditional is a root one, so `inner`'s chained geometry is not wanted there.
    fn build_stripped_shell_tail_doc_with(
        &self,
        expr: &ast::Expression<'_>,
        expr_end: u32,
        boundary_end: u32,
        tail: ShellTail,
        position_parens: bool,
        inner: impl FnOnce() -> DocId,
    ) -> DocId {
        if !self.has_trailing_paren_comments(expr_end, boundary_end) {
            return inner();
        }
        if self.shell_gap_retains_parens(expr_end, boundary_end, position_parens) {
            return self.build_expression_doc_keep_paren_comments(
                expr,
                boundary_end,
                SeqLayout::Aligned,
            );
        }

        let d = self.d();
        let inner = inner();

        // Every comment left here is a same-line block. Where the shell is the last
        // thing before a statement `;`, that block defers past the terminator — the same
        // answer the statement's own value-to-`;` gap gives once the shell is gone
        // ([`Printer::push_semicolon_with_gap_comments`] and its terminator sibling), which is
        // what makes one pass enough. Keying the choice on the stripped `)` instead cannot
        // reach a fixed point: this output erases that `)`, so the next pass reads the
        // comment as statement-trailing and moves it (`(x /* t */);` → `x /* t */;` →
        // `x; /* t */`). A shell that is NOT terminator-adjacent — a ternary CONSEQUENT
        // (whose gap ends at the `:`), an object value, a non-last declarator, a nested
        // assignment — keeps the block inline, where it is already its own fixed point.
        // A ternary ALTERNATE is terminator-adjacent and does reach this arm, which is
        // prettier's answer there too; the pair its branch may print is applied outside,
        // by `parenthesize_ternary_branch`, so nothing here crosses a surviving `)`.
        // A shell that closes the value of an expression statement or a declaration's last
        // declarator hands its region to that statement's terminator gap instead, whenever
        // the region is a run of same-line blocks ([`Self::shell_statement_tail_region`]) —
        // for its ASI spelling too, and in order with a comment written after it. This arm
        // answers the rest: the positions with no statement tail (a class field, a `return`
        // / `throw` / `export default` value) and a region that also holds a `//` or an
        // own-line comment below the value.
        if tail == ShellTail::StatementTerminator
            && self.shell_meets_statement_terminator(boundary_end)
        {
            let mut parts: DocBuf = smallvec![inner];
            for comment in self.comments_to_emit_between(expr_end, boundary_end) {
                let suffix = d.concat(&[d.text(" "), self.build_comment_doc(comment)]);
                parts.push(d.line_suffix(suffix));
            }
            return d.concat(&parts);
        }

        let comments = self.build_comments_between(expr_end, boundary_end, CommentSpacing::Leading);
        d.concat(&[inner, comments])
    }

    /// True when the next significant byte at or after `boundary_end` — the end of a
    /// stripped grouping shell — is the statement's `;`.
    ///
    /// The question a deferred trailing block must ask: is this gap the statement's
    /// terminator gap? Asking it of the SOURCE (not of the stripped `)`, which the
    /// output deletes) is what makes the answer survive the strip, so pass 2 — which
    /// sees the same `;` and no shell — agrees.
    fn shell_meets_statement_terminator(&self, boundary_end: u32) -> bool {
        let bytes = self.source.as_bytes();
        self.next_significant_byte(boundary_end, bytes.len() as u32)
            .is_some_and(|pos| bytes[pos] == b';')
    }

    /// The comments between an expression's end and a following `)`, as ready-to-append
    /// separator+comment parts, plus whether they force the broken `(⏎\texpr // c⏎)` frame.
    ///
    /// **A printer that synthesizes its own `(`…`)` owns this gap** — no enclosing emitter
    /// can see between those parens, so a comment left unclaimed here is DROPPED, not
    /// relocated. Both such printers call this: the stripped-paren restorer below and
    /// `build_comment_bound_pair_doc`, which lacked the gap entirely
    /// (`parenthesized/jsdoc_cast_trailing_paren_comment`).
    ///
    /// The separator is newline-aware — a comment the author put on a new line relative to
    /// the *previous item* (the expression, or the prior comment) breaks; otherwise it
    /// trails inline. Tracking the previous item rather than `expr_end` keeps a same-line
    /// group together (`x⏎ /* a */ // b`) while stopping a line comment that follows
    /// another comment from being swallowed by it. In the inline case every comment is a
    /// same-line block comment, so the rule collapses to a plain space.
    ///
    /// Returns `None` when the gap is empty, so callers keep their no-comment fast path.
    pub(crate) fn trailing_paren_comment_parts(
        &self,
        expr_end: u32,
        boundary_end: u32,
    ) -> Option<(DocBuf, bool)> {
        if !self.has_trailing_paren_comments(expr_end, boundary_end) {
            return None;
        }
        let d = self.d();

        // A line comment runs to end-of-line, an own-line block comment was authored on
        // its own line, and a multi-line block spans lines of its own — in every case the
        // shell already occupies more than one line, and a shell that breaks expands
        // rather than gluing its content to the `(` (the same rule
        // `build_expanded_parenthesized_union_opt` states for a breaking paren). Without
        // the `multiline` term the two authorings of one comment disagreed: `(⏎\tx // c⏎)`
        // expanded while `(x /* m1⏎m2 */)` stayed glued, at the same gap and for the same
        // reason.
        let needs_break = self
            .comments_to_emit_between(expr_end, boundary_end)
            .any(|c| {
                !c.is_block || c.multiline || self.has_newline_between(expr_end, c.span.start)
            });

        let mut parts = DocBuf::new();
        let mut prev_end = expr_end;
        for comment in self.comments_to_emit_between(expr_end, boundary_end) {
            if self.has_newline_between(prev_end, comment.span.start) {
                parts.push(d.hardline());
            } else {
                parts.push(d.text(" "));
            }
            parts.push(self.build_comment_doc(comment));
            prev_end = comment.span.end;
        }
        Some((parts, needs_break))
    }

    /// Build expression doc re-adding the stripped grouping parens around trailing
    /// comments, producing `(expr /* c */)` or `(\n\texpr // c\n)`.
    ///
    /// Used where stripping the parens would relocate the comment — arrow bodies
    /// (prettier moves the comment into the params) and other non-sequence operands
    /// with an own-line/line trailing comment. Keeping the parens preserves the
    /// comment where the user wrote it. (Sequence operands take the dedicated
    /// `build_sequence_doc_value` path, which keeps the comment inside the sequence's
    /// own parens instead of adding a second pair.)
    pub(in crate::printer) fn build_expression_doc_keep_paren_comments(
        &self,
        expr: &ast::Expression<'_>,
        boundary_end: u32,
        layout: SeqLayout,
    ) -> DocId {
        let expr_end = expr.span().end;

        // A sequence self-parenthesizes, so it takes the shared arm rather than the
        // paren-restoring path below — `build_expression_doc` would emit its parens and
        // this method would re-wrap them (`() => ((1, 2, 3) /* c */)`). `layout` is the
        // caller's: an arrow body hangs its operands, the ASI-shell operands align.
        if let ast::ExpressionKind::SequenceExpression(seq) = &expr.kind {
            return self.build_shell_sequence_doc(seq, expr.span, expr_end, boundary_end, layout);
        }

        let inner = self.build_expression_doc(expr);
        self.build_kept_paren_shell_doc(inner, expr_end, boundary_end)
            .unwrap_or(inner)
    }

    /// The RETAINED shell's rendering: the value inside the pair the author wrote, with
    /// the operand→`)` run behind it — inline where the run is a same-line block, on the
    /// operand's own indented line where a `//` or an own-line comment forces the pair
    /// open ([`Self::trailing_paren_comment_parts`] decides which).
    ///
    /// `inner` is whatever renders the value at this position, so the ordinary expression
    /// doc and a frozen verbatim slice share one rendering rather than two. `None` says
    /// the gap holds nothing to emit, leaving the caller its own bare form.
    fn build_kept_paren_shell_doc(
        &self,
        inner: DocId,
        expr_end: u32,
        boundary_end: u32,
    ) -> Option<DocId> {
        let d = self.d();
        let (comment_parts, needs_break) =
            self.trailing_paren_comment_parts(expr_end, boundary_end)?;

        Some(if needs_break {
            let mut indent_parts: DocBuf = smallvec![d.hardline(), inner];
            indent_parts.extend(comment_parts);
            d.concat(&[
                d.text("("),
                d.indent(d.concat(&indent_parts)),
                d.hardline(),
                d.text(")"),
            ])
        } else {
            let mut parts: DocBuf = smallvec![d.text("("), inner];
            parts.extend(comment_parts);
            parts.push(d.text(")"));
            d.concat(&parts)
        })
    }

    /// [`Self::build_kept_paren_shell_doc`] over a FROZEN value's verbatim slice — the
    /// retained arm of [`Self::build_shell_value_doc`] and the frozen sequence's own
    /// required pair, which is the same emission.
    ///
    /// The pair is unconditional here, unlike the unfrozen twin's bare fallback: every
    /// path that reaches this one prints a `)` in the output (the position's clarity pair,
    /// or the sequence's required one), so a gap that turns out to hold nothing to emit
    /// still owes the parens.
    ///
    /// The **arrow body** asks it directly rather than through [`Self::build_shell_value_doc`]:
    /// its retained-paren arm reassembles the body itself
    /// ([`Printer::build_arrow_expression_body`]), and answering that gap with a bare
    /// `parens()` would leave it with no emitter and DROP the comment inside it
    /// (`docs/comments.md` hazard 4). One emitter, so the frozen and unfrozen forms of every
    /// retained shell keep agreeing about where the comment renders.
    pub(crate) fn build_frozen_kept_paren_doc(&self, frozen: Span, boundary_end: u32) -> DocId {
        let inner = self.build_frozen_node_doc(frozen);
        self.build_kept_paren_shell_doc(inner, frozen.end, boundary_end)
            .unwrap_or_else(|| self.d().parens(inner))
    }

    /// Promote block comments that appear before an assignment operator to the LHS.
    ///
    /// In `a /* comment */ = b`, the comment is between `left.span().end` and `right.span().start`
    /// but positioned before the `=` in source. Prettier places such comments before the operator,
    /// so we promote them to the LHS doc.
    ///
    /// Returns the promoted comments doc (with leading space) and the new RHS comment start
    /// position, or None if no comments need promoting.
    ///
    /// **Block comments only** — the ones that can sit inline before the operator. A
    /// comment that cannot (a `//`, or a multiline block the author broke after)
    /// stays put and takes the operator's tail with it onto a continuation line;
    /// that gap is answered by [`Printer::build_operator_value_continuation`], which
    /// the caller consults first. Emitting such a comment here would swallow the
    /// operator into it; leaving it to the RHS emitter would relocate it *past* the
    /// operator.
    ///
    /// `op_pos` is the operator's offset, found once by the caller
    /// ([`Printer::find_operator_in_source`]) and shared with that gate.
    pub(crate) fn promote_comments_before_operator(
        &self,
        start: u32,
        op_pos: u32,
    ) -> Option<(DocId, u32)> {
        let d = self.d();
        // Collect block comments that appear before the operator
        let mut promoted_parts = DocBuf::new();
        let mut last_promoted_end = start;
        for comment in self.comments_to_emit_between(start, op_pos) {
            if comment.is_block {
                promoted_parts.push(d.text(" "));
                promoted_parts.push(self.build_comment_doc(comment));
                last_promoted_end = comment.span.end;
            }
        }

        if promoted_parts.is_empty() {
            None
        } else {
            Some((d.concat(&promoted_parts), last_promoted_end))
        }
    }

    /// Find the position of an operator string between two positions, skipping
    /// whitespace and comments in the source.
    ///
    /// The multi-byte sibling of [`Printer::find_equals_position`] (a bare `=`, with a
    /// midpoint fallback rather than `None`); both step over comments through
    /// [`tsv_lang::source_scan::skip_comment`], so a `//` or `/* */` in the gap can
    /// never hide the operator behind its text.
    pub(crate) fn find_operator_in_source(
        &self,
        start: u32,
        end: u32,
        operator: &str,
    ) -> Option<u32> {
        let bytes = self.source.as_bytes();
        let op_bytes = operator.as_bytes();
        let op_len = op_bytes.len();
        let end_usize = end as usize;
        let mut i = start as usize;

        while i + op_len <= end_usize {
            if let Some(past_comment) = tsv_lang::source_scan::skip_comment(bytes, i, end_usize) {
                i = past_comment;
                continue;
            }
            if &bytes[i..i + op_len] == op_bytes {
                return Some(i as u32);
            }
            i += 1;
        }
        None
    }

    /// Prepend comments from removed parentheses to a doc.
    ///
    /// When parentheses are removed during parsing (e.g., `(/* comment */ expr)` becomes `expr`),
    /// the expression's span extends to include the removed parens. Comments between
    /// `outer_start` (the paren) and `inner_start` (the expression) need to be preserved.
    ///
    /// Returns the original doc unchanged if no comments or if `outer_start >= inner_start`.
    ///
    /// `node` is the span of the expression whose hoist site this is — the key an armed
    /// left-spine claim names its claimer by ([`Self::removed_paren_comments_opt`]).
    #[inline]
    pub(crate) fn prepend_removed_paren_comments(
        &self,
        node: Span,
        outer_start: u32,
        inner_start: u32,
        doc: DocId,
    ) -> DocId {
        self.prepend_opt(
            self.removed_paren_comments_opt(node, outer_start, inner_start),
            doc,
        )
    }

    /// The run [`Self::prepend_removed_paren_comments`] prepends, on its own — for a
    /// caller that must place it around a doc it has not finished building (the root
    /// conditional, whose run goes OUTSIDE the group it wraps its test in: `docs/comments.md`
    /// §The left-spine shell run). `None` when the gap is empty or inverted, so the two
    /// spellings of the guard cannot drift.
    ///
    /// Under an armed left-spine claim ([`Printer::claimed_left_spine_run`]) the claimer's
    /// site — `node` is its span — prints the claim's whole region, and any other site
    /// prints only the part of its gap past the region, which the claimer already took.
    pub(crate) fn removed_paren_comments_opt(
        &self,
        node: Span,
        outer_start: u32,
        inner_start: u32,
    ) -> Option<DocId> {
        let mut outer_start = outer_start;
        if let Some(claim) = self.claimed_left_spine_run.get() {
            if claim.claimer == node {
                return self
                    .build_rhs_comments_opt(claim.region.start, claim.region.end.max(inner_start));
            }
            if claim.region.start <= outer_start && outer_start < claim.region.end {
                outer_start = claim.region.end;
            }
        }
        (outer_start < inner_start)
            .then(|| self.build_rhs_comments_opt(outer_start, inner_start))
            .flatten()
    }

    /// The retained-shell form for a **statement value** whose authored grouping parens
    /// hold a `//` — `export default (⏎\tx // c⏎)`, `export = (⏎\tx // c⏎)`.
    ///
    /// These positions print no pair of their own around the value, so without this the
    /// comment falls to the statement's terminator gap and defers past the `)` and the
    /// `;`, onto a line that may already hold a `//` — where the two merge into one
    /// comment. Only a **line** comment needs the shell: a block trails without ending
    /// its line, so its relocation past the `;` is lossless and stable, and tsv matches
    /// prettier there.
    ///
    /// Returns the shell and the position just past the retained `)`, which is where the
    /// caller's terminator-gap scan resumes. `None` leaves the caller's plain path alone —
    /// no authored paren, or no `//` inside one.
    pub(crate) fn build_value_paren_line_comment_shell(
        &self,
        value_doc: DocId,
        value_end: u32,
        span_end: u32,
    ) -> Option<(DocId, u32)> {
        let close = self.value_paren_line_comment_close(value_end, span_end)?;
        let shell = self.build_paren_operand_comment_doc(value_end, close, value_doc, ")")?;
        Some((shell, Self::past_grouping_close(close, span_end)))
    }

    /// Where the shell above closes, when it applies — the value's authored grouping `)`
    /// with a `//` inside it. Split out for the caller that must know the close *before*
    /// it can build the value doc (`export =` builds its value inside a keyword-header
    /// closure), so the two answer one question rather than two.
    pub(crate) fn value_paren_line_comment_close(
        &self,
        value_end: u32,
        span_end: u32,
    ) -> Option<u32> {
        let close = self.retained_grouping_close(value_end, span_end)?;
        self.has_line_comments_between(value_end, close)
            .then_some(close)
    }

    /// Where a caller's terminator-gap scan resumes: just past the retained `)`.
    pub(crate) fn past_grouping_close(close: u32, span_end: u32) -> u32 {
        close.saturating_add(1).min(span_end)
    }

    /// The one emitter for a comment the author wrote between a **parenthesized**
    /// operand and the `)` that closes its shell — `(x + y /* c */)!`,
    /// `(a?.b // c⏎)!`, `<T>(x /* c */)`.
    ///
    /// tsv keeps such a comment INSIDE the parens, where it was written; prettier
    /// relocates it past the `)` (cataloged as the non-null grouped-operand and
    /// angle-bracket assertion-operand divergences). Four constructs reach this gap and
    /// must answer it identically: the standalone non-null whose operand needs its
    /// parens (`build_ts_non_null_doc`'s needs-parens arm), the chain's parenthesized
    /// base (`ChainNode::Base`'s `paren_comment_end`), the required-paren positions
    /// that never enter a chain — a `new` callee and a template tag
    /// (`build_sealed_non_null_paren_doc`) — and the angle-bracket type assertion,
    /// whose own span is what ends at the `)` (`build_ts_type_assertion_doc`, which
    /// calls from each of its two return paths).
    ///
    /// Returns `None` when the gap holds nothing to emit, leaving the caller to
    /// render its own bare parens — which is what makes the retention the comment's
    /// doing: an empty gap still strips a redundant shell.
    ///
    /// A line-spanning run takes the expanded layout — a `//` cannot trail inline before
    /// the `)` (it would swallow it), and a multi-line block already makes the shell
    /// span lines, where a shell that breaks expands rather than gluing its operand to
    /// the `(` (the rule [`Self::trailing_paren_comment_parts`] states for the same
    /// gap) — so the operand goes multiline with the comment inside; a single-line block
    /// run trails `operand` inline. `operand` is UNSHAPED: the expanded layout is a shell
    /// of its own, so a caller whose operand takes a paren-body shape where it folds asks
    /// [`Self::build_shaped_owned_required_pair_doc`] instead. `close` is what follows the
    /// operand: `")"` where a separate node prints the `!` (or where nothing does),
    /// `")!"` where this doc owns it.
    pub(crate) fn build_paren_operand_comment_doc(
        &self,
        start: u32,
        end: u32,
        operand: DocId,
        close: &'static str,
    ) -> Option<DocId> {
        let d = self.d();
        if self.has_line_spanning_comments_to_emit_between(start, end) {
            // Every comment in this gap was authored AFTER the operand — there is no
            // next node for one to lead — so the whole run trails, in authored order,
            // on the anchored emitter (the layout is vertical: the closer's hardline
            // below ends every line, and flushes the run's deferred `//`s; a boundary
            // instead would end the line first, landing a blank before the closer).
            // A block-only run holding a multi-line block takes the same emitter: it
            // trails inline on the operand's line, and the closer drops below it.
            // A chain-gap classification here is a category error: its `leading_*`
            // buckets would hoist an own-line comment above the operand.
            return Some(self.build_trailing_run_expanded_shell_doc(start, end, operand, close));
        }
        if self.has_comments_to_emit_between(start, end) {
            let trailing = self.build_chain_block_comments_doc(start, end, CommentSpacing::Leading);
            return Some(d.concat(&[d.text("("), operand, trailing, d.text(close)]));
        }
        None
    }

    /// [`Self::build_paren_operand_comment_doc`]'s line-spanning arm — the expanded shell
    /// with `operand` one indent in and the trailing run anchored behind it — for a caller
    /// that has already asked whether the gap holds a line-spanning run.
    fn build_trailing_run_expanded_shell_doc(
        &self,
        start: u32,
        end: u32,
        operand: DocId,
        close: &'static str,
    ) -> DocId {
        let mut body = DocBuf::with_capacity(3);
        body.push(operand);
        self.push_anchored_trailing_run(&mut body, start, end, RunLeadingBlank::Keep);
        self.compose_expanded_shell_doc(None, &body, close)
    }
}