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
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
// Function expression printing for TypeScript
//
// This module handles function-related expressions:
// - Arrow function expressions (async, parameters, return types, body)
// - Function expressions (parameters, return types, body)
//
// Note: Block statements are in blocks.rs as a reusable utility

use crate::ast;
use crate::printer::ArrowChainContext;
use crate::printer::AssumedBreak;
use crate::printer::LeadingGlue;
use crate::printer::ShareTag;
use crate::printer::class_common::ClassHeaderOptions;
use crate::printer::class_common::ClassTypeParamsGap;
use crate::printer::class_expr_has_decorators;
use crate::printer::expressions::assignment::{
    is_curried_arrow_chain, is_curried_arrow_chain_that_breaks,
};
use crate::printer::expressions::operators::SeqLayout;
use crate::printer::needs_parens::leftmost_no_lookahead;
use crate::printer::statements::function::FunctionHeadModifier;
use crate::printer::types::helpers::{is_huggable_type, type_literal_members_hold_brace_type};
use crate::printer::{
    CommentFilter, CommentSpacing, CommentVec, ParenContext, Printer,
    is_multiline_template_expression, unwrap_parenthesized,
};
use smallvec::{SmallVec, smallvec};
use tsv_lang::Span;
use tsv_lang::doc::after_operator::hang_after_operator;
use tsv_lang::doc::arena::{DocArena, DocId};
use tsv_lang::doc::{DocBuf, arena::GroupId};
use tsv_lang::source_scan::has_newline_before_position;

/// Whether an arrow body stays on the `=>` line for a reason that a forced chain break
/// cannot overrule — the two unconditional disjuncts of prettier's `shouldPutBodyOnSameLine`
/// (`print/arrow-function.js`):
///
/// - `shouldAlwaysAddParens` — a **sequence** body, which hugs "so that the required
///   parentheses end up on their own lines". Its parens are the sequence's own hanging
///   layout ([`SeqLayout::Hanging`]); breaking after the `=>` would put the `(` on the body's
///   line and lose that shape.
/// - `mayBreakAfterShortPrefix` — an **object**, **array** or nested **arrow** body (block
///   bodies are handled by their own arm), plus `isTemplateOnItsOwnLine`: a multiline
///   template hugs when its backtick shares the `=>`'s line and breaks when the author put it
///   on its own, which keeps both authorings stable.
///
/// ⚠️ **One rule, two printers.** The plain arrow body ([`Printer::build_arrow_expression_body`])
/// and the curried chain's ([`Printer::build_arrow_chain_doc`]) are twins over prettier's one
/// `shouldPutBodyOnSameLine`, and they have already drifted: the chain builder was missing
/// the sequence disjunct, so a chain broken by `arrow_chain_should_break` hung `(a, b)` on
/// the next line while its twin hugged it. Add a body kind here, not at a call site.
///
/// Read through [`Printer::arrow_body_hugs`], which subtracts the one body whose doc opens
/// with a hoisted run — a kind belongs here, the run exclusion there.
///
/// The third disjunct is deliberately NOT here: `shouldAddParensIfNotBreak` (a ternary body)
/// is the one prettier gates on `!shouldBreakChain`, and it renders differently besides —
/// parens in the flat form only ([`ternary_body_parens_group`]) — so each printer states it
/// as its own arm.
fn arrow_body_always_hugs(expr: &ast::Expression<'_>, source: &str) -> bool {
    matches!(
        expr.kind,
        ast::ExpressionKind::SequenceExpression(_)
            | ast::ExpressionKind::ObjectExpression(_)
            | ast::ExpressionKind::ArrayExpression(_)
            | ast::ExpressionKind::ArrowFunctionExpression(_)
    ) || (is_multiline_template_expression(expr)
        && !has_newline_before_position(source, expr.span().start))
}

/// Span of the node at an expression's leftmost (no-lookahead) position that an arrow
/// body must parenthesize, or `None` if the leftmost token needs no pair.
///
/// Two node kinds qualify, for one reason — a concise body cannot START with their first
/// token, so the pair goes around *just that node*:
///
/// - an **object literal**, whose `{` is ambiguous with a block body — `{} as T`,
///   `{}.prop`, `{} && a`, `{} ? a : b`, `{}.b++`;
/// - a **decorated class expression**, whose `@` is not a token `ConciseBody` admits —
///   `@dec class {}.k`, `@dec class {}()`, `@dec class {} ? a : b`, and the rest of the
///   same eight shapes. An *undecorated* `class {}` opens a concise body fine and stays
///   bare, as prettier keeps it.
///
/// Delegates to the shared `leftmost_no_lookahead` walk (prettier's
/// `startsWithNoLookaheadToken`, also used by the expression-statement paren path) and
/// keeps the result only when it is one of those two. Assignment and sequence *bodies* are
/// excluded — they get whole-body parens instead — matching prettier's
/// needs-parentheses.js arrow-body carve-out (which still recurses through *nested*
/// assignments/sequences, so the carve-out guards only the top-level body type).
///
/// Returns the node's span so the printer wraps exactly it (keyed by span, robust to a
/// chain rebuilding its base across conditional-group variants) and never a same-shaped
/// node nested deeper.
fn leftmost_arrow_body_parens_span(expr: &ast::Expression<'_>) -> Option<Span> {
    if matches!(
        expr.kind,
        ast::ExpressionKind::AssignmentExpression(_) | ast::ExpressionKind::SequenceExpression(_)
    ) {
        return None;
    }
    let leftmost = leftmost_no_lookahead(expr);
    match &leftmost.kind {
        ast::ExpressionKind::ObjectExpression(_) => Some(leftmost.span),
        ast::ExpressionKind::ClassExpression(c) if class_expr_has_decorators(c) => {
            Some(leftmost.span)
        }
        _ => None,
    }
}

/// Join a curried chain's head signatures with ` =>` and each gap's own tail — a bare
/// `line`, or that gap's `=>`-glued comment run plus the break it forces
/// ([`Printer::push_arrow_gap_glued_head`]).
///
/// A per-gap separator rather than one shared `join_doc`: the `=>` a glued run belongs to
/// lives in the separator here, so the run cannot ride the following signature the way it
/// does at every other arrow gap.
///
/// `tails[i]` sits between `sigs[i]` and `sigs[i + 1]`; a short slice falls back to a plain
/// `line`, which is what the uncommented chain has always emitted.
fn join_arrow_chain_heads(d: &DocArena, sigs: &[DocId], tails: &[DocId]) -> DocId {
    let mut parts = DocBuf::with_capacity(sigs.len().saturating_mul(3).saturating_sub(2));
    for (i, &sig) in sigs.iter().enumerate() {
        if i > 0 {
            parts.push(d.text(" =>"));
            parts.push(tails.get(i - 1).copied().unwrap_or_else(|| d.line()));
        }
        parts.push(sig);
    }
    d.concat(&parts)
}

/// What [`Printer::push_arrow_gap_glued_head`] emitted onto the `=>` line, and what its
/// caller still owes below. Its existence IS the "something was glued" answer — the
/// emitter returns `None` when it pushed nothing, so there is no state in which a caller
/// can read a resume position that never moved.
struct ArrowGapGluedHead {
    /// Where the remaining, own-line run resumes — past the `//` that ended the `=>` line.
    resume: u32,
    /// An author blank between that `//` and what follows it, which only this seam can
    /// emit.
    blank_below: bool,
}

/// Prepend an optional leading comment run to a doc, allocating nothing when there is none.
///
/// One spelling for every consumer of an [`Printer::arrow_gap_leading_run`]-shaped
/// `Option`: [`Printer::build_arrow_body_doc_with_leading`] (which decides which side of the
/// body's parens the run belongs on), the arm that emits its paren tokens itself, the
/// block-body own-line arm, and the chain's inter-head gap. The no-run case must stay
/// node-free: this sits on the arrow-body hot path.
#[inline]
pub(in crate::printer) fn prepend_leading(
    d: &DocArena,
    leading: Option<DocId>,
    doc: DocId,
) -> DocId {
    match leading {
        Some(run) => d.concat(&[run, doc]),
        None => doc,
    }
}

/// Prettier's `shouldAddParensIfNotBreak` for a ternary arrow body: the parens exist only in
/// the FLAT rendering and are dropped the moment the group breaks, the body hanging on its own
/// line instead.
///
/// Both terminal-body printers build exactly this — the plain arrow body
/// ([`Printer::build_arrow_expression_body`]) and the curried chain's
/// ([`Printer::build_arrow_chain_doc`]). Only their `will_break` fallback differs
/// (`hang_after_operator` vs `indent_line`), so that stays at each site; the leading `" "` is
/// each caller's too, since one pushes into a buffer and the other returns a concat.
///
/// ⚠️ The third ternary-paren site is **not** this shape and must not be folded in:
/// [`Printer::build_arrow_body_doc_with_leading`] uses a bare `if_break(body, parens(body))`
/// with no group, indent or softline, because its callers have already forced a break. It reads
/// like the same rule and would change layout.
fn ternary_body_parens_group(d: &DocArena, body: DocId) -> DocId {
    d.group(d.concat(&[
        d.if_break(d.empty(), d.text("(")),
        d.indent(d.concat(&[d.softline(), body])),
        d.if_break(d.empty(), d.text(")")),
    ]))
}

/// [`ternary_body_parens_group`] with the space after `=>` inside its flat half (` (`): the
/// plain arrow body's form when a comment run the author broke after leads the body, whose
/// broken layout puts nothing past `=>` on its line (prettier's own-line arm). Measured from
/// the signature, the group in break mode then adds no column past `=>`.
fn ternary_body_parens_group_spaced(d: &DocArena, body: DocId) -> DocId {
    d.group(d.concat(&[
        d.if_break(d.empty(), d.text(" (")),
        d.indent(d.concat(&[d.softline(), body])),
        d.if_break(d.empty(), d.text(")")),
    ]))
}

/// Walk a curried arrow chain's heads from `head` inwards, calling `visit` with each head
/// and the **previous** head's `=>` end (`None` at the chain's own head, whose leading gap
/// belongs to the enclosing site), and returning the terminal non-arrow body.
///
/// One walk, two consumers: [`Printer::build_arrow_chain_doc`] builds a signature per head,
/// and [`Printer::chain_comment_outside_emitted_regions`] collects the regions that builder
/// prints. The predicate's region list is an **assertion about the builder**, so the two
/// must visit the same heads and the same gaps — a copied traversal that stopped one head
/// short would leave a region unclaimed by either, which is a DROPPED comment.
fn walk_arrow_chain<'a, 'arena>(
    head: &'a ast::ArrowFunctionExpression<'arena>,
    head_span: Span,
    mut visit: impl FnMut(&'a ast::ArrowFunctionExpression<'arena>, Span, Option<u32>),
) -> &'a ast::ArrowFunctionBody<'arena> {
    let mut current = head;
    let mut current_span = head_span;
    let mut gap_start = None;
    loop {
        visit(current, current_span, gap_start);
        gap_start = Some(arrow_token_end(current));
        match &current.body {
            ast::ArrowFunctionBody::Expression(b) => match &b.kind {
                ast::ExpressionKind::ArrowFunctionExpression(inner) => {
                    current = inner;
                    current_span = b.span;
                }
                _ => break &current.body,
            },
            ast::ArrowFunctionBody::BlockStatement(_) => break &current.body,
        }
    }
}

/// Whether an expression's leftmost position holds a node an arrow body must
/// parenthesize. See [`leftmost_arrow_body_parens_span`].
pub(in crate::printer) fn has_leftmost_arrow_body_parens(expr: &ast::Expression<'_>) -> bool {
    leftmost_arrow_body_parens_span(expr).is_some()
}

/// Whether the node at an arrow body's leftmost position that takes a pair is the body
/// itself (a bare object, a bare decorated class) rather than a node inside it.
fn arrow_body_is_its_own_leftmost_pair(expr: &ast::Expression<'_>) -> bool {
    leftmost_arrow_body_parens_span(expr) == Some(expr.span())
}

/// Check if an expression is a huggable pattern for function parameters.
///
/// Prettier's `shouldHugTheOnlyFunctionParameter` hugs a single object/array pattern,
/// keeping `({` and `}: Type)` together while letting the pattern's content break.
///
/// A pattern with a default hugs only when the default is an identifier or an EMPTY
/// object/array — the three spellings whose default cannot itself take the width. A
/// non-empty literal or a call default makes the parameter list expand instead, the
/// pattern staying flat inside it (`destructuring_param_default_long`).
///
/// Shared with the signature-param path (`build_signature_params_doc`) so bodyless
/// declarations (declare / overload) and type-member signatures (method / call /
/// construct) hug the lone param exactly like value-param functions do.
fn is_huggable_pattern(expr: &ast::Expression<'_>) -> bool {
    match &expr.kind {
        ast::ExpressionKind::ObjectPattern(_) | ast::ExpressionKind::ArrayPattern(_) => true,
        ast::ExpressionKind::AssignmentPattern(ap) => {
            matches!(
                ap.left.kind,
                ast::ExpressionKind::ObjectPattern(_) | ast::ExpressionKind::ArrayPattern(_)
            ) && match &ap.right.kind {
                ast::ExpressionKind::Identifier(_) => true,
                ast::ExpressionKind::ObjectExpression(obj) => obj.properties.is_empty(),
                ast::ExpressionKind::ArrayExpression(arr) => arr.elements.is_empty(),
                _ => false,
            }
        }
        _ => false,
    }
}

/// The offset just past an arrow's `=>` — where the gap before its body opens.
///
/// One spelling of that bound. Its readers had two: `arrow.arrow_token` raw at the
/// expand-last-arg hug gate, `arrow_token + "=>".len()` everywhere else. The `=>` token's own
/// bytes can hold no comment, so both ranges held the same comments and the drift stayed
/// invisible — which is the argument for not carrying two of them, not for tolerating it.
pub(in crate::printer) fn arrow_token_end(arrow: &ast::ArrowFunctionExpression<'_>) -> u32 {
    arrow.arrow_token + "=>".len() as u32
}

/// The start an arrow shares with its lone **unparenthesized** parameter — the one shape
/// where a node and its child begin at the same byte while the parent still prints ahead of
/// it (the `(` the printer synthesizes around that parameter).
///
/// `None` for every other arrow, the async paren-less one included (`async /* c */ x => x`):
/// its span starts at `async`, so the two positions differ and the comment is never the
/// arrow's to begin with — [`Printer::push_async_arrow_head`] prints it positionally.
///
/// Read only by [`Printer::build_arrow_params_doc_ungrouped`], to suppress the parameter's
/// duplicate owned-comment claim; see the ⚠️ there.
fn bare_param_sharing_arrow_start(
    arrow: &ast::ArrowFunctionExpression<'_>,
    span: Span,
) -> Option<u32> {
    if arrow.params_start.is_some() {
        return None;
    }
    let start = arrow.params.first()?.span().start;
    (start == span.start).then_some(start)
}

/// Whether `arrow`'s signature — its params' `(` through its `=>` — holds a comment that
/// **forces** a break.
///
/// The expand-last-arg hug renders that signature on one line, which such a comment makes
/// impossible: the break is forced out mid-hug (`map(([/* a⏎b */ x, y]) => …`) instead of
/// breaking the call, which is neither layout anyone asked for.
///
/// Prettier reaches the same conclusion by another route: the hug state's hard line
/// propagates a break to its enclosing `conditionalGroup`, whose printer then jumps
/// straight to the most-expanded state (`call-arguments.js`, `printer.js`'s `doc.break`
/// arm). tsv has no break-propagation pass — `should_break` is only ever set explicitly —
/// so the question is asked here instead, of the **source**, before either hug path builds
/// anything. Asking pre-build is also what keeps this off the exponential-rebuild rake: the
/// alternative, building the arrow and inspecting `will_break`, needs a second build of the
/// same subtree on the fall-through.
///
/// Both hug paths (`call_formatting.rs`'s plain call, `chain_args.rs`'s member chain) route
/// through this one predicate — the two disagreeing about when a hug is legal is exactly
/// how the mangle survived on `arr.map(…)` while `fn(…)` was fine.
///
/// A **glued single-line** block comment is deliberately absent:
/// `fn(([/* c */ x, y]) => [y, x])` hugs, in tsv and prettier alike, because it inlines
/// without forcing anything.
///
/// An **own-line** single-line block is not that case — it does force the signature open —
/// but it is asked for over the *trailing-parameter* region only, never over the whole
/// signature, and the reason is idempotence rather than taste: breaking a parameter list is
/// itself what puts a comment glued to `(` or to a comma at a line start, so a signature-wide
/// own-line test answers differently on the output of the hug it just permitted. See
/// [`Printer::range_has_layout_stable_break_forcing_comment`] for the F1 failure that spells
/// this out, and [`Printer::arrow_trailing_param_comment_forces_break`] for the region where
/// the question *is* stable. The two disjuncts below are exactly that split.
pub(in crate::printer) fn arrow_signature_has_breaking_comments(
    printer: &Printer<'_>,
    arrow: &ast::ArrowFunctionExpression<'_>,
    span: Span,
) -> bool {
    // `arrow_token` is the `=>`, captured by the parser for exactly this kind of question.
    //
    // **An EMPTY parameter list refuses nothing that `printFunctionParameters` owns.** Its
    // `parameters.length === 0` arm returns the `(…)` doc *before* the bailout throw, so
    // neither a broken type-parameter list nor a dangling `()` comment can defeat the hug
    // (`fn(x, <⏎// c⏎T>() => {…})` and `fn(x, ( // c⏎): T => {…})` both stay hugged). What
    // survives an empty list is the return type, because `printArrowFunctionSignature` asks
    // `willBreak(returnTypeDoc)` itself, outside that early return — so the region shrinks
    // to what follows `)`.
    //
    // With parameters present the region opens at the **type parameters**, not at the `(`:
    // the bailout is `willBreak(typeParametersDoc) || willBreak(printed)`, one question over
    // both, so a break forced inside `<…>` refuses the hug exactly as one inside the
    // parameter list does — and the `>`→`(` gap between them belongs to the same region.
    // Starting at the `(` asked only the second half, which hugged
    // `fn(x, <⏎// c⏎T>(a: T) => {…})` onto the callee's line in every spelling.
    // An unparenthesized `x => …` has no `(` either, so the region then opens at the arrow
    // node itself — which still catches `x /* a⏎b */ => y`.
    let signature_start = arrow.type_parameters.as_ref().map_or_else(
        || arrow.params_start.unwrap_or(span.start),
        |type_params| type_params.span.start,
    );
    // Zero-comment gate: both disjuncts below read comments inside `[signature_start, body)`,
    // so with no comment on page there neither can fire, and the `)` scans that locate their
    // regions are skipped. The signature region `[start, arrow_token)` opens at or after
    // `signature_start` — at it with parameters, and past the `(` (itself at or after the type
    // parameters) without, since only a parenthesized list can be empty — and ends at the `=>`,
    // before the body; the trailing-parameter region `[last parameter's end, params end)` sits
    // inside the list, its end found by a scan bounded by the body's start. A comment yielded
    // by either walk lies inside the window, and the window's walk meets it or an earlier one;
    // the trailing walk is to-emit, a subset of on-page, which counts an owned comment too.
    if !printer.has_comments_on_page_between(signature_start, arrow.body.span().start) {
        return false;
    }
    let start = if arrow.params.is_empty() {
        arrow
            .params_start
            .and_then(|open| printer.find_closing_paren(open, arrow.arrow_token))
            .unwrap_or(arrow.arrow_token)
    } else {
        signature_start
    };
    printer.range_has_layout_stable_break_forcing_comment(start, arrow.arrow_token)
        || printer.arrow_trailing_param_comment_forces_break(arrow)
}

/// [`arrow_signature_has_breaking_comments`] for a `function` expression — the same refusal,
/// over a **strictly smaller region**, because `printFunction` reaches the bailout by only
/// one of the arrow's three routes.
///
/// The **expand-last-argument hug asks one question regardless of the callback's kind.** Its
/// arrow twin was gated at every hug state and this had no gate at all, so a `function`
/// callback whose signature is forced to break kept a hug the arrow refuses
/// (`fn(x, function (y // c⏎) { … })`).
///
/// But the region is the **parameter list only**, and its two exclusions are the oracle's,
/// not an omission:
///
/// - **Type parameters are out.** `printFunction` prints them itself
///   (`print("typeParameters")`, beside the group) and passes no `shouldPrintTypeParameters`,
///   so `typeParametersDoc` is `""` where the throw reads it — `fn(x, function <⏎// c⏎T>(a: T)
///   {…})` keeps the hug where its arrow spelling loses it.
/// - **The return type is out.** The `willBreak(returnTypeDoc)` throw lives in
///   `printArrowFunctionSignature`; `printFunction` has no counterpart, so it hugs
///   `fn(x, function (p): // c⏎T {…})`. The region therefore stops at the return type's `:`
///   — but not before it, since a comment in the `)`→`:` gap attaches to the **last
///   parameter** and so does break `printed`.
/// - And as for the arrow, an **empty** parameter list takes the
///   `parameters.length === 0` early return, ahead of the throw, so nothing in it refuses.
pub(in crate::printer) fn function_signature_has_breaking_comments(
    printer: &Printer<'_>,
    func: &ast::FunctionExpression<'_>,
) -> bool {
    // Zero-comment gate, as for the arrow: both regions below lie inside
    // `[params_start, body)` — the parameter-list region ends at or before the body (at the
    // return type or the body itself), and the trailing-parameter region runs from the last
    // parameter's end to a `)` found by a scan bounded by the body's start — so with no
    // comment on page there neither fires, and the `)` scan is skipped.
    if !printer.has_comments_on_page_between(func.params_start, func.body.span.start) {
        return false;
    }
    let end = if func.params.is_empty() {
        func.params_start
    } else {
        func.return_type
            .as_ref()
            .map_or(func.body.span.start, |return_type| return_type.span.start)
    };
    printer.range_has_layout_stable_break_forcing_comment(func.params_start, end)
        || printer.function_trailing_param_comment_forces_break(func)
}

/// Whether `arrow`'s signature **will break** as a hugged call argument — the doc half of
/// prettier's `ArgExpansionBailout`, beside the source half
/// [`arrow_signature_has_breaking_comments`].
///
/// Under `expandLastArg` / `expandFirstArg` prettier throws the bailout when
/// `willBreak(returnTypeDoc)` (`printArrowFunctionSignature`) or, with parameters present,
/// `willBreak(typeParametersDoc) || willBreak(printed)` (`printFunctionParameters`), and the
/// call breaks every argument out. A break forced inside the signature — an object or object
/// type the author expanded, a blank line between parameters, a matrix array, a member chain
/// the chain printer breaks — is the same fact as a break a comment forces there, and the
/// call answers it the same way: whatever forced it, the hug would render the signature's
/// head on the callee's line.
///
/// Asked of the signature's own docs, built here — parameters and return type, never the
/// body, so asking costs a signature and not the subtree. No source scan can stand in for
/// the build: the doc layer forces breaks from source that holds no newline at all
/// (`[[1, 2], [3, 4]]`, `x.a(() => 1).b(() => 2).c(() => 3)`). Each half the oracle gates is
/// gated here too: an **empty** parameter list takes `printFunctionParameters`'
/// `parameters.length === 0` return ahead of the throw, so only the return type is asked.
///
/// **One carve-out, tsv's:** a block-bodied arrow keeps the hug when the only break in its
/// hugged sole parameter is the author's expansion of that parameter's own top-level object
/// type ([`sole_param_object_type_start`]). Prettier prints that literal without
/// a group, so the expansion never reaches its bailout; tsv keeps the expansion, keeps the
/// hug for a block body, and breaks the call out for an expression body (see
/// `docs/conformance_prettier_ts.md` §Hugged sole-parameter object type). Any other break in
/// that parameter refuses as prettier's does, and so do the return type and the type
/// parameters.
fn arrow_signature_will_break(
    printer: &Printer<'_>,
    arrow: &ast::ArrowFunctionExpression<'_>,
    span: Span,
) -> bool {
    let d = printer.d();
    if let Some(return_type) = &arrow.return_type
        && d.will_break(printer.build_arrow_return_type_doc(return_type, arrow.params_start))
    {
        return true;
    }
    if arrow.params.is_empty() {
        return false;
    }
    if let Some(type_params) = &arrow.type_parameters
        && d.will_break(printer.build_type_parameter_declaration_doc_wrapping(type_params))
    {
        return true;
    }
    let window_start = arrow.params_start.unwrap_or(span.start);
    if params_cannot_force_break(printer, arrow.params, window_start, arrow.arrow_token) {
        return false;
    }
    let unforced = if arrow.body.is_expression() {
        None
    } else {
        sole_param_object_type_start(printer, arrow.params, arrow.params_start, || {
            printer.arrow_params_end(arrow)
        })
    };
    printer.ask_signature_params(unforced, || {
        d.will_break(printer.build_arrow_params_doc_ungrouped(arrow, span))
    })
}

/// Whether a parameter list's doc provably carries **no forced break**, answered from the
/// AST and two window reads instead of building the list — the fast path of the signature
/// questions ([`arrow_signature_will_break`], [`function_signature_refuses_hug`]), which only
/// ever ask a parameter list's `will_break`.
///
/// `true` when every parameter is flat ([`param_is_flat`]) and
/// `start..end` — the signature from its `(` (or a bare parameter) to the `=>` or the body,
/// so it covers every gap the list's emitters read — holds no line break and no comment on
/// page. A parameter list's doc gets a forced break from exactly these sources:
///
/// - a **comment**: a line comment, an own-line block, a format-ignore directive's frozen
///   slice — none on page in the window;
/// - a **source line break**: an author blank line between parameters, a line-continuation
///   or other newline-bearing literal text — none in the window. Asked of the comment
///   line-break table, which stays real in the canonical reprint, so the answer never rests
///   on a newline the layout table erased;
/// - a **parameter property**'s modifiers, or a **sub-doc that breaks on its own**: an
///   expanded object or object type, a matrix array, a nested pattern, a member chain, a
///   default value that is more than one token, a decorator's arguments — none of which a
///   flat parameter has.
///
/// Print width never forces a break, so a list too long for its line is still `false` here,
/// as `will_break` answers it.
fn params_cannot_force_break(
    printer: &Printer<'_>,
    params: &[ast::Expression<'_>],
    start: u32,
    end: u32,
) -> bool {
    params.iter().all(param_is_flat)
        && !printer.comment_has_newline_between(start, end)
        && !printer.has_comments_on_page_between(start, end)
}

/// A parameter whose doc holds no break of its own making — only text, the separators
/// between its pieces, and the soft lines of a type list — so that, with no comment and no
/// line break in its source, nothing in it is forced to break. Undecorated, and one of:
///
/// - an identifier, optional or not, with a flat annotation ([`annotation_is_flat`]) or none;
/// - a flat object pattern `{ a, b: c, ...d }` or array pattern `[a, , ...b]` — bare
///   identifier leaves only, no computed key, no nested pattern, no default — with a flat
///   annotation or none;
/// - a rest element `...a` over a bare identifier, with a flat annotation or none;
/// - a default `a = x` whose binding is such an identifier and whose value is a single
///   literal or identifier token.
fn param_is_flat(param: &ast::Expression<'_>) -> bool {
    match &param.kind {
        ast::ExpressionKind::Identifier(id) => {
            id.decorators().unwrap_or_default().is_empty()
                && annotation_is_flat(id.type_annotation())
        }
        ast::ExpressionKind::ObjectPattern(pattern) => {
            pattern.decorators.unwrap_or_default().is_empty()
                && annotation_is_flat(pattern.type_annotation.as_ref())
                && pattern.properties.iter().all(|property| match property {
                    ast::ObjectPatternProperty::Property(property) => {
                        !property.computed
                            && !property.method
                            && is_bare_identifier(property.key)
                            && is_bare_identifier(property.value)
                    }
                    ast::ObjectPatternProperty::RestElement(rest) => {
                        rest.type_annotation.is_none() && is_bare_identifier(rest.argument)
                    }
                })
        }
        ast::ExpressionKind::ArrayPattern(pattern) => {
            pattern.decorators.unwrap_or_default().is_empty()
                && annotation_is_flat(pattern.type_annotation.as_ref())
                && pattern.elements.iter().all(|element| {
                    element.as_ref().is_none_or(|element| match &element.kind {
                        ast::ExpressionKind::RestElement(rest) => {
                            rest.type_annotation.is_none() && is_bare_identifier(rest.argument)
                        }
                        _ => is_bare_identifier(element),
                    })
                })
        }
        ast::ExpressionKind::RestElement(rest) => {
            is_bare_identifier(rest.argument) && annotation_is_flat(rest.type_annotation.as_ref())
        }
        ast::ExpressionKind::AssignmentPattern(default) => {
            default.decorators.unwrap_or_default().is_empty()
                && matches!(
                    &default.left.kind,
                    ast::ExpressionKind::Identifier(id)
                        if id.decorators().unwrap_or_default().is_empty()
                            && annotation_is_flat(id.type_annotation())
                )
                && matches!(
                    default.right.kind,
                    ast::ExpressionKind::Literal(_) | ast::ExpressionKind::Identifier(_)
                )
        }
        _ => false,
    }
}

/// An identifier with no annotation and no decorator — a pattern's leaf.
fn is_bare_identifier(expr: &ast::Expression<'_>) -> bool {
    matches!(
        &expr.kind,
        ast::ExpressionKind::Identifier(id)
            if id.type_annotation().is_none() && id.decorators().unwrap_or_default().is_empty()
    )
}

/// An absent annotation, or one whose type is flat ([`type_is_flat`]), a top-level union or
/// intersection of flat members included.
fn annotation_is_flat(annotation: Option<&ast::TSTypeAnnotation<'_>>) -> bool {
    annotation.is_none_or(|annotation| match annotation.type_annotation {
        ast::TSType::Union(ast::TSUnionType { types, .. })
        | ast::TSType::Intersection(ast::TSIntersectionType { types, .. }) => {
            types.iter().all(|member| type_is_flat(member))
        }
        other => type_is_flat(other),
    })
}

/// A type printed as text and type lists only: a keyword type, the `this` type, a string /
/// number / bigint literal type, a type reference (qualified names included) whose type
/// arguments are flat, a flat element's array type, `keyof` / `unique` / `readonly` over a
/// flat type, a flat indexed access, or a `typeof` query without type arguments. Unions are
/// admitted only at the annotation's top level ([`annotation_is_flat`]), so no type argument
/// list here holds one. Template literal types (substitutions are arbitrary types), object
/// types, function types, tuples and the rest are out.
fn type_is_flat(ty: &ast::TSType<'_>) -> bool {
    match ty {
        ast::TSType::Keyword(_)
        | ast::TSType::ThisType(_)
        | ast::TSType::Literal(
            ast::TSLiteralType::String(_)
            | ast::TSLiteralType::Number(_)
            | ast::TSLiteralType::BigInt(_)
            | ast::TSLiteralType::UnaryExpression(_),
        ) => true,
        ast::TSType::TypeReference(reference) => reference
            .type_arguments
            .as_ref()
            .is_none_or(|args| args.params.iter().all(|arg| type_is_flat(arg))),
        ast::TSType::Array(array) => type_is_flat(array.element_type),
        ast::TSType::TypeOperator(operator) => type_is_flat(operator.type_annotation),
        ast::TSType::IndexedAccess(access) => {
            type_is_flat(access.object_type) && type_is_flat(access.index_type)
        }
        ast::TSType::TypeQuery(query) => query.type_arguments.is_none(),
        _ => false,
    }
}

/// The position of the object-type literal annotating a **hugged** sole parameter at its top
/// level — `(a: { … })`, `({ a }: { … })` — whose authored expansion the hug policy does not
/// read ([`Printer::unforced_param_type_literal`]); `None` when the list has no such literal.
///
/// Exactly prettier's group-less node: `printObject` drops the group of an object type whose
/// path is `typeAnnotation → typeAnnotation → shouldHugTheOnlyParameter`, so the literal must
/// annotate the parameter itself — an identifier or a destructuring pattern straight in the
/// list, not one under a default. Only the author's expansion of that literal goes unread:
/// a blank line between its own members still breaks the signature when the literal prints
/// expanded (prettier's `isNextLineEmpty` separator is a `hardline`, outside the dropped
/// group; one written flat prints flat, its blank dropped, so the hug stays), and its members
/// are not that node, so a nested literal the author expanded breaks it too, as do a
/// pattern's own breaks (an expanded default object, a nested pattern, a blank line between
/// a destructured parameter's properties).
fn sole_param_object_type_start(
    printer: &Printer<'_>,
    params: &[ast::Expression<'_>],
    open: Option<u32>,
    close: impl FnOnce() -> Option<u32>,
) -> Option<u32> {
    sole_param_object_type(printer, params, open, close).map(|literal| literal.span.start)
}

/// The literal [`sole_param_object_type_start`] names, as the node.
///
/// The annotation's shape is read first and the hug's gap and directive reads only for a
/// list it admits, so `close` — the list's `)`, a source scan for most callers — is located
/// only then. Both halves are pure reads, so the order is free.
fn sole_param_object_type<'a>(
    printer: &Printer<'_>,
    params: &'a [ast::Expression<'a>],
    open: Option<u32>,
    close: impl FnOnce() -> Option<u32>,
) -> Option<&'a ast::TSTypeLiteral<'a>> {
    let [param] = params else {
        return None;
    };
    let annotation = match &param.kind {
        ast::ExpressionKind::Identifier(id) => id.type_annotation(),
        ast::ExpressionKind::ObjectPattern(pattern) => pattern.type_annotation.as_ref(),
        ast::ExpressionKind::ArrayPattern(pattern) => pattern.type_annotation.as_ref(),
        _ => None,
    }?;
    let ast::TSType::TypeLiteral(literal) = unwrap_parenthesized(annotation.type_annotation) else {
        return None;
    };
    printer
        .hugs_sole_parameter(params, open, close(), true)
        .then_some(literal)
}

/// A block-bodied callback argument whose hugged sole parameter's object type
/// ([`sole_param_object_type_start`]) the author wrote FLAT — the one shape whose print-width
/// break of that literal tsv reads back as authored.
///
/// The hug keeps an authored expansion of that literal for a block body (the cataloged
/// divergence), so a literal that breaks only for width on the broken-out argument line
/// would read back as the hug: prettier's form there is not a tsv fixed point. The hug
/// ladders admit the hug with the literal assumed expanded instead, through a state gated on
/// that very line ([`AssumedBreak::TypeLiteral`]); this names its eligibility, so every
/// ladder asks one question.
///
/// Comment-free signatures only: a comment there decides the hug through
/// [`callback_signature_refuses_hug`] alone, and keeps the source's reading. A literal whose
/// members hold a blank line is out too: read expanded, it refuses the hug. So is one whose
/// members hold a nested non-empty brace type ([`type_literal_members_hold_brace_type`]): the
/// hug would break that type for width, and its break reads back as authored.
pub(in crate::printer) struct FlatSoleParamLiteral<'a> {
    /// The literal's span start — the [`AssumedBreak::TypeLiteral`] position.
    pub(in crate::printer) literal: u32,
    /// The callback's block body, which every printing of the callback shares.
    pub(in crate::printer) body: &'a ast::BlockStatement<'a>,
    /// Whether the callback is an arrow (its body builds through
    /// `Printer::arrow_block_body_doc`) rather than a `function`.
    pub(in crate::printer) is_arrow: bool,
    /// The break that ends the broken-out argument's line before the body does: a `function`
    /// whose sole parameter groups on its own ([`should_group_function_parameters`]) with an
    /// object return type, which breaks after that type's `{` ([`function_return_type_break`]).
    ///
    /// [`should_group_function_parameters`]: crate::printer::types::function_types::should_group_function_parameters
    pub(in crate::printer) return_break: Option<AssumedBreak>,
}

/// The break prettier's params group measures a `function`'s flat parameters up to, when that
/// group is its own: prettier's `shouldGroupFunctionParameters` (one parameter, type
/// parameters that allow grouping, an object return type) wraps the parameters in a group of
/// their own, and its `fits` reads the rest commands in break mode, so the return type's `{`
/// ends the measured line (`function (a: { … }): {`).
///
/// `None` for any other return type: one that will break already ends the measured line at
/// its own forced break, and one that does not group the parameters leaves the line to the body's.
fn function_return_type_break(func: &ast::FunctionExpression<'_>) -> Option<AssumedBreak> {
    let return_type = func.return_type.as_ref()?;
    if !crate::printer::types::function_types::type_params_allow_grouping(
        func.type_parameters.as_ref(),
    ) {
        return None;
    }
    match unwrap_parenthesized(return_type.type_annotation) {
        ast::TSType::TypeLiteral(literal) => Some(AssumedBreak::TypeLiteral(literal.span.start)),
        ast::TSType::Mapped(mapped) => Some(AssumedBreak::MappedType(mapped.span.start)),
        _ => None,
    }
}

/// [`FlatSoleParamLiteral`] for `arg`, or `None`.
pub(in crate::printer) fn flat_sole_param_literal<'a>(
    printer: &Printer<'_>,
    arg: &'a ast::Expression<'a>,
) -> Option<FlatSoleParamLiteral<'a>> {
    if printer.canonical {
        return None;
    }
    let (literal, body, is_arrow, return_break) = match &arg.kind {
        ast::ExpressionKind::ArrowFunctionExpression(arrow) => {
            let ast::ArrowFunctionBody::BlockStatement(body) = &arrow.body else {
                return None;
            };
            let literal =
                sole_param_object_type(printer, arrow.params, arrow.params_start, || {
                    printer.arrow_params_end(arrow)
                })?;
            (literal, body, true, None)
        }
        ast::ExpressionKind::FunctionExpression(func) => {
            let literal =
                sole_param_object_type(printer, func.params, Some(func.params_start), || {
                    printer
                        .find_closing_paren(func.params_start, func.body.span.start)
                        .map(|after_paren| after_paren - 1)
                })?;
            (literal, &func.body, false, function_return_type_break(func))
        }
        _ => return None,
    };
    // A blank line between the literal's members refuses the hug once the literal is read
    // expanded (`type_literal_force_multiline`), so for it the width break reads back as the
    // broken-out form, not the hug — no state of this kind applies. A nested brace type is
    // out for the same reason: its own width break in the hug reads back as authored, which
    // the hug keeps refusing, as prettier does.
    if printer.literal_authored_expanded(literal)
        || type_literal_members_hold_brace_type(literal)
        || printer.type_literal_members_hold_blank_line(literal)
        || printer.has_comments_on_page_between(arg.span.start, body.span.start)
    {
        return None;
    }
    Some(FlatSoleParamLiteral {
        literal: literal.span.start,
        body,
        is_arrow,
        return_break,
    })
}

/// The break a hug that flattens a `function` callback's parameters is measured up to: the
/// first `{` of its return type, when that type will not break on its own.
///
/// Prettier hugs a last argument that will break (a block body) in
/// `conditionalGroup([[…, group(last, { shouldBreak: true })], allArgsBrokenOut()])`, and its
/// `fits` measures every group nested in a broken one in break mode, so the hug is measured
/// only up to the callback's first line break. Where the hug flattens the parameters
/// (`shouldExpandParameters`: a plain call's last of several arguments, the parameters
/// `removeLines`'d), that break is the return type's first `{`. tsv's inline state measures
/// the hug flat up to the body's `{`; measured that way, a hug that fits only up to the
/// return type's `{` would break every argument out, and prettier's form would read back as
/// the hug with that type authored expanded — a second fixed point. The hug ladders admit
/// the hug with the `{` assumed broken ([`AssumedBreak`]), measured like any state.
///
/// The `{` is the return type's own (an object or mapped type), the one in its sole type
/// argument (`Promise<{`, [`Printer::sole_type_arg_hug_break`]), or the first object member
/// of a hugged union (`{ … } | null`). Distinct from [`FlatSoleParamLiteral::return_break`],
/// which models prettier's parameter GROUPING (`shouldGroupFunctionParameters`) and so
/// takes the object and mapped return types alone: a `Promise<{ … }>` return does not group.
///
/// `None` unless the callback has at most one parameter, of any type, and type parameters
/// that allow grouping (`type_params_allow_grouping`): otherwise tsv's hug does not hold
/// the parameters flat in this measurement, so the state would admit a hug that breaks
/// them, which prettier never prints. `None` too for a bare object return type the author
/// expanded (a perf early-out: the assumed break would be the authored one), an empty
/// object type (no break inside it), and a comment anywhere from the argument to the body —
/// the refusal [`flat_sole_param_literal`] makes, so no comment rides on the assumed break.
pub(in crate::printer) fn function_return_hug_break(
    printer: &Printer<'_>,
    arg: &ast::Expression<'_>,
) -> Option<AssumedBreak> {
    if printer.canonical {
        return None;
    }
    let ast::ExpressionKind::FunctionExpression(func) = &arg.kind else {
        return None;
    };
    if func.params.len() > 1
        || !crate::printer::types::function_types::type_params_allow_grouping(
            func.type_parameters.as_ref(),
        )
    {
        return None;
    }
    let return_type = func.return_type.as_ref()?.type_annotation;
    let brk = return_type_hug_brace(printer, return_type)?;
    if crate::printer::is_brace_block_multiline(printer.source, return_type.span())
        || printer.has_comments_on_page_between(arg.span.start, func.body.span.start)
    {
        return None;
    }
    Some(brk)
}

/// The `{` [`function_return_hug_break`] assumes broken in `ty`, read through every paren
/// shell the printer strips — at the top, around a sole type argument, and around a hugged
/// union's members — so the predicate reads the printed form, and a shell the author wrote
/// cannot refuse a hug its stripped twin takes.
fn return_type_hug_brace(printer: &Printer<'_>, ty: &ast::TSType<'_>) -> Option<AssumedBreak> {
    let member_brace = |union: &ast::TSUnionType<'_>| {
        union
            .types
            .iter()
            .find_map(|member| match unwrap_parenthesized(member) {
                ast::TSType::TypeLiteral(literal) if !literal.members.is_empty() => {
                    Some(AssumedBreak::TypeLiteral(literal.span.start))
                }
                _ => None,
            })
    };
    match unwrap_parenthesized(ty) {
        ast::TSType::TypeLiteral(literal) if !literal.members.is_empty() => {
            Some(AssumedBreak::TypeLiteral(literal.span.start))
        }
        ast::TSType::Mapped(mapped) => Some(AssumedBreak::MappedType(mapped.span.start)),
        ast::TSType::TypeReference(reference) => {
            let args = reference.type_arguments.as_ref()?;
            if let [arg] = args.params {
                let peeled = unwrap_parenthesized(arg);
                let is_shell = |ty: &ast::TSType<'_>| matches!(ty, ast::TSType::Parenthesized(_));
                let shell = is_shell(arg)
                    || matches!(peeled, ast::TSType::Union(union)
                        if union.types.iter().any(|member| is_shell(member)));
                if shell {
                    return match peeled {
                        ast::TSType::TypeLiteral(literal) if !literal.members.is_empty() => {
                            Some(AssumedBreak::TypeLiteral(literal.span.start))
                        }
                        ast::TSType::Mapped(mapped) => {
                            Some(AssumedBreak::MappedType(mapped.span.start))
                        }
                        ast::TSType::Union(union) if printer.union_prints_hugged(union) => {
                            member_brace(union)
                        }
                        _ => None,
                    };
                }
            }
            printer.sole_type_arg_hug_break(args)
        }
        ast::TSType::Union(union) if printer.union_prints_hugged(union) => member_brace(union),
        _ => None,
    }
}

/// Whether `arrow`'s signature refuses a hug that renders its head on the callee's line —
/// prettier's `ArgExpansionBailout`, whatever forces the break: a comment
/// ([`arrow_signature_has_breaking_comments`]) or a break the signature's own docs carry
/// (an authored-expanded object, a blank line between parameters).
///
/// THE question every arrow hug asks before it renders the signature hugged — the
/// expand-last ladders, the lone-argument hugs, and the expand-first hug alike, in every
/// callee spelling — so no site can answer it from one half alone.
pub(in crate::printer) fn arrow_signature_refuses_hug(
    printer: &Printer<'_>,
    arrow: &ast::ArrowFunctionExpression<'_>,
    span: Span,
) -> bool {
    arrow_signature_has_breaking_comments(printer, arrow, span)
        || arrow_signature_will_break(printer, arrow, span)
}

/// [`arrow_signature_refuses_hug`] for a `function` expression argument of a plain call with
/// `arg_count` arguments — the expand-last bailout only, since `printFunction` sets
/// `shouldExpandParameters` under `expandLastArg` alone.
///
/// The comment half is [`function_signature_has_breaking_comments`], asked as before. The
/// doc half is gated by `printFunction`'s own condition: the call has more than one
/// argument, or every parameter is an untyped identifier — so a lone callback with a typed
/// or patterned parameter keeps the hug with its parameters broken, in both formatters. Only
/// the parameter list is asked (`printFunction` reads neither type parameters nor return type
/// at the throw), and the block-bodied arrow's carve-out holds here too: the authored
/// expansion of a hugged sole parameter's own object type is not read.
fn function_signature_refuses_hug(
    printer: &Printer<'_>,
    func: &ast::FunctionExpression<'_>,
    arg_count: usize,
) -> bool {
    if function_signature_has_breaking_comments(printer, func) {
        return true;
    }
    if func.params.is_empty()
        || !(arg_count > 1 || func.params.iter().all(is_untyped_identifier_param))
    {
        return false;
    }
    if params_cannot_force_break(
        printer,
        func.params,
        func.params_start,
        func.body.span.start,
    ) {
        return false;
    }
    let close = printer
        .find_closing_paren(func.params_start, func.body.span.start)
        .map(|after_paren| after_paren - 1);
    let unforced =
        sole_param_object_type_start(printer, func.params, Some(func.params_start), || close);
    // The list is built only to be asked, and every layout candidate of a member chain asks
    // it again, so the build is shared across them ([`ShareTag::SignatureParamsProbe`]).
    let key = printer.chain_share_key_of(
        func,
        Span::new(func.params_start, func.body.span.start),
        ShareTag::SignatureParamsProbe,
    );
    printer.ask_signature_params(unforced, || {
        printer.d().will_break(printer.chain_shared_doc(key, || {
            printer.build_params_doc_with_comments(func.params, Some(func.params_start), close)
        }))
    })
}

/// A parameter `printFunction` counts toward its "every parameter is an untyped identifier"
/// test.
fn is_untyped_identifier_param(param: &ast::Expression<'_>) -> bool {
    matches!(&param.kind, ast::ExpressionKind::Identifier(id) if id.type_annotation().is_none())
}

/// Whether a callback argument of a plain call with `arg_count` arguments refuses the
/// expand-last hug — [`arrow_signature_refuses_hug`] or [`function_signature_refuses_hug`] by
/// the callback's kind.
///
/// The kind-agnostic entry point, so a hug state gates on one question rather than
/// re-deciding per callback kind. Every arm that reached for the arrow predicate alone left
/// the `function` spelling ungated.
pub(in crate::printer) fn callback_signature_refuses_hug(
    printer: &Printer<'_>,
    arg: &ast::Expression<'_>,
    arg_count: usize,
) -> bool {
    match &arg.kind {
        ast::ExpressionKind::ArrowFunctionExpression(arrow) => {
            arrow_signature_refuses_hug(printer, arrow, arg.span)
        }
        ast::ExpressionKind::FunctionExpression(func) => {
            function_signature_refuses_hug(printer, func, arg_count)
        }
        _ => false,
    }
}

/// Check if an expression has a huggable type annotation.
///
/// Parameters with huggable type annotations like `a?: { b: T }` should be hugged:
/// - The opening `{` stays on the same line as the parameter name
/// - The content expands internally
/// - The closing `}` comes on its own line
///
/// This matches Prettier's behavior where `fn(a?: {` stays together.
///
/// NOTE: Does NOT recurse into AssignmentPattern. When a param has a default value
/// like `a: { b: T } = {}`, the `= {}` prevents hugging — prettier breaks the
/// param list instead. Destructuring patterns with defaults (`{a, b} = {}`) are
/// handled separately by `is_huggable_pattern`.
///
/// Shared with the signature-param path (`build_signature_params_doc`) — see
/// `is_huggable_pattern`.
fn has_huggable_type_annotation(expr: &ast::Expression<'_>) -> bool {
    match &expr.kind {
        ast::ExpressionKind::Identifier(id) => id
            .type_annotation()
            .is_some_and(|ann| is_huggable_type(ann.type_annotation)),
        _ => false,
    }
}

/// [`Printer::head_forced_chain_lead`]'s verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::printer) enum HeadForcedChainLead {
    /// The seam breaks after its operator and the heads stack at one indent under it, as
    /// with no comment: an empty gap, a run of single-line blocks glued through to the
    /// first head (it leads that head below the break), or a gap that stacks the chain
    /// under the break it forces ([`Printer::seam_break_stacks_curried_chain`]).
    Stacked,
    /// A PRESERVED multi-line block glued through to the value: its own lines are the
    /// break, so the seam takes none after its operator — the first head rides the
    /// comment's closing line and the rest indent under it, the chain's default shape.
    /// The width-driven chain's answer too ([`Printer::build_led_curried_chain_doc`]), and
    /// prettier's for both.
    PreservedBlock,
    /// A run the author gave lines of its own above the chain (`=⏎/* c */⏎({}) => …`,
    /// `= /* c */⏎({}) => …`): prettier's leading own-line comment. The seam breaks after
    /// its operator for the run and the chain takes its default shape below it — the heads
    /// past the first indented under it — as the width-driven chain does.
    OwnLineRun,
}

impl HeadForcedChainLead {
    /// The context the chain is built under: [`ArrowChainContext::AssignmentRhs`] makes the
    /// arrow printer decline its own chain layout so the seam's break stacks the heads;
    /// `None` is the default shape.
    pub(in crate::printer) fn chain_context(self) -> ArrowChainContext {
        match self {
            Self::Stacked => ArrowChainContext::AssignmentRhs { leading_run: None },
            Self::PreservedBlock | Self::OwnLineRun => ArrowChainContext::None,
        }
    }
}

impl<'a> Printer<'a> {
    /// Run `ask` — a parameter list built only to be ASKED whether it will break — with
    /// `test_call_flat_params` cleared and `unforced` naming the literal whose authored
    /// expansion the question does not read ([`Self::unforced_param_type_literal`]),
    /// restoring both afterwards.
    ///
    /// The test-call flag is consumed by the first parameter list built under it, so the
    /// question must not take it from the build that prints: it asks the list as an ordinary
    /// one, and the printing build still finds the flag set.
    fn ask_signature_params(&self, unforced: Option<u32>, ask: impl FnOnce() -> bool) -> bool {
        let prev_flat = self.test_call_flat_params.replace(false);
        let prev_unforced = self.unforced_param_type_literal.replace(unforced);
        let answer = ask();
        self.unforced_param_type_literal.set(prev_unforced);
        self.test_call_flat_params.set(prev_flat);
        answer
    }

    /// Whether `arrow` has an empty parameter list with a comment inside its parens (or in the
    /// gap behind them) — the one signature prettier's `expandLastArg` / `expandFirstArg`
    /// printing does not flatten, since `printFunctionParameters` returns an empty list
    /// before its `removeLines`. **On page**: an owned comment occupies the line as well.
    pub(in crate::printer) fn arrow_empty_params_hold_comments(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
    ) -> bool {
        arrow.params.is_empty()
            && arrow
                .params_start
                .is_some_and(|open| self.has_comments_on_page_between(open, arrow.arrow_token))
    }

    /// Whether both delimiter gaps around a lone parameter are free of comments to emit —
    /// the shared precondition of the sole-parameter hug at all three parameter builders.
    ///
    /// A comment in either gap declines the hug outright: the hug arm emits neither gap and
    /// must not grow an emitter for one, so an unclaimed gap would be a DROP
    /// (`docs/comments.md` hazard 4). The breakable path places it instead.
    ///
    /// `open` is the position the parameter's leading gap starts at (just past the `(`) and
    /// `close` the `)`. Either may be `None` when the caller could not locate its parens —
    /// the gap then collapses onto the parameter's own edge and is empty by construction.
    /// `comments_present` is the caller's zero-comment window gate, so a comment-free
    /// signature answers `true` without a search; a caller that has not computed one yet
    /// passes `true`.
    pub(in crate::printer) fn param_delimiter_gaps_empty(
        &self,
        param: &ast::Expression<'_>,
        open: Option<u32>,
        close: Option<u32>,
        comments_present: bool,
    ) -> bool {
        !comments_present
            || (open.is_none_or(|o| !self.has_comments_to_emit_between(o, param.span().start))
                && close.is_none_or(|c| !self.has_comments_to_emit_between(param.span().end, c)))
    }

    /// Prettier's **`shouldHugTheOnlyFunctionParameter`** (`print/function-parameters.js`):
    /// a lone parameter that is an object/array pattern, or carries an object-type
    /// annotation, hugs — `({` and `}: T)` stay welded to the signature while the pattern's
    /// own group breaks, instead of the parameter LIST breaking around it.
    ///
    /// Shared by all three parameter builders — the value-param path
    /// ([`Self::build_params_doc_with_comments`] — function declarations, expressions,
    /// methods, arrows), the signature path ([`Self::build_signature_params_doc`] — bodyless
    /// `declare`/overload functions and type-member method/call/construct signatures) and
    /// the function/constructor-TYPE path (`build_function_params_doc`), so the hug cannot
    /// drift between them; each hugs through [`Self::build_hugged_literal_param_doc`] and
    /// its own ordinary parameter doc.
    ///
    /// See [`Self::param_delimiter_gaps_empty`] for the comment precondition and
    /// [`Self::param_has_decorators`] for the decorator one (prettier's
    /// `hasNotParameterDecorator`: any decorator declines the hug, because the decorator
    /// and its binding form a group of their own that the hug cannot express).
    pub(in crate::printer) fn hugs_sole_parameter(
        &self,
        params: &[ast::Expression<'_>],
        open: Option<u32>,
        close: Option<u32>,
        comments_present: bool,
    ) -> bool {
        params.len() == 1
            && (is_huggable_pattern(&params[0]) || has_huggable_type_annotation(&params[0]))
            && self.param_delimiter_gaps_empty(&params[0], open, close, comments_present)
            && !self.param_has_decorators(&params[0])
            && !self.param_annotation_holds_own_line_directive(&params[0])
    }

    /// Whether a lone parameter's annotation carries an honored own-line format-ignore
    /// directive — in its `:`→type gap, or inside that type's redundant paren shell
    /// ([`Printer::paren_interior_routed_inner`]).
    ///
    /// It declines the hug, the third precondition beside the two delimiter gaps and the
    /// decorator: the hug arm prints the `:`→literal run INLINE
    /// ([`Printer::build_hugged_literal_param_doc`]), which glues the directive to the
    /// parameter's `p:` — a placement tsv's own floor reads as inert, so the freeze is lost
    /// on the second pass and the author's bytes normalize once. The breakable path honors
    /// it through the annotation's own directive route, which is also where every other
    /// annotation position (a declarator, a class property, a signature member) honors it,
    /// so declining is what keeps the sole-parameter spelling agreeing with its siblings.
    fn param_annotation_holds_own_line_directive(&self, param: &ast::Expression<'_>) -> bool {
        let ast::ExpressionKind::Identifier(id) = &param.kind else {
            return false;
        };
        id.type_annotation().is_some_and(|ann| {
            let colon_end = ann.span.start + 1;
            self.member_gap_frozen(colon_end, ann.type_annotation.span().start)
                || self
                    .paren_interior_routed_inner(ann.type_annotation)
                    .is_some()
        })
    }

    /// Build a doc with `context` active so the outermost curried arrow chain in
    /// it picks the right flattened layout. The arrow printer consumes the
    /// context at entry (`replace(None)`); restoring the prior value here keeps it
    /// from leaking to a sibling argument / operand / RHS. Mirrors prettier
    /// routing the parent context into `printArrowFunctionSignatures`.
    pub(in crate::printer) fn build_with_arrow_chain_context(
        &self,
        context: ArrowChainContext,
        build: impl FnOnce() -> DocId,
    ) -> DocId {
        let prev = self.arrow_chain_context.replace(context);
        let doc = build();
        self.arrow_chain_context.set(prev);
        doc
    }

    /// Build a curried chain RHS under [`ArrowChainContext::AssignmentRhs`] and print the
    /// seam's operator→value comment run (`gap` is its window) with it — exactly once,
    /// wherever it belongs:
    ///
    /// - a run glued through to the chain rides INTO it, behind the chain's own
    ///   break-after-operator softline, so it leads the first head on whichever line the
    ///   heads land on. Printed ahead of the chain instead it stays on the operator's line
    ///   while the heads break below (`= /* c */⏎(a) =>`), which the next pass reads as a run
    ///   the author broke after. Where no chain layout consumed it — the chain declined,
    ///   the value froze — the context comes back still holding it and it leads the value;
    /// - a run holding a MULTI-LINE block leads the chain from the operator's line, and the
    ///   chain takes no break after the operator at all: inside the chain's group the
    ///   comment's body would force that break on a chain that fits
    ///   (`const i = /* a⏎b */ (p) => (q) => p;`), so the first head rides the comment's
    ///   closing line and the rest indent under it — prettier's own answer for the shape;
    /// - a run that is not glued through (the author gave part of it a line of its own)
    ///   leads the chain as built.
    pub(in crate::printer) fn build_led_curried_chain_doc(
        &self,
        leading_run: Option<DocId>,
        gap: (u32, u32),
        build: impl FnOnce() -> DocId,
    ) -> DocId {
        let d = self.d();
        let unled = ArrowChainContext::AssignmentRhs { leading_run: None };
        let Some(run) = leading_run else {
            return self.build_with_arrow_chain_context(unled, build);
        };
        if self.has_multiline_block_comments_on_page_between(gap.0, gap.1) {
            let doc = self.build_with_arrow_chain_context(ArrowChainContext::None, build);
            return d.concat(&[run, doc]);
        }
        if !self.comment_run_glued_through(gap.0, gap.1) {
            return d.concat(&[run, self.build_with_arrow_chain_context(unled, build)]);
        }
        let prev = self
            .arrow_chain_context
            .replace(ArrowChainContext::AssignmentRhs { leading_run });
        let doc = build();
        match self.arrow_chain_context.replace(prev) {
            ArrowChainContext::AssignmentRhs {
                leading_run: Some(_),
            } => d.concat(&[run, doc]),
            _ => doc,
        }
    }

    /// Whether a curried chain under a seam that has ALREADY broken after its operator and
    /// indented — a comment arm's forced break, or a hang — stacks its heads at the one
    /// indent the comment-free chain gives them ([`ArrowChainContext::AssignmentRhsHung`]).
    ///
    /// Two gaps, the two where prettier has no form to match:
    ///
    /// - a `//` on the OPERATOR's line (`= // c⏎(a) => (b) => …`), where prettier fabricates
    ///   a blank line below the comment and indents the chain twice;
    /// - an indentable block GLUED to the first head, which hangs it
    ///   ([`Printer::indentable_block_leads_value`]) and which prettier likewise indents twice.
    ///
    /// A run the author gave lines of its own above the chain (`=⏎// c⏎(a) => …`,
    /// `= /* c */⏎(a) => …`, and an indentable block with the chain on the line BELOW its
    /// `*/` — the kind does not make an own-line comment anything else) is NOT one: prettier
    /// prints that chain in its default shape —
    /// the heads past the first indented under it — stably, and tsv matches it, which is
    /// the no-context build every such arm already does.
    pub(in crate::printer) fn seam_break_stacks_curried_chain(
        &self,
        value: &ast::Expression<'_>,
        gap_start: u32,
    ) -> bool {
        if !is_curried_arrow_chain(value) {
            return false;
        }
        let value_start = value.span().start;
        self.comments_on_page_between(gap_start, value_start)
            .next()
            // The SOURCE question, never a distance from `gap_start`: a seam's gap may open
            // ahead of its operator (the assignment's, at the target's end), so a line break
            // the author put before the `=` would read as one before the comment.
            .is_some_and(|c| !c.is_block && self.comment_follows_content_on_its_line(c))
            || (self.indentable_block_leads_value(gap_start, value_start)
                && self.comment_run_glued_through(gap_start, value_start))
    }

    /// How the operator→value gap's comment run places a curried chain whose heads force
    /// the break ([`is_curried_arrow_chain_that_breaks`]) — the one reading both
    /// `printAssignment` twins take (`build_declarator_init_doc`,
    /// [`Printer::build_assignment_layout`]), so the declarator, the assignment, the class
    /// field and the object property cannot answer one comment four ways. `gap_start` opens
    /// the gap.
    ///
    /// ⚠️ Every arm is a question about the SOURCE, never about which arm of a cascade ran
    /// first. The declarator reaches its preserved-block arm only past its broke-after and
    /// own-line arms, so there "a multi-line block is in the gap" implied "glued through";
    /// the assignment layout has no such order, and the same test pulled a class
    /// property's OWN-LINE block onto the `=` line with the first head at the member's
    /// indent — idempotent, so no fixed-point fixture saw it.
    pub(in crate::printer) fn head_forced_chain_lead(
        &self,
        value: &ast::Expression<'_>,
        gap_start: u32,
    ) -> HeadForcedChainLead {
        let value_start = value.span().start;
        if !self.has_comments_on_page_between(gap_start, value_start)
            || self.seam_break_stacks_curried_chain(value, gap_start)
        {
            HeadForcedChainLead::Stacked
        } else if !self.comment_run_glued_through(gap_start, value_start) {
            HeadForcedChainLead::OwnLineRun
        } else if self.has_multiline_block_comments_on_page_between(gap_start, value_start) {
            HeadForcedChainLead::PreservedBlock
        } else {
            HeadForcedChainLead::Stacked
        }
    }

    /// Build `value`'s doc for a seam that has ALREADY broken after its operator and
    /// indented, under [`ArrowChainContext::AssignmentRhsHung`] where
    /// [`Self::seam_break_stacks_curried_chain`] says the chain stacks, and untouched
    /// otherwise. `gap_start` opens the operator→value gap.
    ///
    /// Every `=` / `:` seam with such an arm asks this, so the declarator, the assignment,
    /// the class field and the object property cannot answer one comment four ways.
    pub(in crate::printer) fn build_hung_value_doc(
        &self,
        value: &ast::Expression<'_>,
        gap_start: u32,
        build: impl FnOnce() -> DocId,
    ) -> DocId {
        if self.seam_break_stacks_curried_chain(value, gap_start) {
            self.build_with_arrow_chain_context(ArrowChainContext::AssignmentRhsHung, build)
        } else {
            build()
        }
    }

    /// The root doc of an EMBEDDER's assignment value
    /// (`crate::__private::build_assignment_value_expression_doc`, which states the contract): the
    /// assignment-value mark, then — where the host leaves the break after its operator to
    /// the value, handing it the operator→value gap that opens at `value_gap_start` — a
    /// curried chain's assignment-RHS shape, printing the gap's run itself.
    ///
    /// The run is placed exactly as `build_assignment_layout`'s fluid chain arm places it:
    /// hoisted whole off the page ([`Self::hoist_owned_value_gap_run`] — a chain that owns
    /// its break is that hoist's second licence), else the gap's emit-axis block run, and
    /// handed to [`Self::build_led_curried_chain_doc`], which puts it behind the chain's
    /// own softline.
    pub(crate) fn build_assignment_value_root_doc(
        &self,
        expression: &ast::Expression<'_>,
        value_gap_start: Option<u32>,
    ) -> DocId {
        self.mark_assignment_value(expression);
        let build = || self.build_root_expression_doc(expression);
        let Some(gap_start) = value_gap_start.filter(|_| is_curried_arrow_chain(expression)) else {
            return build();
        };
        let value_start = expression.span().start;
        // The gap's emit-axis block run — what either arm below leads the chain with.
        let emit_run = || {
            self.build_comments_between_filtered_opt(
                gap_start,
                value_start,
                CommentSpacing::Trailing,
                CommentFilter::BlockOnly,
            )
        };
        if is_curried_arrow_chain_that_breaks(expression) {
            // The host breaks after its operator for such a chain, so the gap's run leads the
            // first head below that break — the declarator's own answer, where the arrow
            // prints the one comment glued to its `(` and the gap prints the rest. The
            // context only makes the arrow printer decline a break of its own.
            let doc = self.build_with_arrow_chain_context(
                ArrowChainContext::AssignmentRhs { leading_run: None },
                build,
            );
            return match emit_run() {
                Some(run) => self.d().concat(&[run, doc]),
                None => doc,
            };
        }
        self.hoist_owned_value_gap_run(gap_start, expression, false, |hoisted| {
            // `or`, never a concat — see [`Printer::hoisted_owned_value_gap_run_opt`]. The
            // emit-axis run is built only where the hoist declined.
            let run = hoisted.or_else(emit_run);
            self.build_led_curried_chain_doc(run, (gap_start, value_start), build)
        })
        .1
    }

    /// The whole `" =" …` right-hand side of an EMBEDDER's assignment seam whose
    /// operator→value gap stacks a curried chain under the break it forces
    /// ([`Self::seam_break_stacks_curried_chain`]: a `//` on the operator's line, an
    /// indentable block leading the value), or `None` where it does not — the host then
    /// keeps its own layout. `crate::__private::build_stacked_curried_chain_rhs_doc` states the
    /// contract.
    ///
    /// The declarator's own arms, in the declarator's order
    /// (`Printer::build_declarator_init_doc`): the broke-after block run, the
    /// comment-forced break ([`Self::build_eq_comment_break_rhs`], which keeps a `//` on the
    /// operator's line), then the indentable hang with the run hoisted out of the value. Each
    /// prints the gap's whole run, so the host prints none of it. `build_suffix` is handed
    /// the value's doc, only on `Some`, and what it returns rides after the value inside
    /// whatever indent the arm opened.
    pub(crate) fn build_stacked_curried_chain_rhs_doc(
        &self,
        expression: &ast::Expression<'_>,
        operator_pos: u32,
        build_suffix: impl Fn(DocId) -> DocId,
    ) -> Option<DocId> {
        let gap_start = operator_pos + 1;
        if !self.seam_break_stacks_curried_chain(expression, gap_start) {
            return None;
        }
        let d = self.d();
        self.mark_assignment_value(expression);
        let value_start = expression.span().start;
        let hoisted_run = self.hoisted_owned_value_gap_run_opt(gap_start, expression, false);
        let hung_value = || {
            let value = self.build_hung_value_doc(expression, gap_start, || {
                self.build_gap_value_doc(hoisted_run, expression, || {
                    self.build_root_expression_doc(expression)
                })
            });
            d.concat(&[value, build_suffix(value)])
        };
        let emit_run = self.build_comments_between_filtered_opt(
            gap_start,
            value_start,
            CommentSpacing::Trailing,
            CommentFilter::BlockOnly,
        );
        if emit_run.is_some()
            && let Some(rhs) = self.broke_after_operator_rhs_doc(gap_start, value_start, hung_value)
        {
            return Some(d.concat(&[d.text(" ="), rhs]));
        }
        if let Some(rhs) =
            self.build_eq_comment_break_rhs(operator_pos, value_start, " =", hung_value)
        {
            return Some(rhs);
        }
        let value = hung_value();
        let value = match hoisted_run.or(emit_run) {
            Some(run) => d.concat(&[run, value]),
            None => value,
        };
        Some(d.concat(&[d.text(" ="), hang_after_operator(d, value)]))
    }

    /// Run `build` with [`Printer::in_stacked_arrow_chain`] set to `value`, restoring the
    /// prior value afterward. Mirrors `build_with_arrow_chain_context`: the flag is
    /// per-chain layout state that must not leak to sibling arrows nested inside the
    /// body (callbacks, object-property arrows). The arms that set it to the value
    /// it already holds rely on the restore returning that same value.
    fn build_with_stacked_chain(&self, value: bool, build: impl FnOnce() -> DocId) -> DocId {
        let prev = self.in_stacked_arrow_chain.replace(value);
        let doc = build();
        self.in_stacked_arrow_chain.set(prev);
        doc
    }

    /// Print an arrow function expression using doc-based formatting with width-aware wrapping.
    ///
    /// Prettier behavior for arrow functions:
    /// Build a Doc for an arrow function with width-aware wrapping.
    ///
    /// Prettier's algorithm (from arrow-function.js and function-parameters.js):
    /// 1. Type params are wrapped in their OWN group - they break independently
    /// 2. Function params are NOT in their own group - just softlines
    /// 3. The whole signature (type params group + params + return type) is wrapped in a group
    /// 4. When the signature group breaks, params break but type params may stay flat
    ///
    /// Structure:
    /// ```text
    /// group([
    ///     group(type_params),  // inner group - breaks independently
    ///     "(", indent([softline, params...]), ifBreak(","), softline, ")",
    ///     return_type,
    ///     " =>"
    /// ])
    /// " " + body
    /// ```
    fn build_arrow_doc_wrapping(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
    ) -> DocId {
        // Consume the chain context (set by the enclosing assignment / call-arg /
        // binary-operand printer) so only the outermost chain arrow uses it;
        // nested arrows in the chain reset to the default layout.
        let chain_context = self.arrow_chain_context.replace(ArrowChainContext::None);
        if self.should_use_arrow_chain_layout(arrow, span, chain_context) {
            return self.build_arrow_chain_doc(arrow, span, chain_context);
        }
        // A leading run the seam handed in goes back to it: only the chain layout has a
        // softline to put it behind ([`Self::build_led_curried_chain_doc`]).
        if matches!(
            chain_context,
            ArrowChainContext::AssignmentRhs {
                leading_run: Some(_)
            }
        ) {
            self.arrow_chain_context.set(chain_context);
        }

        let d = self.d();
        let mut parts = DocBuf::new();

        // The `=>` token position (parser-recorded) distinguishes:
        // - Comments between the signature and `=>` → print BEFORE `=>`
        // - Comments between `=>` and body → print AFTER `=>`
        let arrow_end = arrow_token_end(arrow);

        // Build the signature (async + type params + params + return type) via the
        // shared builder, then append any comment between the signature and `=>`
        // (`(x) /* c */ =>`) — the seam the call-argument states share.
        //
        // The stacked-chain flag describes this arrow's place in its chain — the BODY build
        // below reads it — and says nothing about an arrow nested in the signature (a default
        // parameter's own curried chain), so the signature is built with it cleared.
        let sig_doc = self.build_with_stacked_chain(false, || {
            self.append_pre_arrow_comments(arrow, span, self.build_arrow_signature_doc(arrow, span))
        });

        // Wrap entire signature in a group. In expand-last-arg context, render the
        // signature flat (remove_lines) so the params can't break — prettier's
        // `expandLastArg` path prints params with `removeLines`, which is what lets a
        // force-broken arrow keep its destructuring param inline and fall through to
        // the all-args-broken-out layout instead of shattering the param.
        // An empty list is not flattened when it holds a comment: prettier returns an empty
        // list ahead of its `removeLines`, so a dangling `//` keeps its own line.
        let flat_params = self.expand_last_arg_flat_params.get();
        if flat_params && !self.arrow_empty_params_hold_comments(arrow) {
            parts.push(d.remove_lines(sig_doc));
        } else {
            parts.push(d.group(sig_doc));
        }

        // " =>" outside the sig group so fits() look-ahead sees it as text
        // consuming remaining width. When sig + " =>" = print_width, the " =>"
        // leaves remaining=0 for the body — ternary body's " " text then
        // pushes to -1 and forces the sig group to break params.
        parts.push(d.text(" =>"));

        // Body: expression bodies can break to a new line with indent; block bodies
        // stay hugged to `=>`.
        //
        // ⚠️ This is where `expand_last_arg_flat_params` STOPS. Prettier hands
        // `expandLastArg` to exactly one nested print — `bodyDoc = print("body", args)`
        // (`print/arrow-function.js`) — so it reaches the hugged argument and then travels
        // only down an ARROW-BODY spine (`shouldPrintAsChain` is false under the flag, so
        // each head prints its body with the same `args` and the run of signatures all take
        // `removeLines`). Every other body kind receives the flag and ignores it: the object
        // / array / ternary printers pass no `args` to their own children, so an arrow nested
        // inside the hugged body keeps its break points. tsv spells the flag as ambient
        // `Printer` state, so without this clear it survived the whole descent and
        // `remove_lines`ed such an arrow's parameters — printing a 101-column line where
        // prettier shatters the destructuring param
        // (`calls/chained/expand_last_nested_arrow_params_long`). The signature above is
        // built with the flag still set, which is what keeps prettier's `removeLines` over
        // the argument's OWN parameters — including anything nested in a parameter default,
        // where prettier's doc-level transform strips lines too.
        let body_is_arrow = matches!(
            &arrow.body,
            ast::ArrowFunctionBody::Expression(expr)
                if matches!(expr.kind, ast::ExpressionKind::ArrowFunctionExpression(_))
        );
        let restore_flat = flat_params && !body_is_arrow;
        if restore_flat {
            self.expand_last_arg_flat_params.set(false);
        }
        match &arrow.body {
            ast::ArrowFunctionBody::Expression(expr) => {
                self.build_arrow_expression_body(&mut parts, expr, arrow, span, arrow_end);
            }
            ast::ArrowFunctionBody::BlockStatement(block) => {
                self.build_arrow_block_body(&mut parts, block, arrow_end);
            }
        }
        if restore_flat {
            self.expand_last_arg_flat_params.set(true);
        }

        d.concat(&parts)
    }

    /// Whether the grouping shell the parser stripped from an arrow BODY holds a comment —
    /// the gate on the retained-paren arm of [`Self::build_arrow_expression_body`].
    ///
    /// Not `has_trailing_paren_comments(body.span().end, …)`, and the difference is one node
    /// kind: a SEQUENCE's span overshoots its operands by the shell the parser erased from
    /// the LAST one, so a comment written there sits *behind* that start and the gate reads
    /// the gap as empty. [`Printer::shell_trailing_gap_start`] is the one statement of where
    /// a shell's trailing gap opens, and an arrow body is a value position exactly like the
    /// declarator's and the `return` argument's: the comment belongs inside the pair the
    /// sequence prints (prettier #19263), not floated out past it by the statement default
    /// (`() => (x, (y /* t */))`, whose float landed the comment after the `)` and, for a
    /// `//`, past the statement's `;` as well).
    ///
    /// ⚠️ **Two askers, one predicate — and the second asker cannot currently reach the
    /// widened reading.** The body arm asks it to take the retained-paren route; the hug
    /// arm's geometry probe asks it as a *precondition* — "this body took that route, so
    /// the hug ladder is not in play" ([`Self::arrow_gap_broke_after_run`]). A sequence
    /// body does HUG (`arrow_body_always_hugs`), so the probe's own hug test admits it,
    /// but no sequence body with a comment in that shell survives to be asked: the in-file
    /// caller sits BELOW the retained-paren early return, which asks this same predicate
    /// and has already returned when it is true, and the call-side caller is reached only
    /// past `could_expand_arrow_arg`, which is false for a sequence body (prettier expands
    /// only an object / array / block terminal, a call through a trailing `!`, or a
    /// ternary). Reverting just this call site to the narrow reading formats the whole
    /// fixture suite and the whole gates corpus to the same bytes. It is spelled this way
    /// anyway because the two askers must not be able to drift: if `could_expand_arrow_arg`
    /// or the retained-paren arm ever widens, a second copy of the rule left here would be
    /// one state the two report differently.
    fn arrow_body_shell_holds_comments(
        &self,
        expr: &ast::Expression<'_>,
        arrow_span_end: u32,
        frozen: Option<Span>,
    ) -> bool {
        let gap_start = self.shell_trailing_gap_start(expr, arrow_span_end, frozen, false);
        self.has_trailing_paren_comments(gap_start, arrow_span_end)
    }

    /// Emit the body of an arrow with an expression body (the `=>` already pushed)
    /// into `parts`. Branches on whether the body hugs `=>` (object/array/template),
    /// hangs on the next line, joins a curried chain, or carries comments — mirroring
    /// prettier's `shouldPutBodyOnSameLine` / `shouldAddParensIfNotBreak` cascade.
    fn build_arrow_expression_body(
        &self,
        parts: &mut DocBuf,
        expr: &ast::Expression<'_>,
        arrow: &ast::ArrowFunctionExpression<'_>,
        arrow_span: Span,
        arrow_end: u32,
    ) {
        let d = self.d();

        // The `=>`→body value head ([`Printer::value_head_frozen_span`]): an own-line
        // directive in the gap freezes the whole body, the assignment family's rule with
        // `=>` as the delimiter. Resolved ONCE, above the cascade, because the two arms
        // that can hold such a directive sit on opposite sides of the early return below —
        // the retained-paren arm here and arm 1 of the cascade, and no other (asserted
        // where `has_own_line_comment` is computed). Resolved above the gate too, since the
        // gap the gate measures opens at the FROZEN slice's end where there is one.
        let frozen = self.value_head_frozen_span(arrow_end, expr.span());

        // Check for trailing comments from stripped grouping parens.
        // When the parser strips parens from `() => (x /* c */)`, comments
        // between the body's printed end and the arrow's span end are lost. Re-add parens
        // to preserve them, matching the unary expression approach.
        let has_trailing_paren_comments =
            self.arrow_body_shell_holds_comments(expr, arrow_span.end, frozen);

        if has_trailing_paren_comments {
            let body_start = expr.span().start;
            // A sequence body hangs (prettier's `shouldIndentSequenceExpression`) — the
            // same answer the comment-free arrow-body path gives; this arm reaches the
            // sequence through the retained-paren helper, so it names the layout itself.
            //
            // A FROZEN body prints verbatim, so no layout of the retained pair's contents
            // is available to it — the shell keeps its own emission
            // ([`Printer::build_frozen_kept_paren_doc`], the same one the declarator and
            // assignment shells take), which is what keeps this gap's comment inside the
            // pair on both the frozen and the unfrozen path.
            let body_doc = match frozen {
                Some(frozen) => self.build_frozen_kept_paren_doc(frozen, arrow_span.end),
                None => self.build_expression_doc_keep_paren_comments(
                    expr,
                    arrow_span.end,
                    SeqLayout::Hanging,
                ),
            };
            // This arm reassembles the body — it wraps the retained parens itself — so it
            // must answer the `=>`→body gap on its own, exactly as the cascade below does.
            // Emitting the run inline unconditionally is the blind-twin bug that costs a
            // `//` its line end: `() => // c⏎(x /* t */)` printed
            // `() => // c (x /* t */);`, the whole body swallowed into the comment.
            if self.has_own_line_post_arrow_comment(arrow_end, body_start) {
                self.push_arrow_gap_tail(parts, arrow_end, body_start, |resume| {
                    prepend_leading(d, self.arrow_gap_leading_run(resume, body_start), body_doc)
                });
            } else {
                // Leading comments between `=>` and body (if any):
                // `() => /* lead */ (x /* trail */)` — emit inline leading,
                // then paren-wrapped body with trailing. Only glued blocks reach
                // here; the arm above took every comment that must end its line.
                // The run is the hug arm's own (`gap_run` below, defined past this
                // early return), so the two agree on the gap by construction.
                parts.push(d.text(" "));
                if let Some(run) = self.build_rhs_comments_glued_opt(arrow_end, body_start) {
                    parts.push(run);
                }
                parts.push(body_doc);
            }
            // Skip normal body handling — paren wrapping covers all cases
            return;
        }

        // Check for comments between `=>` and body start
        // These are comments like: `() => /* comment */ expr`
        let body_start = expr.span().start;
        let has_post_arrow_comments = self.has_comments_to_emit_between(arrow_end, body_start);

        // Prettier's `hasLeadingOwnLineComment`: checks if any comment
        // between `=>` and body has a newline after it. Inline block
        // comments like `=> /* c */ expr` return false (body stays hugged),
        // while own-line comments return true (body breaks).
        let has_own_line_comment =
            has_post_arrow_comments && self.has_own_line_post_arrow_comment(arrow_end, body_start);

        // A resolved freeze reaches arm 1 and no other: an honored directive is a `//` alone
        // on its line, which satisfies both conjuncts above, and arms 2-7 are each reached
        // only once arm 1 declined. Every one of them builds the body through a route that
        // knows nothing of `frozen`, so a shape that broke this would drop the freeze
        // silently — the wrong output being its own fixed point, invisible to every gate.
        debug_assert!(
            frozen.is_none() || has_own_line_comment,
            "an =>→body freeze must reach the own-line-comment arm"
        );

        // Prettier's `shouldPutBodyOnSameLine`: certain expression types stay hugged to =>
        // Object/array literals always hug.
        // Nested arrows hug ONLY when outer has no return type annotation.
        // With return type: const f = (x: T): H => (y) => expr; // breaks
        // Without:          const f = (x: T) => (y) => expr;    // hugs
        //
        // A body inside the pair a comma-list region keeps is no chain head: the pair closes
        // the chain there ([`Printer::chain_holds_region_kept_body`]).
        let is_arrow_body = matches!(expr.kind, ast::ExpressionKind::ArrowFunctionExpression(_))
            && !self.relational_sibling_pair_is_kept(expr);

        // Check if this is a curried arrow where ANY arrow triggers chain breaking.
        // Triggers: return type with params, type parameters, non-identifier params.
        // ⚠️ This reader is what `skip_arrow_chain` is FOR. Its other reader
        // (`should_use_arrow_chain_layout`) is redundant with the flag's own set condition, so
        // this is the flag's only live effect: in an expand-last hug (prettier's
        // `expandLastArg`, where `shouldPrintAsChain` is false) the body must stay on the `=>`
        // line rather than break. Dropping the term unhugs every typed curried callback.
        //
        // ⚠️ The verdict belongs to the WHOLE chain (prettier accumulates `shouldBreakChain`
        // over every head before it prints any), and `arrow_chain_should_break` only looks
        // inwards from the arrow it is handed. A head BELOW the trigger therefore reads the
        // verdict from the stacked flag its outer heads set, or the plain heads past a
        // destructured one hug each other on one line (`(b) => (c) =>`).
        let chain_should_break = is_arrow_body
            && !self.skip_arrow_chain.get()
            && (self.in_stacked_arrow_chain.get()
                || crate::printer::arrow_chain_should_break(arrow));

        // Check if body arrow has trailing param comments (forces break)
        let body_arrow_param_comment_forces_break = matches!(
            &expr.kind,
            ast::ExpressionKind::ArrowFunctionExpression(body_arrow)
                if self.arrow_trailing_param_comment_forces_break(body_arrow)
        );

        // Inline block comments don't prevent hugging — only own-line comments do.
        // `() => /* comment */ ({...})` hugs (inline block comment)
        // `() =>\n  /* comment */\n  ({...})` breaks (own-line comment)
        //
        // The two extra conjuncts are tsv's, not prettier's, and both are compensations for
        // being on THIS path rather than the chain layout: a chain the break forces open must
        // stack its heads here (the chain layout renders that break itself), and a trailing
        // param comment in the body arrow's signature forces it multiline. Neither can fire
        // for a body that is not an arrow, so a sequence / object / array / template body
        // reaches the same answer both printers give.
        let should_hug = !has_own_line_comment
            && self.arrow_body_hugs(expr)
            && !chain_should_break
            && !body_arrow_param_comment_forces_break;

        // The curried-chain and parenthesized-ternary arms below *reassemble* the body —
        // they build its doc and wrap it themselves — so nothing on those routes emits the
        // `=>`→body gap and the comment is dropped outright (`(x) => /* c */ (a ? b : c)`).
        // The run is handed to the body (`build_arrow_body_doc_with_leading`), which is the
        // single place that decides which side of the body's parens it belongs on: inside a
        // ternary's `if_break` layout parens, outside every required one. That is where the
        // call-argument routes already put it (`prepend_arrow_body_comments`) and where
        // prettier puts it — the ternary's parens are a layout artifact that vanishes when
        // the body breaks, so a position outside them exists in only one rendering.
        //
        // Own-line comments took the first arm, so the gap holds nothing but inline blocks
        // and takes the same emitter the hug and normal arms use. The lookup is the *emit*
        // axis, which skips owned comments: one glued to the body's first token rides the
        // body's own doc and still prints exactly once.
        // Lazy: only the arms below read it, and the own-line arm never does — it always has
        // `has_post_arrow_comments` set (a conjunct of `has_own_line_comment`) and routes to
        // `build_arrow_body_with_comments_doc`, so building this up front would leave a dead
        // comments doc in the arena on every commented arrow that isn't one of the rest.
        //
        // `AdjacentGlued` is the one glue mode that is provably a SPACE per comment here, which
        // is what lets the whole glued half of this gap share the single leading-comment emitter
        // (`docs/comments.md`) instead of hand-rolling the separator: every arm below is reached
        // only once `has_own_line_comment` declined, so no comment in the gap can satisfy
        // `comment_cannot_glue_to_operator`, and the mode's hug test is then unconditionally true.
        // A MULTI-LINE block the BODY owns is glued to the body's first token and travels
        // INSIDE its doc, so its reprinted body force-breaks the body's own group and a body
        // prettier keeps flat explodes ([`Printer::hoist_owned_value_gap_run`] carries the
        // why). The `=>`→body gap is a value gap like the `=` seams — it already marks
        // itself one (`mark_jsdoc_cast_value_gap`) — so it hoists the same way: the run
        // REPLACES the gap's own emitter below, and every arm that builds the body does so
        // under the paired suppression (`build_value_under_hoist`), or the comment is
        // dropped outright (`docs/comments.md` hazard 1).
        //
        // ⚠️ Declined for an INJECTED body: the expand-last paths pre-build the body doc
        // elsewhere (`Printer::with_arrow_body_inject`), without this suppression, so the
        // comment is already inside it and hoisting would print it twice.
        let hoisted_run = self
            .arrow_body_inject
            .get()
            .is_none_or(|(span, _)| span != body_start)
            .then(|| {
                self.hoisted_owned_value_gap_run_opt(
                    arrow_end,
                    expr,
                    self.needs_parens(expr, ParenContext::ArrowBody),
                )
            })
            .flatten();
        let build_body = |build: &dyn Fn() -> DocId| -> DocId {
            self.build_value_under_hoist(hoisted_run, expr, build)
        };
        // `or`, never a concat — the hoisted run is the same gap read on the wider
        // (on-page) axis, so emitting both prints every un-owned comment in it twice.
        let gap_run = || {
            hoisted_run.or_else(|| {
                has_post_arrow_comments
                    .then(|| self.build_rhs_comments_glued_opt(arrow_end, body_start))
                    .flatten()
            })
        };

        // ⚠️ These arms are ORDERED and the order is LOAD-BEARING — each is reached only
        // because every arm above it declined, so an arm's stated condition is never its
        // full precondition. In precedence order:
        //
        //   1. own-line comment      — takes every own-line/line comment out of the gap, so
        //                              arms 2-7 see nothing but inline blocks there.
        //   2. hug                   — object / array / same-line template bodies stop here.
        //   3. curried, typed        — a nested arrow under a return type, or inside a chain.
        //   4. curried, param comment— a nested arrow whose params carry a trailing comment.
        //   5. curried, innermost    — the terminal body of a curried chain, ANY body type.
        //   6. ternary               — `shouldAddParensIfNotBreak`.
        //   7. normal expression.
        //
        // The trap that has already cost a bug: **5 fires before 6**, so a ternary body
        // inside a curried chain is printed by arm 5 (which delegates to
        // `build_arrow_body_doc`, whose own ternary branch adds the parens) and never
        // reaches arm 6. The two routes must therefore agree about the `=>`→body gap —
        // arms 3/4/5/6 each reassemble the body and so must each hand the gap run to it,
        // which is what `gap_run` above is for. `build_arrow_chain_doc` is an eighth route
        // for the gaps it emits — the inter-head ones, via `arrow_gap_leading_run` — but
        // never for the TERMINAL `=>`→body gap: `chain_comment_outside_emitted_regions`
        // leaves that region out of the chain's emitted set, so a comment there declines
        // the chain layout and lands in the arms below. (Declining for a comment
        // anywhere in the chain at all would make the whole flattened layout dead code.)
        if has_own_line_comment {
            // Own-line or line comments — always break. A run the author GLUED to `=>`
            // keeps that line first; only what is left resumes on the leading-run route.
            self.push_arrow_gap_tail(parts, arrow_end, body_start, |resume| {
                self.build_arrow_body_with_comments_doc(expr, resume, body_start, frozen)
            });
        } else if should_hug {
            // Hugged body (possibly with inline block comments):
            // `() => ({...})` or `() => /* c */ ({...})`. The whole arm is
            // [`Self::arrow_hug_body_doc`], which the curried-chain layout's terminal
            // hug arm calls too.
            parts.push(self.arrow_hug_body_doc(
                arrow,
                arrow_span,
                arrow_end,
                expr,
                hoisted_run,
                gap_run(),
            ));
        } else if is_arrow_body && (chain_should_break || self.in_stacked_arrow_chain.get()) {
            // Curried arrow chain - all arrows break without indent so they align:
            // const f = (x: T): H => (y) => expr   // outer has return type
            // const f = (x: T) => (y): H => expr   // inner has return type
            // becomes:
            // const f =
            //     (x: T): H =>      or      (x: T) =>
            //     (y) =>                    (y): H =>
            //         expr                      expr
            //
            // The flag is already set when reached via `in_stacked_arrow_chain`, so
            // unconditionally setting it `true` for the body build is equivalent.
            let body_doc = build_body(&|| {
                self.build_with_stacked_chain(true, || {
                    self.build_arrow_body_doc_with_leading(expr, gap_run())
                })
            });
            parts.push(d.concat(&[d.hardline(), body_doc]));
        } else if is_arrow_body && body_arrow_param_comment_forces_break {
            // Nested arrow with trailing param comments - first level gets indent,
            // subsequent levels align (use curried pattern)
            // (a, // c) => (b, // c) => {}
            // becomes:
            // (a, // c) =>
            //     (b, // c) =>
            //     (c, // c) => {}
            let body_doc = build_body(&|| {
                self.build_with_stacked_chain(true, || {
                    self.build_arrow_body_doc_with_leading(expr, gap_run())
                })
            });
            parts.push(d.indent_hardline(body_doc));
        } else if self.in_stacked_arrow_chain.get() {
            // Innermost arrow in curried chain - body is NOT another arrow.
            // This needs indent since it's the final expression.
            // Reset flag so arrows inside the body (e.g. callback args) aren't
            // treated as part of the curried chain; restore to `true` (its value on
            // entry, since this arm is reached only when the flag is set) afterward.
            let body_doc = build_body(&|| {
                self.build_with_stacked_chain(false, || {
                    self.build_arrow_body_doc_with_leading(expr, gap_run())
                })
            });
            parts.push(d.indent_hardline(body_doc));
        } else if self.arrow_body_takes_ternary_pair(expr) {
            // Prettier's shouldAddParensIfNotBreak: ternary body gets conditional
            // parens when inline, no parens when on its own line.
            // Excludes ternaries whose test starts with ObjectExpression (matches
            // Prettier's startsWithNoLookaheadToken check) — those fall through
            // to the normal path which calls build_arrow_body_doc for object parens.
            //
            // Structure: [" ", group([ifBreak("","("), indent([softline, body]),
            //                         ifBreak("",")")])]
            //
            // The " " TEXT element before the group is critical for fits() boundary:
            // when sig + " =>" = exactly print_width, remaining=0. The " " consumes
            // 1 char (→ -1), making the sig group fail fits() and break params.
            // With the old group(indent(line, body)), line() in Break mode would
            // short-circuit fits() to return true, keeping the sig flat.
            //
            // Flat:  ` => (cond ? a : b)` — parens, same line
            // Break: ` =>\n\tcond ? a : b` — no parens, next line
            //
            // Expand-last-arg body reuse: the multi-arg conditional-body break state builds
            // this same ternary separately; reuse the pre-built DocId (span-keyed) to avoid an
            // O(2^depth) double build when the ternary recurses. See the `arrow_body_inject` field.
            let body_doc = if let Some((span, doc)) = self.arrow_body_inject.get()
                && span == expr.span().start
            {
                doc
            } else {
                // A multi-line comment the body owns prints outside the ternary's own
                // group, or its hard break explodes a ternary prettier keeps flat
                // ([`Printer::build_value_with_outermost_owned_comment`]).
                build_body(&|| self.build_expression_doc_claiming_outermost(expr))
            };
            // This arm emits the paren tokens itself rather than going through
            // `build_arrow_body_doc`, so it prepends the run on its own seam — the same
            // side of the parens that helper picks for a ternary, i.e. inside.
            // `will_break` asks about the BODY, so it reads the raw doc.
            //
            // A run the author broke after takes its newline-after soft `line`
            // instead of the glued space: inside the parens group it materializes
            // exactly when the ternary drops to its own (paren-less) line — width
            // or a hard break in the body — and collapses to the glued bytes flat.
            // An author blank yields with a WIDTH break, as at every value gap
            // (`Printer::value_gap_soft_broke_after_run`); a body with a hard break of its
            // own forces the break instead, so the run takes the forced emitter and the
            // blank survives with it — the `=` seams' two halves
            // ([`Printer::break_or_hang_after_operator_run_doc`]).
            let soft_run = self.value_gap_soft_broke_after_run(arrow_end, body_start);
            if let Some(run) = &soft_run
                && self.broke_after_run_break_is_forced(run, body_doc)
            {
                parts.push(self.break_after_operator_run_doc(run, body_start, body_doc));
            } else {
                // Prettier's `hasLeadingOwnLineComment` is a newline after ANY comment in the
                // gap, so a run the author broke after takes its own-line arm: no space after
                // `=>` and no paren pair to measure, the signature's `fits()` ending at `=>`.
                let broke_after = soft_run.is_some();
                let with_leading = if let Some(run) = soft_run {
                    let mut run_parts = DocBuf::new();
                    self.push_leading_run_with_soft_line(&mut run_parts, &run);
                    run_parts.push(body_doc);
                    d.concat(&run_parts)
                } else {
                    prepend_leading(d, gap_run(), body_doc)
                };
                if broke_after {
                    // The run's own line is the BROKEN layout, so the space rides the flat
                    // half with the `(` — a `(sig) =>` line of exactly the print width keeps
                    // its parameters flat with the run below `=>`
                    // (`calls/arrow_ternary_body_lone_arg_comment_long`), while a signature
                    // that must break still joins the run into the parens on `) =>` when it fits.
                    // The body cannot break here: one that will takes the forced emitter above
                    // (`broke_after_run_break_is_forced`).
                    parts.push(ternary_body_parens_group_spaced(d, with_leading));
                } else {
                    // Prettier's `" "` before the parens group, whatever that group decides: the
                    // renderer trims it at a break, but the signature's `fits()` counts it, so a
                    // `(sig) =>` line one short of the print width breaks the parameters
                    // (`calls/arrow_ternary_body_lone_arg_long`).
                    parts.push(d.text(" "));
                    parts.push(if d.will_break(body_doc) {
                        // Body has hardlines (multiline template in ternary, etc.)
                        // Use normal break layout — no parens needed
                        hang_after_operator(d, with_leading)
                    } else {
                        ternary_body_parens_group(d, with_leading)
                    });
                }
            }
        } else {
            // Normal expression: can break after => with indentation
            // Short: (x) => x + 1
            // Long:  (veryLongParams) =>
            //            veryLongExpr
            //
            // The body is wrapped in a group so it can make its own fits() decision.
            // This allows the arrow body to stay inline even when the parent element
            // is in break mode, as long as the body content fits from its position.
            //
            // Normal expression body: can break after => with indentation.
            // Template literal bodies with literalline nodes will propagate
            // breaks naturally, enabling chain/call expansion decisions.
            // Inline block comments before a non-huggable body:
            // `() => /* comment */ a + b`
            //
            // A run the author broke after takes the `=` seams' two halves
            // ([`Printer::break_or_hang_after_operator_run_doc`]): a body with a hard break of
            // its own forces the break, and an author blank survives with it; anything else
            // rides the hang group's own machinery — flat renders the glued bytes, a width
            // break puts the run on its own line with the body re-fitting below, prettier's
            // `printLeadingComment` `line`, and an author blank yields with that break, as at
            // the ternary arm (`Printer::value_gap_soft_broke_after_run`).
            let body_doc = build_body(&|| self.build_arrow_body_doc(expr));
            parts.push(
                if let Some(run) = self.value_gap_soft_broke_after_run(arrow_end, body_start) {
                    self.break_or_hang_after_operator_run_doc(&run, body_start, body_doc)
                } else {
                    hang_after_operator(d, prepend_leading(d, gap_run(), body_doc))
                },
            );
        }
    }

    /// The `=>`→body emission for a HUG-eligible body — an object / array / sequence /
    /// same-line template — with the gap's run already read on both axes by the caller.
    ///
    /// **Both arrow layouts print their hug arm through here**, which is what holds the
    /// curried chain's terminal hug to the single arrow's: the chain's own copy of this
    /// cascade drifted, feeding its terminal gap the SOFT broke-after run
    /// ([`Printer::push_leading_run_with_soft_line`]) where this arm feeds the glued one, so
    /// a run the author broke after landed its own forced break inside the hug's
    /// `concat([" ", …])` — no group, no indent — and printed flush at column 0, a second
    /// fixed point one pass away.
    ///
    /// A block run glued to `=>` that the author broke after, before a body that WILL break,
    /// takes prettier's break-after-operator form instead of the hug — the run own-line under
    /// `=>`, the body below it (the `=` seams' rule; the shared gate + emitter). A body that
    /// FITS declines and keeps the glued hug, whose flat render is the same bytes prettier's
    /// collapsed `line` produces.
    ///
    /// The geometry is [`Self::arrow_gap_broke_after_run`] rather than this arm's own
    /// reading, because the enclosing CALL must ask the identical question to know whether
    /// its `)` drops with the body — see that predicate.
    ///
    /// `gap_run` is the caller's glued-or-hoisted run and `hoisted_run` the hoist half of it,
    /// so the fallback body is built under the hoist's paired suppression
    /// ([`Printer::build_value_under_hoist`]). The broken arm needs neither: the hoist fires
    /// only on a run glued through to the body and `arrow_gap_broke_after_run` only on one
    /// the author broke after, so the two are disjoint by construction.
    fn arrow_hug_body_doc(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        arrow_span: Span,
        gap_start: u32,
        expr: &ast::Expression<'_>,
        hoisted_run: Option<DocId>,
        gap_run: Option<DocId>,
    ) -> DocId {
        let d = self.d();
        let body_start = expr.span().start;
        let broken = self
            .arrow_gap_broke_after_run(arrow, arrow_span, gap_start, body_start)
            .and_then(|run| {
                let body_doc = self.build_arrow_body_doc(expr);
                d.will_break(body_doc)
                    .then(|| self.break_after_operator_run_doc(&run, body_start, body_doc))
            });
        if let Some(doc) = broken {
            return doc;
        }
        let mut parts: DocBuf = smallvec![d.text(" ")];
        if let Some(run) = gap_run {
            parts.push(run);
        }
        parts.push(
            self.build_value_under_hoist(hoisted_run, expr, || self.build_arrow_body_doc(expr)),
        );
        d.concat(&parts)
    }

    /// Emit the body of an arrow with a block-statement body (the `=>` already
    /// pushed) into `parts`. A block body always stays hugged to `=>` and
    /// terminates any curried-arrow chain.
    /// The doc an arrow's **block** body renders as, on its own — the block-body counterpart
    /// of [`Self::build_arrow_body_doc`], split out so an argument printer can pre-build it
    /// once and inject it ([`Self::inject_arrow_body`]) rather than have each of the two
    /// `expandLastArg` printings rebuild the whole body.
    ///
    /// A block body terminates any curried-arrow chain — arrows nested inside it (callbacks,
    /// object-property arrows) are NOT part of the chain, so the stacked-chain flag is cleared
    /// so they aren't force-broken after `=>`. Mirrors the innermost expression-body case.
    pub(crate) fn arrow_block_body_doc(&self, block: &ast::BlockStatement<'_>) -> DocId {
        if let Some((span, doc)) = self.arrow_body_inject.get()
            && span == block.span.start
        {
            return doc;
        }
        self.build_with_stacked_chain(false, || self.build_block_statement_doc(block))
    }

    fn build_arrow_block_body(
        &self,
        parts: &mut DocBuf,
        block: &ast::BlockStatement<'_>,
        arrow_end: u32,
    ) {
        let d = self.d();

        // Block body: always stays hugged to => (no break)
        // (params) => {
        //     ...
        // }
        // Check for comments between `=>` and body start
        let body_start = block.span.start;
        let has_post_arrow_comments = self.has_comments_to_emit_between(arrow_end, body_start);

        // The `=>`→body head's freeze for a BLOCK body, the statement-shaped twin of the
        // expression body's ([`Printer::gap_frozen_span`]): an own-line directive in the gap
        // freezes the block whole, braces included. A block owes no terminator, so the
        // emission is the plain node slice — the same one the `export default` declaration
        // values take. Prettier freezes here too, and self-stably.
        let block_doc = match self.gap_frozen_span(arrow_end, block.span) {
            Some(frozen) => self.build_frozen_node_doc(frozen),
            None => self.arrow_block_body_doc(block),
        };

        // A line comment (or own-line block comment) between `=>` and the block
        // body must break so the comment sits on its own line and the `{` drops
        // to the next line — emitting it inline would let the `//` run to
        // end-of-line and swallow the `{`, dropping the whole block body
        // (non-idempotent, non-reparseable). Mirrors the expression-body path
        // (`build_arrow_body_with_comments_doc`).
        if has_post_arrow_comments && self.has_own_line_post_arrow_comment(arrow_end, body_start) {
            self.push_arrow_gap_tail(parts, arrow_end, body_start, |resume| {
                prepend_leading(d, self.arrow_gap_leading_run(resume, body_start), block_doc)
            });
            return;
        }

        // Otherwise the block stays hugged to `=>`; an inline block comment
        // (`=> /* c */ {}`) sits between and can't swallow the brace.
        if has_post_arrow_comments {
            let mut comment_parts: DocBuf = DocBuf::new();
            for comment in self.comments_to_emit_between(arrow_end, body_start) {
                comment_parts.push(d.text(" "));
                comment_parts.push(self.build_comment_doc(comment));
            }
            parts.push(d.concat(&comment_parts));
        }

        parts.push(d.text(" "));
        parts.push(block_doc);
    }

    /// Whether to render an arrow as a flattened curried chain (prettier's
    /// `printArrowFunctionSignatures`): the body must be another arrow, and every comment
    /// must sit in a region [`Printer::build_arrow_chain_doc`] emits
    /// ([`Self::chain_comment_outside_emitted_regions`]). Prettier asks nothing of the
    /// POSITION — `shouldPrintAsChain` is `!expandLastArg && body is arrow` — so a `None`
    /// context (no enclosing chain site: `export default`, `return`, an array element, a
    /// ternary branch, a default parameter, `yield`, `throw`, a cast's operand) takes the
    /// layout too, in prettier's default shape.
    ///
    /// ⚠️ [`crate::printer::arrow_chain_should_break`] — prettier's `shouldBreakChain` — is a **break**
    /// decision, not a refusal, and it is one here in every context but `AssignmentRhs`.
    /// The exception is real rather than stylistic: at an assignment the SITE already owns
    /// the break, `choose_layout` answering the identical question with
    /// `AssignmentLayout::BreakAfterOperator` (`assignment.rs`, `is_curried_arrow_chain_that_breaks`),
    /// whose newline-after-`=` plus indent renders exactly what the chain layout's own
    /// `indent([softline, …])` would — so letting the chain through there would apply the
    /// indent twice. Nothing owns the break in call-argument or binaryish position, which is
    /// why the refusal there simply lost it: the heads stayed flat one indent short of
    /// prettier. Any future site that widens the context set inherits the break arm, not the
    /// refusal, unless it can point at its own owner the way the assignment does.
    ///
    /// The `skip_arrow_chain` term below is **load-bearing**, not a restatement. Prettier's
    /// `expandLastArg` print has no chain layout at all (`printArrowFunction`'s
    /// `shouldPrintAsChain = !args.expandLastArg && …`), and every hug state that reads that
    /// printing builds it through `calls::build_expand_last_arg_doc` — which sets the flag for
    /// an **untyped** chain too, one nothing further down refuses. The context is no backstop:
    /// only an arrow consumes `arrow_chain_context` (`build_arrow_doc_wrapping` takes it), so a
    /// call NESTED in an argument still has the enclosing `CallArgOrBinaryish` ambient while its
    /// own hug states build — `fn0(g1((a) => (b) => (c) => ({ … })))`, where dropping the term
    /// gives the expanded printing a chain layout, whose own heads then break and FIT, hugging a
    /// run prettier breaks out.
    ///
    /// The one `None` that declines is an INNER head of a chain the assignment site
    /// stacked: the context was consumed by the head that declined, and the heads below it
    /// belong to that stacked layout ([`Printer::in_stacked_arrow_chain`]), not to a chain
    /// of their own.
    fn should_use_arrow_chain_layout(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
        context: ArrowChainContext,
    ) -> bool {
        if self.skip_arrow_chain.get() {
            return false;
        }
        // Inside a chain the ASSIGNMENT site stacked (its `=` owns the break and the indent),
        // every inner head is built with the consumed `None` context. Those belong to the
        // stacked layout already under way, not to a fresh chain of their own.
        if context == ArrowChainContext::None && self.in_stacked_arrow_chain.get() {
            return false;
        }
        let body_is_arrow = matches!(
            &arrow.body,
            ast::ArrowFunctionBody::Expression(b)
                if matches!(b.kind, ast::ExpressionKind::ArrowFunctionExpression(_))
        );
        if !body_is_arrow || self.chain_holds_region_kept_body(arrow) {
            return false;
        }
        if matches!(
            context,
            ArrowChainContext::AssignmentRhs { .. } | ArrowChainContext::AssignmentRhsHung
        ) && crate::printer::arrow_chain_should_break(arrow)
        {
            return false;
        }
        !self.chain_comment_outside_emitted_regions(arrow, span)
    }

    /// Whether an arrow body down `arrow`'s curried chain prints inside the pair the author
    /// wrote around it, kept by a comma-list owner's region rules
    /// ([`Printer::relational_sibling_pair_is_kept`]): `fn(() => (c => c < d), e > (f, g))`,
    /// `fn(a < b, () => (c => c > (d, e)))`. The chain layout prints every head's body bare,
    /// which between the `<` and the later `>` reads as one generic call, or puts a head's
    /// `=>` past another inside the region, a line tsv's own parse can refuse; so such a chain
    /// takes the ordinary arrow layout, whose body builds through the kept pair.
    fn chain_holds_region_kept_body(&self, arrow: &ast::ArrowFunctionExpression<'_>) -> bool {
        if !self.has_relational_sibling_pairs.get() {
            return false;
        }
        let mut current = arrow;
        while let ast::ArrowFunctionBody::Expression(body) = &current.body
            && let ast::ExpressionKind::ArrowFunctionExpression(inner) = &body.kind
        {
            if self.relational_sibling_pair_is_kept(body) {
                return true;
            }
            current = inner;
        }
        false
    }

    /// Whether the chain holds a comment in a gap [`Printer::build_arrow_chain_doc`] has
    /// no emitter for — the question that decides whether the flattened layout is legal
    /// at all.
    ///
    /// The chain doc's byte range partitions into five region kinds, and it emits three
    /// of them:
    ///
    /// - each head's **signature**, `[head.span.start, arrow_signature_end(head))`, printed
    ///   by [`Self::build_arrow_signature_doc`] — the same region the default arrow layout
    ///   delegates to that builder, [`Self::append_pre_arrow_comments`] owning the complement;
    /// - each inner head's leading **`=>`→body gap**, via [`Self::arrow_gap_leading_run`];
    /// - the **terminal `=>`→body gap**, whose run rides the terminal body glued — but only
    ///   when every comment in it CAN glue ([`Self::terminal_arrow_gap_emitted`]);
    /// - the **terminal body**'s own span, printed by `build_arrow_body_doc` /
    ///   `build_block_statement_doc`.
    ///
    /// The other two are unemitted, so a comment in one is DROPPED — hazard 4 in
    /// `docs/comments.md`, measured rather than assumed: each head's signature→`=>` gap
    /// (`(x) /* c */ =>`), and the terminal body→chain-end region (a stripped grouping
    /// paren's trailing comments, whose retained-paren form is a sanctioned divergence the
    /// default layout owns). ⚠️ **Ownership masks both**: a glued block comment rides
    /// inside its own node's doc, so only a line or own-line comment exposes the loss and a
    /// block-comment repro reports the chain healthy. Those gaps route to the default arrow
    /// layout, which owns them — and at both, that layout already converges with prettier.
    ///
    /// ⚠️ The question is **positional** — comment offsets against span regions — and must
    /// stay that way. A kind or own-line test here would be conditioned on what this very
    /// layout produces (breaking a parameter list is what puts a comment at a line start),
    /// the rake spelled out at
    /// [`Self::range_has_layout_stable_break_forcing_comment`].
    fn chain_comment_outside_emitted_regions(
        &self,
        head: &ast::ArrowFunctionExpression<'_>,
        head_span: Span,
    ) -> bool {
        if !self.has_comments_to_emit_between(head_span.start, head_span.end) {
            return false;
        }
        let mut emitted: SmallVec<[(u32, u32); 8]> = SmallVec::new();
        let mut terminal_gap_start = head_span.start;
        let terminal = walk_arrow_chain(head, head_span, |current, current_span, gap_start| {
            emitted.push((
                current_span.start,
                self.arrow_signature_end(current, current_span),
            ));
            if let Some(gap_start) = gap_start {
                emitted.push((gap_start, current_span.start));
            }
            terminal_gap_start = arrow_token_end(current);
        });
        let body = terminal.span();
        if self.terminal_arrow_gap_emitted(terminal_gap_start, body) {
            emitted.push((terminal_gap_start, body.start));
        }
        // ⚠️ The terminal body's emitted region stops where its DOC stops printing, which is
        // not its span end for a SEQUENCE: the span overshoots the operands by the grouping
        // shell the parser erased from the LAST one, and the chain's `build_arrow_body_doc`
        // takes the float-out builder, which carries a comment there OUT of the pair
        // (`(a) => (b) => (x, (y /* t */))` → `(x, y) /* t */`, and a `//` past the `;`).
        // That region is the retained-paren form's, which only the DEFAULT arrow layout
        // owns ([`Printer::arrow_body_shell_holds_comments`]) — the same reason the
        // body→chain-end region above it is unemitted, one node's span inward.
        let printed_end = match terminal {
            ast::ArrowFunctionBody::Expression(expr) => {
                self.shell_trailing_gap_start(expr, head_span.end, None, false)
            }
            ast::ArrowFunctionBody::BlockStatement(_) => body.end,
        };
        emitted.push((body.start, printed_end));

        self.comments_to_emit_between(head_span.start, head_span.end)
            .any(|comment| {
                !emitted
                    .iter()
                    .any(|&(start, end)| comment.span.start >= start && comment.span.end <= end)
            })
    }

    /// Whether [`Printer::build_arrow_chain_doc`] emits the **terminal** `=>`→body gap —
    /// the one gap the chain spans that the inter-head emitter cannot reach, since the
    /// terminal body is not a head.
    ///
    /// The body part answers that gap with the **same emitters** the default arrow layout's
    /// `=>`→body arms use — the glued run, the owned-comment hoist, the broke-after pair, and
    /// the own-line arm's [`Self::push_arrow_gap_tail`] — so every comment in it has a home
    /// and the region is emitted for every authoring but one.
    ///
    /// ⚠️ **The exception is a FROZEN body head**, not a comment kind. An alone-on-line
    /// format-ignore directive in this gap freezes the whole body
    /// ([`Printer::value_head_frozen_span`]), and the frozen slice is built from the
    /// directive's own span by the default layout's own-line arm, which resolves that span
    /// above its cascade. The chain reassembles the body through builders that know nothing
    /// of it, so a freeze here would print the body reformatted and no gate would see it —
    /// the wrong output is its own fixed point. That one gap routes to the default layout,
    /// which owns it.
    ///
    /// ⚠️ **Deciding this by comment KIND is the own-line rake, and it bit.** While the gap's
    /// own-line runs were refused, this layout's own forced broke-after emission
    /// (`=> /* a */⏎/**⏎ * b⏎ */ v`, whose break prettier keeps) *produced* an own-line run on
    /// pass 1, which pass 2 then read as a refusal — one authoring, two layouts, two head
    /// indents, forever. A region this layout emits must be decided by something its own
    /// output cannot manufacture; a freeze is such a thing, an own-line comment is not.
    ///
    /// The gap needs an emitter at all because its comment is invisible on the *emit* axis
    /// exactly when the body's first token OWNS it — a glued block binds to the token after
    /// it, so the author's redundant grouping parens around the body (`=> /* c */ (z)`) hand
    /// the binding to the `(` instead and the same comment, in the same position, reads as
    /// unemitted. Since the shell is stripped on the way out, one pass later the comment is
    /// owned: two forms of one authoring, two passes apart. A redundant paren carries no
    /// authoring signal, so at this gap both format alike.
    fn terminal_arrow_gap_emitted(&self, gap_start: u32, body_span: Span) -> bool {
        self.value_head_frozen_span(gap_start, body_span).is_none()
    }

    /// The leading-comment run for an arrow-adjacent gap that is **already broken** — the
    /// `=>`→body gap in its own-line arms, and a chain's head→head gap — or `None` when the
    /// gap holds nothing to emit.
    ///
    /// One question, one builder, for the three sites that ask it: the block-body own-line
    /// arm, the expression-body own-line arm ([`Self::build_arrow_body_with_comments_doc`],
    /// which hands the run to the body so it lands on the right side of its parens), and the
    /// chain's inter-head gap. All three take `LeadingGlue::Adjacent` — the mode whose extra
    /// glued rule cannot fire, since every comment reaching them is own-line by their
    /// callers' gates — so the difference between them is only what they do with the run,
    /// which is [`prepend_leading`]'s job.
    ///
    /// ⚠️ At the chain's gap, what reaches here is only ever a run needing a line of its own:
    /// a **glued block** there is owned and rides the inner arrow's own doc, claimed by
    /// `prepend_owned_leading_comment_at` a step earlier. That is why the chain layout
    /// printed glued blocks correctly while dropping every line and own-line comment beside
    /// them — the ownership mask on hazard 4 (`docs/comments.md`).
    fn arrow_gap_leading_run(&self, start: u32, end: u32) -> Option<DocId> {
        self.build_rhs_comments_opt(start, end)
    }

    /// Emit the `=>`-GLUED head of an arrow gap's comment run — the comments the author
    /// wrote on the `=>`'s own line — and report where the remaining, own-line run resumes.
    ///
    /// This is the `=>` spelling of [§Uniform Forced-Continuation
    /// Indent](../../../../docs/conformance_prettier.md): a `//` runs to end-of-line, so
    /// whatever follows it cannot stay on that line, and tsv keeps the comment where the
    /// author wrote it and drops the tail to the continuation. Every sibling gap already
    /// answers this way through [`Printer::append_keyword_value_line_comments`] (`new`,
    /// `await`, `keyof`, `: T`, and the **function-type** arrow's own `=>`), whose same-line
    /// loop this mirrors — a glued block takes a space, a glued `//` takes the deferred
    /// trailing form and ends the line.
    ///
    /// ⚠️ The *emission* is that emitter's; the **policy around it is not**, so the two are
    /// deliberately not one function. The family emitter glues a same-line block whether or
    /// not a `//` follows it; here a prefix with no `//` in it glues nothing, because a
    /// multiline block the author broke after is a different rule at this gap (below).
    ///
    /// ⚠️ **Anything emitted here owes a HARDLINE below it**, not the soft
    /// [`hang_after_operator`] line: a glued `//` is a `line_suffix`, so a tail that renders
    /// flat behind it is swallowed into the comment — output that does not reparse. The
    /// three `=>`→body sites get that for free from [`Self::push_arrow_gap_tail`], which is
    /// the only way they reach this; the chain's head gap owes it by hand because its break
    /// is a *separator* rather than a hang, and it pays through the same
    /// [`Self::arrow_glued_head_break`].
    ///
    /// Returning the resume position rather than the whole run keeps the own-line half on
    /// its existing route — [`Self::build_arrow_body_with_comments_doc`] hands that run to
    /// the body so it lands on the correct side of the body's parens, which a wholesale
    /// switch to the family emitter would lose.
    fn push_arrow_gap_glued_head(
        &self,
        parts: &mut DocBuf,
        sig_end: u32,
        body_start: u32,
    ) -> Option<ArrowGapGluedHead> {
        let d = self.d();
        // The same-line prefix, and whether it ends in the `//` that makes it one.
        let glued: CommentVec<'_> = self
            .comments_to_emit_between(sig_end, body_start)
            .take_while(|c| self.is_same_line(sig_end, c.span.start))
            .collect();
        // ⚠️ **The rule is the LINE comment's**, not every glued comment's. A `//` runs to
        // end-of-line, so the author could not have put the tail on that line and the
        // comment's position is unambiguous; a **block** the author glued and then broke
        // after is the [§Authored breaks in value
        // position](../../../../docs/conformance_prettier.md) case instead, where the break
        // is the signal and the run hangs own-line under `=>` with the body below it. So a
        // same-line prefix with no `//` in it glues nothing and leaves the gap to the
        // caller's existing route (`arrow/body_comment`'s `unformatted_inline` is the pin).
        if glued.last().is_none_or(|c| c.is_block) {
            return None;
        }
        let mut resume = sig_end;
        for comment in &glued {
            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));
            }
            resume = comment.span.end;
        }
        // The `//` ended the `=>` line, so the rest of the run is own-line by construction.
        // An author blank below it has no other emitter — the break below is the next thing
        // out — so it is measured here, stepping over any comment in the gap (the in-source
        // axis).
        let next = self.blank_scan_end(resume, body_start);
        Some(ArrowGapGluedHead {
            resume,
            blank_below: self.has_blank_line_between_strict(resume, next),
        })
    }

    /// The forced break a glued comment head owes below itself, carrying an author blank
    /// that survived it. One spelling for the two shapes that need it — the `=>`→body
    /// continuation and the chain's head→head separator — so the blank cannot be honored at
    /// one and dropped at the other.
    fn arrow_glued_head_break(&self, head: &ArrowGapGluedHead) -> DocId {
        let d = self.d();
        if head.blank_below {
            d.concat(&[d.literalline(), d.hardline()])
        } else {
            d.hardline()
        }
    }

    /// Emit an arrow's `=>`→body gap and the tail below it: the author's glued comment head
    /// keeps the `=>` line, and the tail hangs under it.
    ///
    /// **The single route for all three `=>`→body sites** (expression body, block body, and
    /// the retained-paren arm), and the reason none of them can get the break wrong: a glued
    /// head forces a hardline continuation, an unglued gap keeps the soft
    /// [`hang_after_operator`] the uncommented arrow has always used, and the choice is made
    /// here rather than restated at each. `build_tail` receives the position the own-line
    /// half of the run resumes at, which is all the three sites differ by.
    fn push_arrow_gap_tail(
        &self,
        parts: &mut DocBuf,
        sig_end: u32,
        body_start: u32,
        build_tail: impl FnOnce(u32) -> DocId,
    ) {
        let d = self.d();
        let head = self.push_arrow_gap_glued_head(parts, sig_end, body_start);
        let tail = build_tail(head.as_ref().map_or(sig_end, |h| h.resume));
        parts.push(match head {
            Some(head) => d.indent(d.concat(&[self.arrow_glued_head_break(&head), tail])),
            None => hang_after_operator(d, tail),
        });
    }

    /// Build a flattened curried arrow chain: the signature heads
    /// (`(a) => (b) => …`) form a breakable keyed group ([`GroupId`]),
    /// so they stay on one line when they fit and break otherwise. The terminal
    /// arrow's `=>` is emitted after the group so the body hugs the last head; a
    /// hugging body (object/array/template/block) stays inline, others hang on
    /// the next line.
    ///
    /// Mirrors prettier's `printArrowFunction`. The heads' shape depends on the
    /// parent context (`printArrowFunctionSignatures` branches):
    /// - `AssignmentRhs`: all heads join in one group indented one level after
    ///   `=` (the leading softline is the break-after-`=`); when they break, each
    ///   head shares the same indent. The break-after-`=` decision is supplied by
    ///   the enclosing fluid assignment layout (`choose_layout` routes untyped
    ///   chains to `Fluid`).
    /// - `CallArgOrBinaryish`: progressive indent — the first head stays on the
    ///   line, the rest indent one level (`group([sig0, " =>", indent([line,
    ///   join([" =>", line], rest)])])`).
    /// - `None`: prettier's default branch, `group(indent(join([" =>", line], sigs)))` —
    ///   which renders exactly as the progressive shape does (the first head is already on
    ///   the line, so the indent reaches only the rest), and so shares its arm.
    /// - `Callee`: the joined heads at one shared indent inside the callee's own parens,
    ///   which open onto their own lines when the chain breaks.
    fn build_arrow_chain_doc(
        &self,
        head: &ast::ArrowFunctionExpression<'_>,
        span: Span,
        context: ArrowChainContext,
    ) -> DocId {
        let d = self.d();

        // Collect each head's signature, in the walk the legality predicate shares.
        let mut sig_docs: DocBuf = DocBuf::new();
        // The separator tail for the gap BEFORE each head past the first — a bare `line`,
        // or that gap's `=>`-glued comment run plus the forced break it owes. Indexed
        // against `sig_docs` one behind: `gap_tails[i]` sits between head `i` and head
        // `i + 1`.
        let mut gap_tails: DocBuf = DocBuf::new();
        // Where the TERMINAL `=>`→body gap opens. The walk hands each head the gap before
        // it; the last head's own `=>` closes the one before the body, which no head
        // consumes — so it is tracked here and emitted by the body part below.
        let mut terminal_gap_start = span.start;
        // The LAST head — the arrow the terminal body belongs to. The hug arm below hands it
        // to the single arrow's own emitter, which asks the arrow-shaped questions
        // ([`Self::arrow_gap_broke_after_run`]: the hug test, the retained-paren gate and the
        // `=>`→body freeze) of exactly the arrow whose `=>` opens the terminal gap.
        let mut terminal_arrow = (head, span);
        let terminal = walk_arrow_chain(head, span, |current, current_span, gap_start| {
            // Each signature is its own group so its params break independently of
            // the chain (prettier wraps each `printArrowFunctionSignature` in a
            // group): when the heads break onto separate lines, the params stay
            // flat unless a single signature genuinely overflows.
            let sig = d.group(self.build_arrow_signature_doc(current, current_span));
            // An INNER arrow is built from its signature here and never routed through
            // `build_expression_doc`, so this is the only place its owned leading comment
            // can be claimed — otherwise it is dropped. The head is not: this whole chain
            // doc is what `build_expression_doc` wraps, and it claims the head's comment
            // there, so claiming it again here would print it twice. The head's leading
            // gap is the enclosing site's for the same reason, which is what `gap_start`
            // being `None` there says.
            let sig = match gap_start {
                None => sig,
                Some(gap_start) => {
                    let sig = self.prepend_owned_leading_comment_at(current_span.start, sig);
                    // The head gap answers the `=>`-glued question exactly as the body gap
                    // does; what differs is only where the run can go. Here the `=>` lives
                    // in the SEPARATOR between two heads, so a glued run rides the gap tail
                    // rather than the following signature — and takes the separator's line
                    // with it, since a `//` is a `line_suffix` and the head behind it must
                    // not render flat onto the comment's line.
                    let mut glued: DocBuf = DocBuf::new();
                    let head =
                        self.push_arrow_gap_glued_head(&mut glued, gap_start, current_span.start);
                    let resume = head.as_ref().map_or(gap_start, |h| h.resume);
                    gap_tails.push(match head {
                        Some(head) => {
                            glued.push(self.arrow_glued_head_break(&head));
                            d.concat(&glued)
                        }
                        None => d.line(),
                    });
                    prepend_leading(
                        d,
                        self.arrow_gap_leading_run(resume, current_span.start),
                        sig,
                    )
                }
            };
            sig_docs.push(sig);
            terminal_gap_start = arrow_token_end(current);
            terminal_arrow = (current, current_span);
        });

        // Prettier's `shouldBreakChain` — a head carrying a return type with params, type
        // parameters, or a non-identifier parameter puts every head on its own line however
        // short the chain is, and (below) denies the ternary terminal its same-line parens.
        // Provably `false` under `AssignmentRhs`, where such a chain never reaches this
        // builder at all — see `should_use_arrow_chain_layout`.
        let should_break_chain = crate::printer::arrow_chain_should_break(head);

        // The heads group is keyed — its own instance, so a chain nested in a parameter
        // default or in the body never answers for this one; its shape depends on
        // the parent context. Either way the terminal `=>` + body are emitted
        // after the group (below), and `indent_if_break` ties the body's indent
        // to this group's break decision. The hung assignment shape is the one arm
        // nothing reads (no body indent, no callee `)`), so it alone is unkeyed.
        let keyed = |id: GroupId| (id.doc(), Some(id));
        let (heads, heads_id) = match context {
            // Assignment-RHS: the inner group joins ALL heads with ` =>` + line so
            // they stay on one line when they fit and each drop to their own line
            // otherwise; the outer group wraps `indent([softline, inner])`, so
            // when the chain doesn't fit on the `=` line its leading softline
            // breaks (newline after `=`) and indents the heads one level. The
            // enclosing fluid assignment marker stays flat — the break-after-`=`
            // is this softline.
            ArrowChainContext::AssignmentRhs { leading_run } => {
                let inner = d.group(join_arrow_chain_heads(d, &sig_docs, &gap_tails));
                let led = match leading_run {
                    Some(run) => d.concat(&[d.softline(), run, inner]),
                    None => d.concat(&[d.softline(), inner]),
                };
                keyed(d.group_with_id(d.indent(led)))
            }
            // The assignment shape under a seam that already broke and indented: the
            // joined heads alone. The body below takes no `indent_if_break` either — it
            // already stands inside the seam's indent with the heads.
            ArrowChainContext::AssignmentRhsHung => (
                d.group(join_arrow_chain_heads(d, &sig_docs, &gap_tails)),
                None,
            ),
            // Callee: the assignment shape's joined heads under one indent, behind a
            // leading softline that opens the callee's parens — prettier's
            // `group(indent([softline, group(join(heads), {shouldBreak})]), {shouldBreak:
            // !shouldPutBodyOnSameLine})`. The closing softline is emitted after the body
            // (below), keyed on this same group.
            ArrowChainContext::Callee => {
                let joined = join_arrow_chain_heads(d, &sig_docs, &gap_tails);
                let inner = if should_break_chain {
                    d.group_break(joined)
                } else {
                    d.group(joined)
                };
                keyed(d.group_with_id_break(
                    d.indent(d.concat(&[d.softline(), inner])),
                    !self.arrow_chain_body_stays_on_head_line(
                        terminal,
                        terminal_gap_start,
                        should_break_chain,
                    ),
                ))
            }
            // Call-arg/binaryish: progressive indent. The first head stays on the
            // current line; the rest indent one level and each drop to their own
            // line when the group breaks. Mirrors prettier's
            // `group([sig0, " =>", indent([line, join([" =>", line], rest)])])`.
            // `None` — prettier's default `group(indent(join(heads)))` — renders the
            // same: the first head already sits on the line, so the indent reaches only
            // the rest.
            ArrowChainContext::CallArgOrBinaryish | ArrowChainContext::None => {
                // `split_first` is always `Some` here — a curried chain has ≥2
                // heads — but matching avoids a panic path; the `None` arm falls
                // back to the assignment-style joined group.
                let heads_doc = match sig_docs.split_first() {
                    Some((&sig0, rest)) => {
                        // The first gap's tail is emitted here rather than by the join —
                        // it is the one that carries the indent — so the join sees the
                        // tails from the second gap on.
                        let first_tail = gap_tails.first().copied().unwrap_or_else(|| d.line());
                        let rest_joined =
                            join_arrow_chain_heads(d, rest, gap_tails.get(1..).unwrap_or(&[]));
                        d.concat(&[
                            sig0,
                            d.text(" =>"),
                            d.indent(d.concat(&[first_tail, rest_joined])),
                        ])
                    }
                    None => join_arrow_chain_heads(d, &sig_docs, &gap_tails),
                };
                // Prettier's `shouldBreak: shouldBreakChain` on the same group. Only this
                // arm passes it: `AssignmentRhs` never sees a triggering chain (see
                // `should_use_arrow_chain_layout`, where the assignment site owns the break).
                keyed(d.group_with_id_break(heads_doc, should_break_chain))
            }
        };

        // The terminal body (`=> body`) is wrapped in `indent_if_break` keyed on
        // the heads group: when the heads broke onto their own indented lines, the
        // body sits at the heads' indent level too (so a block/object body's own
        // content lands one level deeper); when the heads stayed on the `=` line,
        // the body keeps the base indent. Mirrors prettier's
        // `indentIfBreak(bodyDoc, { groupId: chainGroupId })`.
        // ⚠️ **The terminal `=>`→body gap is answered by the SAME emitters the default arrow
        // layout's `=>`→body arms use**, so the gap and body print as they would on a single
        // arrow with the same gap and body — modulo this layout's own head indent, which is
        // the only thing it owns. Every body kind routes there: a BLOCK body hands the whole
        // gap to [`Self::build_arrow_block_body`] and a HUG-eligible one to
        // [`Self::arrow_hug_body_doc`], the two arms the single arrow prints through; the
        // ternary and normal-expression arms below reassemble the body (they own the chain's
        // hanging `line`) and so ask the gap's questions themselves, one emitter each: a
        // glued run rides the body glued ([`Printer::build_rhs_comments_glued_opt`]), a
        // MULTI-LINE block the body owns is hoisted out of its group
        // ([`Printer::hoisted_owned_value_gap_run_opt`]), and a run the author BROKE AFTER
        // takes the `=` seams' broke-after pair ([`Printer::value_gap_soft_broke_after_run`])
        // — forced onto its own line when the break is paid for
        // ([`Printer::broke_after_run_break_is_forced`]: the body's doc breaks, or the run
        // holds a multi-line block), collapsed to the glued bytes when it is not. Deciding
        // chain-vs-default by predicting that machinery instead is what traded cells between
        // the two layouts on every pass; the only gap still refused the layout is a FROZEN
        // body head ([`Self::terminal_arrow_gap_emitted`]).
        //
        // ⚠️ **Mirroring an arm rather than calling it is what drifts.** The hug arm was a
        // copy of the default's, and its fallback took the SOFT broke-after run where the
        // original takes the glued one, so the run's own forced break landed inside
        // `concat([" ", …])` — no group, no indent — and printed flush at column 0. The block
        // arm was a copy of the glued half alone, so an own-line run welded onto the `=>`
        // line and un-indented the `{`. Both are one call now.
        //
        // ⚠️ **The terminal `=>`→body gap is a VALUE gap, and this is its eighth route into
        // it**, so it owes the same hoist every other value gap reads
        // ([`Printer::hoisted_owned_value_gap_run_opt`]; the default arrow layout asks it in
        // [`Self::build_arrow_expression_body`]). A MULTI-LINE block the body's first token
        // OWNS travels INSIDE the body's doc, where its reprinted `MultilineText` force-breaks
        // the body's own group and a chain body prettier keeps flat explodes. The emit-axis
        // run below cannot see that comment by definition, which is why reading it alone made
        // the layout turn on OWNERSHIP: with the author's redundant parens around the body the
        // comment binds to the `(` instead, the emit axis sees it, the body stays flat — and
        // the next pass, the shell stripped, reaches the owned form and breaks.
        //
        // `or`, never a concat — the hoisted run is this same gap read on the wider (on-page)
        // axis, so emitting both prints every un-owned comment in it twice. A block body owns
        // nothing (ownership is an `Expression` property), so it asks no hoist.
        //
        // ⚠️ Declined for an INJECTED body, the default layout's guard and for its reason: a
        // call printer that pre-built the body doc elsewhere ([`Printer::with_arrow_body_inject`])
        // built it without this suppression, so the comment is already inside it and hoisting
        // would print it twice. The chain reaches that state through an object / array terminal
        // a single-argument hug pre-builds (`prebuild_expand_last_obj_array_body`), which the
        // walk above lands on exactly like any other terminal.
        let body_part = match terminal {
            ast::ArrowFunctionBody::Expression(expr) => {
                let hoisted_run = self
                    .arrow_body_inject
                    .get()
                    .is_none_or(|(span, _)| span != expr.span().start)
                    .then(|| {
                        self.hoisted_owned_value_gap_run_opt(
                            terminal_gap_start,
                            expr,
                            self.needs_parens(expr, ParenContext::ArrowBody),
                        )
                    })
                    .flatten();
                // The glued-or-hoisted run, and — when the author BROKE AFTER it — the run
                // read as the `=` seams read it. Disjoint by construction: the hoist fires
                // only on a run glued through to the body, this one only on a run that is
                // not.
                let glued_run = hoisted_run.or_else(|| {
                    self.build_rhs_comments_glued_opt(terminal_gap_start, expr.span().start)
                });
                let broke_run: Option<CommentVec<'a>> =
                    self.value_gap_soft_broke_after_run(terminal_gap_start, expr.span().start);
                // The run as the reassembling arms take it: the SOFT broke-after form when
                // the author broke after it — the run plus its newline-after `line`, which
                // collapses to the glued bytes flat and holds its own line when this layout's
                // group breaks — else the glued run. The forced half is a shape, not a
                // separator, so each arm asks for it once it holds the body doc that decides
                // it. ⚠️ The hug arm does NOT take this form: its own layout has no group
                // around the gap, so a soft `line` there renders as a bare break at column 0.
                let terminal_run = match &broke_run {
                    Some(run) => {
                        let mut run_parts = DocBuf::new();
                        self.push_leading_run_with_soft_line(&mut run_parts, run);
                        Some(d.concat(&run_parts))
                    }
                    None => glued_run,
                };
                // ⚠️ Every arm that reassembles the body builds it under the hoist's paired
                // suppression, or the hoisted comment is printed twice — the emit and the
                // suppression are one call (`docs/comments.md` §Owned comments).
                let build_body = |build: &dyn Fn() -> DocId| -> DocId {
                    self.build_value_under_hoist(hoisted_run, expr, build)
                };
                if self.has_own_line_post_arrow_comment(terminal_gap_start, expr.span().start) {
                    // A `//`, or a block the author gave a line of its own: the gap breaks,
                    // and it breaks through the default layout's own-line arm — the run the
                    // author GLUED to `=>` keeps that line, the rest resumes below
                    // ([`Self::push_arrow_gap_tail`]). A frozen head never reaches here
                    // ([`Self::terminal_arrow_gap_emitted`]), so the builder's `frozen` is
                    // `None` by construction.
                    let mut gap_parts = DocBuf::new();
                    self.push_arrow_gap_tail(
                        &mut gap_parts,
                        terminal_gap_start,
                        expr.span().start,
                        |resume| {
                            build_body(&|| {
                                self.build_arrow_body_with_comments_doc(
                                    expr,
                                    resume,
                                    expr.span().start,
                                    None,
                                )
                            })
                        },
                    );
                    d.concat(&gap_parts)
                } else if self.arrow_body_hugs(expr) {
                    // Object/array/template/sequence body: hugs the last head, supplies its
                    // own internal indent, and does so however the chain broke — through the
                    // single arrow's own hug arm, so the two cannot part on it. The arrow it
                    // is asked about is the LAST head, whose `=>` opens this gap.
                    let (arrow, arrow_span) = terminal_arrow;
                    self.arrow_hug_body_doc(
                        arrow,
                        arrow_span,
                        terminal_gap_start,
                        expr,
                        hoisted_run,
                        glued_run,
                    )
                } else if self.arrow_body_takes_ternary_pair(expr) && !should_break_chain {
                    // Ternary body: parens when inline, none when broken
                    // (prettier's shouldAddParensIfNotBreak). ⚠️ Prettier gates this
                    // disjunct of `shouldPutBodyOnSameLine` on `!shouldBreakChain`, and
                    // alone among the three — a sequence (`shouldAlwaysAddParens`) and a
                    // hugging body (`mayBreakAfterShortPrefix`) both keep the `=>` line
                    // whatever the chain does. The reason is that this arm's parens exist
                    // only to hold the ternary on ONE line, and a force-broken chain has
                    // already given up on that: the heads are stacked, so the body hangs
                    // bare beneath the last one (`() =>⏎  test ? 1 : 2`) rather than
                    // rendering a delimiter for a rendering that no longer happens.
                    // The run rides INSIDE these layout parens — the side
                    // `build_arrow_body_doc_with_leading` picks for a ternary — so the two
                    // renderings cannot disagree about what the comment leads, and a run
                    // that breaks takes the paren-less arm with the body.
                    //
                    // A run whose break is FORCED takes the break-after-operator form and
                    // the ternary hangs paren-less below it, exactly as the default
                    // layout's ternary arm prints the same gap — including its claim: a
                    // multi-line comment the body owns prints OUTSIDE the ternary's own
                    // group, or its hard break explodes a ternary prettier keeps flat
                    // ([`Printer::build_value_with_outermost_owned_comment`]).
                    let raw_body =
                        build_body(&|| self.build_expression_doc_claiming_outermost(expr));
                    match broke_run
                        .as_ref()
                        .filter(|run| self.broke_after_run_break_is_forced(run, raw_body))
                    {
                        Some(run) => {
                            self.break_after_operator_run_doc(run, expr.span().start, raw_body)
                        }
                        None => {
                            let body_doc = prepend_leading(d, terminal_run, raw_body);
                            if d.will_break(body_doc) {
                                // No own group — the body's line is governed by the outer
                                // chain group below (prettier's `indent([line, bodyDoc])`).
                                d.indent_line(body_doc)
                            } else {
                                d.concat(&[d.text(" "), ternary_body_parens_group(d, body_doc)])
                            }
                        }
                    }
                } else {
                    // Other expression body: hang on the next line when the chain
                    // breaks. No own group — the body's `line` is governed by the
                    // outer chain group below, so the body hangs whenever the heads
                    // break (matching prettier's `indent([line, bodyDoc])` inside
                    // the outer `group([…])`), not on an independent fit check.
                    //
                    // A run whose break is FORCED takes the break-after-operator form, the
                    // default layout's normal-expression arm over the same gap — its own
                    // hardline, so it carries the break rather than reading this layout's
                    // group.
                    let forced = broke_run.as_ref().and_then(|run| {
                        let body_doc = build_body(&|| self.build_arrow_body_doc(expr));
                        self.broke_after_run_break_is_forced(run, body_doc)
                            .then(|| {
                                self.break_after_operator_run_doc(run, expr.span().start, body_doc)
                            })
                    });
                    match forced {
                        Some(doc) => doc,
                        None => d.indent_line(build_body(&|| {
                            self.build_arrow_body_doc_with_leading(expr, terminal_run)
                        })),
                    }
                }
            }
            // A BLOCK body hands the whole gap to the single arrow's own block-body arm —
            // the freeze, the own-line route ([`Self::push_arrow_gap_tail`], whose `//` keeps
            // its line and drops the `{` below it) and the glued-comment route, all in one
            // call. Read on its own the gap looked glue-only, and the glued half copied here
            // welded an own-line run onto the `=>` line with the `{` left flush behind it.
            ast::ArrowFunctionBody::BlockStatement(block) => {
                let mut block_parts = DocBuf::new();
                self.build_arrow_block_body(&mut block_parts, block, terminal_gap_start);
                d.concat(&block_parts)
            }
        };

        // Outer group, mirroring prettier's `printArrowFunction` return
        // (`group([group(signaturesDoc, {id}), " =>", indentIfBreak(bodyDoc)])`).
        // The body's hanging `line` is governed by THIS group, so a non-hugging
        // body hangs whenever the chain doesn't fit — even when the body itself is
        // short — while the nested heads group makes its own break decision.
        // A callee's parens close on their own line when the heads broke — prettier's
        // `ifBreak(softline, "", { groupId: chainGroupId })`.
        let close = match heads_id {
            Some(id) if context == ArrowChainContext::Callee => {
                d.if_break_with_id(d.softline(), d.empty(), id)
            }
            _ => d.empty(),
        };
        let body_part = match heads_id {
            Some(id) => d.indent_if_break(body_part, id),
            None => body_part,
        };
        d.group(d.concat(&[heads, d.text(" =>"), body_part, close]))
    }

    /// Prettier's `shouldPutBodyOnSameLine` for a chain's terminal body, as
    /// [`Self::build_arrow_chain_doc`]'s body arms answer it: a block, a hugging body
    /// ([`Self::arrow_body_hugs`]) and — unless the chain is force-broken — a ternary keep
    /// the last head's line; an own-line comment in the `=>`→body gap denies all of them.
    ///
    /// Read by the callee shape alone, where a body that must hang forces the callee's
    /// parens open.
    fn arrow_chain_body_stays_on_head_line(
        &self,
        terminal: &ast::ArrowFunctionBody<'_>,
        terminal_gap_start: u32,
        should_break_chain: bool,
    ) -> bool {
        let body_start = terminal.span().start;
        if self.has_own_line_post_arrow_comment(terminal_gap_start, body_start) {
            return false;
        }
        match terminal {
            ast::ArrowFunctionBody::BlockStatement(_) => true,
            ast::ArrowFunctionBody::Expression(expr) => {
                self.arrow_body_hugs(expr)
                    // A conditional body a comma-list region leaves bare stays on the
                    // head line too: the line is the one the pair would have held it on.
                    || (!should_break_chain
                        && matches!(
                            expr.kind,
                            ast::ExpressionKind::ConditionalExpression(_)
                        )
                        && !has_leftmost_arrow_body_parens(expr))
            }
        }
    }

    /// Build doc for return type annotation in arrow function context
    /// Union return types get special handling when the signature breaks:
    ///
    /// Flat: (): A | B | C =>
    /// Break: ):
    ///            | A
    ///            | B
    ///            | C =>
    ///
    /// Function types as return types get wrapped in parentheses for disambiguation:
    /// `(x: T): ((y: T) => U) =>` not `(x: T): (y: T) => U =>`
    fn build_arrow_return_type_doc(
        &self,
        annotation: &ast::TSTypeAnnotation<'_>,
        params_start: Option<u32>,
    ) -> DocId {
        // One depth-tracked close-`)` scan feeds both `)`→`:` questions below.
        let close_paren_after = self.return_type_close_paren(params_start, annotation.span.start);
        // An alone-on-line format-ignore directive in the `)`→`:` gap freezes the whole
        // `: type` annotation and keeps its own line — before the function-type paren
        // wrapping below, which would rebuild a frozen type from parts.
        if let Some(frozen) = self.build_frozen_return_type_doc(close_paren_after, annotation) {
            return frozen;
        }
        // Preserve a block comment between `)` and the return type `:`
        // (`(x) /* c */ : T => ...`); prettier adds a space before `:`.
        let comment_prefix = self
            .build_close_paren_to_return_type_comments(close_paren_after, annotation.span.start);

        // Function types need parentheses to disambiguate from the arrow's `=>`
        // (`(x: T): ((y: T) => U) =>`, never `(x: T): (y: T) => U =>`). The pair is the
        // POSITION's, not the annotation's, so it rides the ordinary return-type emitter
        // as an `AnnotationParens::ArrowReturn` rather than a hand-rolled
        // `": (" + type + ")"`. That reassembly was hazard 4: it ran no gap lookup, so
        // every comment in the `:`→type gap and in the authored shell — `(x: T): /* c */
        // ((y: T) => T)`, `(x: T): (/* c */ (y: T) => T)`, `(x: T): ((y: T) => T /* c */)`
        // — reached no emitter and was DROPPED, at the one return-type position that has
        // no comment-aware twin to fall back to.
        let inner_type = unwrap_parenthesized(annotation.type_annotation);
        if matches!(inner_type, ast::TSType::Function(_)) {
            return self.prepend_opt(
                comment_prefix,
                self.build_arrow_return_type_annotation_doc(annotation),
            );
        }

        // Use return type version - only wraps for complex type args (unions/intersections)
        // Simple cases like Promise<void> let params break first
        self.prepend_opt(
            comment_prefix,
            self.build_type_annotation_doc_for_return_type(annotation),
        )
    }

    /// Build doc for arrow params NOT in their own group (outer signature group controls breaking)
    ///
    /// Structure matches prettier's function-parameters.js:
    /// `[typeParams, "(", indent([softline, ...params]), ifBreak(","), softline, ")"]`
    ///
    /// ⚠️ **A paren-less arrow's parameter starts where the ARROW does**, so the arrow's
    /// owned leading comment answers the parameter's position-keyed lookup too and both
    /// claimed it — `/* c */ x => x` printed as `/* c */ (/* c */ x) => x`, at every
    /// position an arrow reaches. The claim belongs to the arrow: the `(` here is
    /// *synthesized*, so pushing the claim down would move the comment inside a paren the
    /// author never wrote (prettier keeps it outside too — `/* c */ (x) => x`). The
    /// parameter declines through [`Self::with_owned_comment_claimed_above`], whose mark is
    /// scoped to this list so a nested arrow in the body still claims its own.
    fn build_arrow_params_doc_ungrouped(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
    ) -> DocId {
        // The trailing boundary stops at `)`, not at the return type or the body:
        // comments between `)` and `=>` belong to the arrow printer
        // ([`Self::append_pre_arrow_comments`]).
        let build = || {
            // A lone parameter written bare inside a comma-list region prints as written
            // (`Printer::region_param_is_bare`). It is an identifier with no annotation —
            // the only bare parameter the grammar admits — so its doc is the whole list,
            // and every comment around it is the arrow's: before it the arrow's own, after
            // it the pre-`=>` gap's.
            if self.region_param_is_bare(arrow, span)
                && let [param] = arrow.params
            {
                self.test_call_flat_params.set(false);
                return self.build_function_parameter_doc(param);
            }
            self.build_params_doc_with_comments(
                arrow.params,
                arrow.params_start,
                self.arrow_params_end(arrow),
            )
        };
        match bare_param_sharing_arrow_start(arrow, span) {
            Some(start) => self.with_owned_comment_claimed_above(start, build),
            None => build(),
        }
    }

    /// Emit an async arrow's `async` keyword and the gap between it and the head of
    /// its parameters — the type-parameter `<`, the params `(`, or a bare single
    /// parameter's own start.
    ///
    /// A comment there is kept where the author wrote it (prettier relocates it into
    /// the body, into the parameter list, or not at all, keyed on which of the three
    /// heads follows — see `docs/conformance_prettier_ts_comments.md` §Comment
    /// relocation). Nothing else prints the gap, so an emitter here is what keeps the
    /// comment from being dropped.
    ///
    /// Only a **single-line block** comment can occupy the gap: every other kind puts
    /// a line terminator between `async` and the parameters, which
    /// `AsyncArrowFunction : async [no LineTerminator here] ArrowFormalParameters`
    /// forbids and the parser rejects. The shared keyword-gap emitter handles the
    /// line-comment shapes anyway rather than assuming that stays true.
    ///
    /// The gap is scanned from the arrow's own span start rather than from a computed
    /// end of the `async` token: the keyword cannot contain a comment, so the two
    /// ranges hold the same comments and this one needs no arithmetic on a keyword
    /// position. (An async arrow's span starts at `async` — the `<T>async (…)` graft
    /// acorn admits is a type assertion to tsv and does not parse.)
    pub(crate) fn push_async_arrow_head(
        &self,
        parts: &mut DocBuf,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
    ) {
        if !arrow.r#async {
            return;
        }
        let d = self.d();
        parts.push(d.text("async"));
        let head_start = arrow
            .type_parameters
            .as_ref()
            .map(|tp| tp.span.start)
            .or(arrow.params_start)
            .or_else(|| arrow.params.first().map(|p| p.span().start))
            .unwrap_or_else(|| arrow.body.span().start);
        parts.push(self.build_keyword_to_name_comments(span.start, head_start));
    }

    /// Where an arrow's **parameter list** ends — just past its `)`, or, for a lone
    /// unparenthesized parameter, at that parameter's own end.
    ///
    /// **The one spelling of that bound**, shared by the three readers that must agree on
    /// it: the parameter-list emitter ([`Self::build_arrow_params_doc_ungrouped`]'s
    /// `trailing_comments_end`, and through it the per-parameter
    /// [`Self::param_trailing_end`]), the force-break gate over that emitter
    /// ([`Self::arrow_trailing_param_comment_forces_break`]), and the signature end
    /// ([`Self::arrow_signature_end`]). A second derivation is how the gate and the emitter
    /// come to disagree about which comments are in the list — the gate opening a list for
    /// a comment no emitter there claims, or the pre-`=>` emitter reaching back over one
    /// the list already printed.
    ///
    /// `None` only for a shape the grammar does not produce — a parenthesized list whose
    /// `)` cannot be found, or no parens and no parameter — which is why the readers that
    /// need a concrete offset supply their own floor rather than this returning one.
    fn arrow_params_end(&self, arrow: &ast::ArrowFunctionExpression<'_>) -> Option<u32> {
        match arrow.params_start {
            // Find closing `)` to get accurate boundary
            Some(params_start) => self.close_paren_after_params(
                params_start,
                arrow.params.last().map(|p| p.span().end),
                arrow.body.span().start,
            ),
            // No parens (single param arrow like `x => x`) - use param end
            None => arrow.params.last().map(|p| p.span().end),
        }
    }

    /// Where an arrow's **signature** ends — after its return type when it has one,
    /// otherwise after its parameter list. The start of the gap before `=>`.
    fn arrow_signature_end(&self, arrow: &ast::ArrowFunctionExpression<'_>, span: Span) -> u32 {
        if let Some(rt) = &arrow.return_type {
            return rt.span.end;
        }
        // The floor is reached only on the shape [`Self::arrow_params_end`] calls out, and
        // it still lands past the parameter list either way — so the pre-`=>` emitter can
        // never reach back over a parameter's own comment and print it a second time.
        self.arrow_params_end(arrow).unwrap_or_else(|| {
            arrow
                .params_start
                .map_or(span.start, |_| arrow.body.span().start)
        })
    }

    /// Whether a comment after an arrow's last parameter forces its parameter list
    /// **multiline**:
    ///
    /// ```text
    /// (a: string, // comment
    /// ) => {}
    /// ```
    ///
    /// Two readers, both in this module: the curried-arrow arm, which drops the chain onto
    /// separate lines, and [`arrow_signature_has_breaking_comments`], which takes this as the
    /// **trailing half** of the signature-wide question the call printers ask. (Those printers
    /// once called this directly, and asking only about the trailing region is what left a
    /// break-forcing comment in a *leading* parameter, between parameters, or in the
    /// return-type gap hugging where prettier expands.)
    ///
    /// ⚠️ It asks whether the comment **forces a break**, not whether one is merely present.
    /// A single-line block glued to its parameter forces nothing — `(y /* c */) => z` is
    /// legal on one line — so the presence reading broke a layout no comment had opened,
    /// at every reader: `const f = (x) => (y /* c */) => z` split a curried chain three
    /// ways, and `fn((y /* c */) => { … })` (plus its member-chain and `new` twins) lost
    /// prettier's callback hug. The break-forcing kinds are the ones
    /// [`Self::comment_cannot_glue_to_operator`] names — a line comment, a multiline
    /// block, or a block on its own line — and prettier converges with tsv on all three
    /// here, which is what makes the narrowing a pure deletion of the wrong cases.
    /// tsv's own catalog already stated the target
    /// ([conformance_prettier_ts_comments.md](../../../../docs/conformance_prettier_ts_comments.md)
    /// §Comment relocation: the sanctioned divergence is the *multiline* block's, and a
    /// single-line block "forces nothing and hugs everywhere in both").
    ///
    /// ⚠️ **The narrow region is what makes the own-line kind safe to ask about**, and that is
    /// the whole reason this is not folded into [`arrow_signature_has_breaking_comments`].
    /// Own-line-ness is manufactured by breaking (see
    /// [`Printer::range_has_layout_stable_break_forcing_comment`]) — but only for a comment the
    /// break can move to a line start. A comment *after the last parameter* stays glued to that
    /// parameter however the list breaks, so here, and only here, the question is stable. The
    /// signature-wide predicate reads on past [`Self::arrow_params_end`] to the `=>` precisely
    /// because it drops the own-line disjunct when it does.
    ///
    /// ⚠️ Bounding it at [`Self::arrow_params_end`] is also what keeps the *presence* reading's
    /// old over-reach from returning: `fn((a) /* c */ => { … })`, `fn((a): T /* c */ => …)` and
    /// `fn((a): /* c */ T => …)` each lost prettier's hug when this swept the return type and the
    /// signature→`=>` gap. The break-forcing question would not fire on those glued blocks today,
    /// but the bound states the intent rather than relying on the kind test to cover for it.
    ///
    /// A `Printer` method rather than one more predicate in `calls/arg_predicates.rs`: it needs
    /// the comment table, and it owns its own bound, so no call site can hand it a different
    /// one.
    fn arrow_trailing_param_comment_forces_break(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
    ) -> bool {
        self.trailing_param_comment_forces_break(arrow.params, self.arrow_params_end(arrow))
    }

    /// [`Self::arrow_trailing_param_comment_forces_break`] for a `function` expression — the
    /// same question about the same region, differing only in how the `)` is located (a
    /// `function`'s parameter list always has parens, so there is no bare-parameter case).
    ///
    /// Its one reader is [`function_signature_has_breaking_comments`], the `function` half of
    /// the callback-hug refusal. It exists because that hug **asks one question regardless of
    /// the callee's shape** and the arrow twin was gated while this was not, so a `function`
    /// callback whose signature is forced to break kept the hug where the arrow refused it —
    /// `fn(function (y // c⏎) { … })` against `fn((y // c⏎) => { … })`, one arm apart in the
    /// same builder (`docs/comments.md`, and the standing
    /// two-parallel-call-argument-printers hazard).
    ///
    /// ⚠️ Prettier splits here and tsv deliberately does not: it expands only when the last
    /// parameter is a **bare identifier**, and hugs once that parameter carries a type
    /// annotation or a default. That is not a layout rule — it falls out of which node the
    /// comment attached to (`handle-comments.js`'s last-function-arg handler fires on an
    /// `Identifier` preceding node, and an annotation puts the type node there instead), so
    /// tsv answers uniformly and catalogs the annotated case
    /// ([conformance_prettier_ts_comments.md](../../../../docs/conformance_prettier_ts_comments.md)
    /// §Comment relocation).
    ///
    /// ⚠️ **`new` is deliberately NOT on this rule.** Prettier hugs a `function` argument under
    /// `new` uniformly — annotated or not — so there is no incoherence there to correct, and
    /// tsv already matches it on both kinds. The uniformity this predicate buys is over the
    /// *callback kind*, not over every construct that can hold one.
    fn function_trailing_param_comment_forces_break(
        &self,
        func: &ast::FunctionExpression<'_>,
    ) -> bool {
        self.trailing_param_comment_forces_break(
            func.params,
            self.find_closing_paren(func.params_start, func.body.span.start),
        )
    }

    /// The shared core of the two predicates above: whether a comment between the last
    /// parameter and the list's `)` forces that list multiline. Split so the *question* is
    /// stated once and only the **bound** derivation differs per callable — two copies of the
    /// break-forcing test is exactly how the arrow's readers and the `function`'s came to
    /// disagree in the first place.
    fn trailing_param_comment_forces_break(
        &self,
        params: &[ast::Expression<'_>],
        params_end: Option<u32>,
    ) -> bool {
        let (Some(last_param), Some(params_end)) = (params.last(), params_end) else {
            return false;
        };
        self.comments_to_emit_between(last_param.span().end, params_end)
            .any(|comment| self.comment_cannot_glue_to_operator(comment))
    }

    /// Append the comments an author wrote between an arrow's signature and its `=>`
    /// (`(x) /* c */ =>`), returning `sig` untouched when that gap is empty — the
    /// overwhelmingly common case, which costs one span search and no doc node.
    ///
    /// ⚠️ **One gap, one emitter.** Every call-argument state reassembles an arrow as
    /// signature + `" =>"` + body without routing it through
    /// [`Self::build_arrow_doc`](Self::build_arrow_doc), so a gap those states don't ask
    /// about is a gap **nobody** prints (`docs/comments.md` hazard 4). That dropped the
    /// comment outright in `fn((x) /* c */ => call(x))`, `new Comp(…)` and the
    /// return-type spelling alike — at every reassembly site — while the plain arrow and
    /// the member chain printed it, which is what made the loss look context-dependent
    /// rather than structural.
    ///
    /// Only block-shaped payloads can occur here: `=>` is preceded by
    /// `[no LineTerminator here]`, so a `//` in this gap is a parse error, not a layout
    /// question.
    pub(in crate::printer) fn append_pre_arrow_comments(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        arrow_span: Span,
        sig: DocId,
    ) -> DocId {
        let arrow_pos = arrow.arrow_token;
        // The gap this prints starts at the signature end, and locating that costs a
        // depth-tracked `)` scan ([`Self::arrow_params_end`]) — for a bound that is only
        // ever the floor of this emptiness test, which almost always answers "nothing
        // here". Nothing can sit in the gap without also sitting in the arrow's own span,
        // so an empty WIDER range settles it and the scan never runs; the exact floor is
        // derived only once a comment is known to be somewhere ahead of `=>`. Same axis
        // on both queries, so the widening can only over-approximate.
        if !self.has_comments_to_emit_between(arrow_span.start, arrow_pos) {
            return sig;
        }
        let sig_end = self.arrow_signature_end(arrow, arrow_span);
        if !self.has_comments_to_emit_between(sig_end, arrow_pos) {
            return sig;
        }
        let d = self.d();
        let mut parts: DocBuf = smallvec![sig];
        for comment in self.comments_to_emit_between(sig_end, arrow_pos) {
            parts.push(d.text(" "));
            parts.push(self.build_comment_doc(comment));
        }
        d.concat(&parts)
    }

    /// Build just the arrow function signature (async + type params + params + return type)
    /// WITHOUT the ` =>` and body. Used by call printer for expand-last-arg pattern.
    ///
    /// This is extracted from `build_arrow_doc_wrapping` to support the special case
    /// where call expressions need to build arrows with conditional parens around the body.
    pub(crate) fn build_arrow_signature_doc(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
    ) -> DocId {
        let d = self.d();
        if !arrow.r#async && arrow.type_parameters.is_none() {
            // No head at all — the common arrow — so the signature IS its tail: no
            // buffer, and no separator ahead of it.
            return self.build_arrow_signature_tail_doc(arrow, span);
        }
        let mut parts = DocBuf::new();

        self.push_async_arrow_head(&mut parts, arrow, span);

        // Type parameters: always their own group so they break independently of
        // the rest of the signature (Prettier's printTypeParameters semantics) —
        // which is what `_wrapping` is, so an arrow shares the declaration printer
        // rather than restating its layout. A hand-copied twin lived here and emitted
        // only its children's docs, so every block comment in the list's own gaps was
        // DROPPED (`<T /* c */, U>` → `<T, U>`, and the three sibling positions) —
        // hazard 4, masked by the line-comment arm routing to the comment-aware
        // builder, which is why only a `//` survived.
        if let Some(tp) = &arrow.type_parameters {
            parts.push(self.build_type_parameter_declaration_doc_wrapping(tp));
        }

        // The signature TAIL — parameters plus return type — belongs to the `>`→`(` gap's
        // emitter, not to `parts`: a `//` in that gap drops the whole tail to a continuation
        // line, which it can only do while holding it.
        let tail = self.build_arrow_signature_tail_doc(arrow, span);

        self.append_signature_head_gap_comments(
            &mut parts,
            self.type_params_paren_gap(arrow.type_parameters.as_ref()),
            None,
            tail,
        );

        d.concat(&parts)
    }

    /// An arrow signature's tail — its parameters, plus its return type when it has one.
    fn build_arrow_signature_tail_doc(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
    ) -> DocId {
        let params_doc = self.build_arrow_params_doc_ungrouped(arrow, span);
        match &arrow.return_type {
            Some(return_type) => self.d().concat(&[
                params_doc,
                self.build_arrow_return_type_doc(return_type, arrow.params_start),
            ]),
            None => params_doc,
        }
    }

    /// Check if any param has a trailing line comment or own-line block comment.
    ///
    /// The last param's arm reads own-line-ness from the SOURCE
    /// ([`Printer::block_comment_owns_its_line`] with `item_follows: false` — no item is
    /// left to lead, so the `)` sharing the comment's line is not glue and the predicate
    /// reduces to its leading half). Anchoring it on the param's line instead called a
    /// comment glued to the list's own comma own-line and opened a list that fits
    /// (`docs/comments.md` §Own-line-ness is a SOURCE question). Paired with
    /// [`Self::build_trailing_gap_comments`], which the last param's arm of
    /// `build_function_params_doc` emits that region through: it trails exactly the comments
    /// this does not force a break for.
    fn has_trailing_line_comment_in_params(
        &self,
        params: &[ast::Expression<'_>],
        trailing_comments_end: Option<u32>,
    ) -> bool {
        params.iter().enumerate().any(|(i, param)| {
            // The PRINTED end, the same anchor the loop's trailing arms claim from: a `//`
            // inside a stripped-paren shell (`a = (1 // c⏎)`) is in the gap they emit, so a
            // gate that starts past the shell lets that comment defer out of a list that
            // never breaks — past the `)` and the body, swallowing whatever follows.
            let param_end = param.printed_end();
            let trailing_end = self.param_trailing_end(params, i, trailing_comments_end);
            if self.has_line_comments_between(param_end, trailing_end) {
                return true;
            }
            // For the last param, also check for own-line block comments before `)`
            i == params.len() - 1
                && self.has_own_line_block_comment_before_closer(param_end, trailing_end)
        })
    }

    /// Where the trailing region after `params[index]` ENDS: the next param's printed
    /// start ([`Self::param_start_with_decorators`]), or — for the last param — the
    /// list's trailing bound. The one spelling of that bound, shared by the emitters in
    /// `build_params_doc_with_comments` and by the force-break gate over them
    /// ([`Self::has_trailing_line_comment_in_params`]), so a comment the gate opens the
    /// list for is the same set the emitters claim.
    ///
    /// A DECORATED next param prints its own decorator region (`build_param_decorators_doc`),
    /// so this bound stops at its first `@`, never at its binding: the region past the `@`
    /// is that builder's to claim, and a trailing scan reaching into it prints the
    /// decorator's comment a second time on the previous param's comma
    /// (`docs/comments.md` §The element-comma seam).
    fn param_trailing_end(
        &self,
        params: &[ast::Expression<'_>],
        index: usize,
        trailing_comments_end: Option<u32>,
    ) -> u32 {
        params.get(index + 1).map_or_else(
            || trailing_comments_end.unwrap_or_else(|| params[index].span().end),
            |next| self.param_start_with_decorators(next),
        )
    }

    /// Build doc for arrow function body expression.
    /// Whether this body hugs the `=>` — [`arrow_body_always_hugs`]'s kinds, minus a body
    /// whose doc OPENS with a hoisted own-line run: a sequence whose leading edge holds an
    /// own-line comment floats it out ahead of its own `(`
    /// (`append_floated_leading_comments`), so the doc is `// c⏎(a, b)` and a hug prints
    /// `=> // c⏎(a, b)` flush — which the reparse reads as the `=>`→body gap's comment and
    /// indents, a second fixed point one pass away. Such a body takes the own-line-comment
    /// arm's break instead (`=>⏎↹// c⏎↹(a, b)`), the same answer every other value seam
    /// gives a hoisted left-spine run (`Printer::left_spine_shell_has_own_line_comment`).
    /// The one predicate all three hug sites read, so they cannot part on it.
    fn arrow_body_hugs(&self, expr: &ast::Expression<'_>) -> bool {
        arrow_body_always_hugs(expr, self.source)
            && !self.left_spine_shell_has_own_line_comment(expr)
    }

    /// An arrow's expression body whose leftmost token takes its own pair — an object's `{`
    /// (read as a block) or a decorated class's `@`, which `ConciseBody` rejects
    /// ([`leftmost_arrow_body_parens_span`]) — built with that pair; `None` for any other body.
    ///
    /// The one seam for it: the whole arrow's body build asks it first, and so does every
    /// call-argument state that reassembles an arrow from its signature and a body it builds
    /// itself ([`Printer::build_arrow_arg_body_doc`]) — a body built past it prints
    /// `(a) =>⏎\t{}.x ? b : c`, which does not reparse.
    pub(in crate::printer) fn build_leftmost_parens_arrow_body_doc(
        &self,
        expr: &ast::Expression<'_>,
    ) -> Option<DocId> {
        let leftmost_span = leftmost_arrow_body_parens_span(expr)?;
        let prev = self
            .arrow_body_leftmost_parens_target
            .replace(Some(leftmost_span));
        let doc = self.build_flat_chain_expression_doc(expr);
        self.arrow_body_leftmost_parens_target.set(prev);
        Some(doc)
    }

    /// [`Self::build_leftmost_parens_arrow_body_doc`] for a body whose leftmost pair sits
    /// INSIDE it (`({}).x ? b : c`, `({}) as T`): `None` as well when the body itself is the
    /// node that takes the pair (a bare object, a bare decorated class) — the call-argument
    /// states print those through their own hug, which adds the pair around the whole body.
    pub(in crate::printer) fn build_inner_leftmost_parens_arrow_body_doc(
        &self,
        expr: &ast::Expression<'_>,
    ) -> Option<DocId> {
        if arrow_body_is_its_own_leftmost_pair(expr) {
            return None;
        }
        self.build_leftmost_parens_arrow_body_doc(expr)
    }

    fn build_arrow_body_doc(&self, expr: &ast::Expression<'_>) -> DocId {
        self.build_arrow_body_doc_with_leading(expr, None)
    }

    /// `build_arrow_body_doc` with a leading comment run placed correctly relative to
    /// whatever parens the body takes.
    ///
    /// The run rides **inside** the ternary's `if_break` parens and **outside** every
    /// other kind. The others are *required* parens (object / assignment
    /// disambiguation), where both formatters keep a leading comment before the `(`;
    /// the ternary's are a layout artifact that vanishes the moment the body breaks, so
    /// a run left outside them would occupy a position that exists in one rendering
    /// only, and the two renderings would disagree about what the comment leads. Inside
    /// is also what lets the authored blank-after-`(` spelling reach its fixed point in
    /// ONE pass, as prettier does, instead of relocating on a second.
    ///
    /// `None` is the no-run case and adds no doc node — this is a hot path.
    fn build_arrow_body_doc_with_leading(
        &self,
        expr: &ast::Expression<'_>,
        leading: Option<DocId>,
    ) -> DocId {
        let d = self.d();
        let prepend = |doc: DocId| prepend_leading(d, leading, doc);
        // Expand-last-arg body reuse: when the enclosing call/new expand-last path has
        // pre-built this exact body (to also compose the break-body state), reuse that
        // DocId instead of rebuilding — rebuilding here *and* separately recurses into
        // itself for `f(lead, x => f(lead, y => …))`, making the doc-node count
        // O(2^depth). See the `arrow_body_inject` field.
        if let Some((span, doc)) = self.arrow_body_inject.get()
            && span == expr.span().start
        {
            return prepend(doc);
        }
        // An arrow body is a value gap (`mark_jsdoc_cast_value_gap`).
        self.mark_jsdoc_cast_value_gap(expr);
        // The node at the arrow body's leftmost position needs parens so the body does not
        // start with a token `ConciseBody` rejects — an object's `{` (read as a block) or a
        // decorated class's `@` ([`leftmost_arrow_body_parens_span`]).
        // Examples: `() => ({}) as T`, `() => ({}).prop`, `() => ({}) && a`, `() => ({}).b++`,
        // `() => (@dec class {}).k`.
        // The span target tells build_expression_doc to wrap exactly that node in parens
        // when reached. Keyed by span (not a bool) so it survives a chain base being
        // rebuilt across conditional-group variants, and never matches a same-shaped node
        // nested deeper (e.g. a call argument). Saved/restored for nested arrows.
        if let Some(doc) = self.build_leftmost_parens_arrow_body_doc(expr) {
            return prepend(doc);
        }

        // Conditional expressions: parens when inline, none when on own line.
        // The primary ternary path is shouldAddParensIfNotBreak in
        // build_arrow_doc_wrapping. This branch handles ternaries reached
        // via other callers (curried innermost arrow, post-arrow comments)
        // where the body always breaks via hardline — if_break selects
        // the break variant (no parens). A body a comma-list region leaves bare takes the
        // standard arm below, which adds no pair a conditional does not need.
        if self.arrow_body_takes_ternary_pair(expr) {
            // A multi-line comment the body owns prints outside the ternary's own group,
            // after the run ([`Printer::build_value_with_outermost_owned_comment`]).
            let body_doc = self.build_expression_doc_claiming_outermost(expr);
            // The leading run rides INSIDE these parens, so the paren decision wraps
            // both — `will_break` asks about the body AND the run.
            let with_leading = prepend(body_doc);
            // A forced break in the body OR in the run mandates the no-parens arm.
            // The run's half is not redundant with the `if_break`: `arena_fits`
            // stops measuring at the first forced newline, so an own-line run's
            // hardline reads as "fits" to the enclosing group, the `if_break`
            // picks its flat arm, and the parens close around content that still
            // breaks (`=> (/* c */⏎a ? …)`) — a form prettier never prints and a
            // second pass cannot hold.
            if d.will_break(body_doc) || leading.is_some_and(|l| d.will_break(l)) {
                return with_leading;
            }
            // Otherwise, use if_break to check enclosing group
            return d.if_break(with_leading, d.parens(with_leading));
        }

        // A sequence body is prettier's other `shouldIndentSequenceExpression` position
        // (with the `return`/`throw` argument): the operands hang inside the parens the
        // sequence prints for itself, `)` dropping to its own line. Claimed here because
        // the expression dispatch below has no parent to read the layout from.
        //
        // ⚠️ **The float-out builder, and that is only safe because a comment in the
        // shell never reaches here.** An arrow body is a VALUE position, so a comment the
        // author wrote between the last operand and a grouping `)` belongs INSIDE the
        // parens the sequence prints (prettier #19263, the `return` argument's rule) —
        // floated out it lands past the pair (`() => (x, (y /* t */))` → `(x, y) /* t */`)
        // and a `//` rides past the statement's `;`. Two gates keep such a body off this
        // arm, and both read the region through one seam
        // ([`Printer::shell_trailing_gap_start`], which is where the LAST OPERAND's own
        // erased shell is accounted for): the default layout's retained-paren arm
        // ([`Self::arrow_body_shell_holds_comments`], which routes it to
        // `build_expression_doc_keep_paren_comments` → the value-position sequence
        // printer), and the chain layout's legality test
        // ([`Self::chain_comment_outside_emitted_regions`], which calls the region
        // unemitted and falls the whole chain through to that same default layout). A
        // third route into this builder would owe the same gate.
        if let ast::ExpressionKind::SequenceExpression(seq) = &expr.kind {
            return prepend(self.build_sequence_doc(seq, expr.span, SeqLayout::Hanging));
        }

        // Standard cases: objects and assignments always need parens.
        //
        // `build_flat_chain_expression_doc`, not `build_expression_doc`: an arrow body is
        // a `shouldNotIndent` position (`node === parent.body && parent.type ===
        // "ArrowFunctionExpression"`, `shouldNotIndent` in `print/binaryish.js`), so its binary chain's
        // continuation lines stay at the body's own column — the `=>` already put the body
        // one level in.
        //
        // ⚠️ **The `=>`→body gap is a value gap, so a MULTI-LINE block the body OWNS is
        // claimed HERE**, outside the body's own group — the CLAIM half of the fallback every
        // value gap takes where the hoist declines ([`Printer::build_gap_value_doc`]; its
        // suppression half reaches this builder one level up, through the body closure the
        // layouts build under the hoist), spelled at this builder because the arrow claims
        // BENEATH the leading run it prepends rather than around it (`docs/comments.md`
        // §Owned comments). The hoist
        // ([`Printer::hoisted_owned_value_gap_run_opt`]) covers a run glued through to the
        // body; a run the author BROKE AFTER routes to a different emitter, and its glued
        // TAIL is owned all the same — claimed by the innermost node, its reprinted
        // `MultilineText` force-breaks a binary / logical / member body both formatters
        // keep flat, while the same comment written ahead of the author's redundant body
        // parens is gap-emitted and leaves it flat: one authoring, two forms, two passes
        // apart. Stated once here, so the default layout and the curried-chain layout —
        // which reaches every body kind through this builder — cannot part on it, and the
        // ternary arm above carries the same rule inside its own pair.
        //
        // The paren arm declines for the hoist's reason: the pair the position prints
        // stands between the comment and the value, so a claim outside it would carry the
        // comment in front of the `(`. A sequence declines on its own (`outermost_claim_child`),
        // and a claim the hoist already made is refused by the shared gate, so the two
        // cannot double-print.
        if self.needs_parens(expr, ParenContext::ArrowBody) {
            prepend(d.parens(self.build_flat_chain_expression_doc(expr)))
        } else {
            prepend(self.build_value_with_outermost_owned_comment(expr, || {
                self.build_flat_chain_expression_doc(expr)
            }))
        }
    }

    /// Build doc for arrow function body with own-line leading comments.
    ///
    /// Called when at least one comment between `=>` and body is on its own line
    /// (line comment or block comment with newline after). The glued-only state takes
    /// [`Printer::build_rhs_comments_glued_opt`] instead — the same shared emitter under
    /// the one glue mode whose extra rule cannot fire here, since an own-line comment is
    /// by definition not glued.
    /// ```typescript
    /// () =>
    ///     /* comment */
    ///     expr
    /// ```
    ///
    /// `frozen` is the `=>`→body freeze the caller resolved. A frozen body prints as its
    /// verbatim slice inside the parens the ARROW-BODY position supplies, so the two forms
    /// agree about the pair — an object body keeps the required pair a brace-less `{` would
    /// otherwise turn into a block, and a sequence keeps its own
    /// ([`Printer::build_frozen_value_doc`]). The layout branches
    /// [`Self::build_arrow_body_doc_with_leading`] picks between are unavailable to a slice
    /// that renders verbatim, and the one they would decide — the ternary's `if_break` pair
    /// — is already settled here: the run this arm emits ends in a hardline, so that pair
    /// takes its break arm and prints nothing.
    fn build_arrow_body_with_comments_doc(
        &self,
        expr: &ast::Expression<'_>,
        sig_end: u32,
        body_start: u32,
        frozen: Option<Span>,
    ) -> DocId {
        // Leading comments: a block comment inline-adjacent to the next comment / the body
        // hugs it with a space; a line comment or own-line block drops to its own line (a
        // line comment must break so it can't absorb the body). Same shape as the
        // RHS-of-`=` leading run, and the same builder the block-body and chain-gap arms
        // take.
        //
        // The run is handed to the body rather than concatenated ahead of it, so it
        // lands on the correct side of whatever parens the body takes — see
        // `build_arrow_body_doc_with_leading`. For every body but a ternary the two are
        // the same bytes; for a ternary the run belongs inside its layout parens.
        let leading = self.arrow_gap_leading_run(sig_end, body_start);
        match frozen {
            Some(frozen) => {
                // A concise body is `[?In]`, so under a `for` header's init the slice owes
                // the ambient pair — and over the SLICE, since a verbatim body has no inner
                // positions to parenthesize a deeper `in` at
                // ([`Printer::wrap_frozen_for_init_in`]). `build_frozen_value_doc` supplies
                // the POSITION's pair from the same `needs_parens` answer, which is what
                // keeps a root `in` body (or an assignment one) at exactly one pair.
                let position_parens = self.needs_parens(expr, ParenContext::ArrowBody);
                let body = self.build_frozen_value_doc(expr, frozen, ParenContext::ArrowBody);
                prepend_leading(
                    self.d(),
                    leading,
                    self.wrap_frozen_for_init_in(expr, frozen, position_parens, body),
                )
            }
            None => self.build_arrow_body_doc_with_leading(expr, leading),
        }
    }

    /// Whether a comment between `=>` and the body forces the body onto its own line —
    /// the arrow's name for [`Printer::comment_hangs_value_after_operator`], which states
    /// the rule and the reasoning for both of its conjuncts.
    ///
    /// A named delegate rather than three inlined calls: the three readers here ask *the
    /// arrow's* question, and the name is what makes them legible next to the arrow's own
    /// geometry half ([`Self::arrow_gap_broke_after_run`]).
    ///
    /// ⚠️ **The `=>` gap is why the shared predicate has its glue conjunct at all.** The
    /// arrow once asked `comment_cannot_glue_to_operator` alone, whose bare `multiline`
    /// fires whether or not the author broke, so a multiline block the author GLUED to
    /// the body (`=> /* line1⏎line2 */ ({ b: 1 })`) read as own-line and dropped the body
    /// below `=>` — tsv moving a comment the author glued, which its own position doctrine
    /// forbids, and alone among the sibling value seams. The rule is body-kind independent
    /// here by construction: a body that does not hug opens below `=>` through the layout,
    /// comment or no comment, so this only ever decides a body that *could* have hugged.
    pub(crate) fn has_own_line_post_arrow_comment(&self, sig_end: u32, body_start: u32) -> bool {
        self.comment_hangs_value_after_operator(sig_end, body_start)
    }

    /// The start of the one comment in `arrow`'s `=>`→`body` gap when it is a single-line
    /// block glued to `=>` with a newline after it — `=> /* c */⏎body`, the comment
    /// prettier separates from the body by a soft line on its first pass and by a hard one
    /// on its second (`printLeadingComment` gives a hard line only with a newline before the
    /// comment too). `None` for any other gap.
    pub(in crate::printer) fn arrow_gap_glued_block_comment(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        body: &ast::Expression<'_>,
    ) -> Option<u32> {
        let gap_start = arrow_token_end(arrow);
        let body_start = body.span().start;
        let mut comments = self.comments_in_source_between(gap_start, body_start);
        let comment = comments.next()?;
        (comments.next().is_none()
            && comment.is_block
            && !comment.multiline
            && !self.has_newline_between(gap_start, comment.span.start)
            && self.has_newline_between(comment.span.end, body_start))
        .then_some(comment.span.start)
    }

    /// The hug arm's half of "does the `=>`→body gap break": `Some(run)` when a block run
    /// glued to `=>` that the author broke AFTER precedes a hug-eligible body — the geometry
    /// [`Self::breaking_value_leading_run`] asks in [`Self::build_arrow_expression_body`]'s
    /// hug arm, plus the two conditions that arm is reached through.
    ///
    /// ⚠️ **It exists so the CALL can ask the arrow's own question.** The gap breaks down two
    /// arms — [`Self::has_own_line_post_arrow_comment`] (a newline BEFORE the comment, or a
    /// line / multiline one) and this one (a newline AFTER it) — and prettier has no such
    /// split: `shouldPutBodyOnSameLine` is one boolean, and the `softline` that lands an
    /// `expandLastArg` call's `)` sits in the same group as the `line` that drops the body
    /// (`trailingSpace` in `print/arrow-function.js`), so the two move together by
    /// construction. tsv's call printers read only the first arm, so a gap broken by this one
    /// dropped the body while `))` stayed glued — and pass 2, now reading the emitted break as
    /// a newline BEFORE, moved the `)`. An F1 2-cycle, not a divergence; pinned by
    /// `calls/arrow_object_body_broke_after_comment` and by three `blanks:audit` shapes.
    ///
    /// The two extra conditions are the arm's preconditions, not this question's: a
    /// **trailing-paren comment** takes the retained-paren arm ABOVE the ladder (which asks
    /// the first arm alone), and a body that does not always hug never reaches the hug arm at
    /// all. `should_hug`'s remaining conjuncts cannot fire here — both require an ARROW body,
    /// and every caller has already walked to the terminal arrow.
    ///
    /// Geometry only: the arm also requires the body doc to `will_break`, which the caller
    /// answers against the body it is about to inject, so no probe builds a doc of its own.
    /// A body that FITS keeps the glued hug in both formatters (`=> /* c */ ({ a: 1 })`).
    pub(crate) fn arrow_gap_broke_after_run(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
        sig_end: u32,
        body_start: u32,
    ) -> Option<CommentVec<'a>> {
        let ast::ArrowFunctionBody::Expression(body) = &arrow.body else {
            return None;
        };
        if !self.arrow_body_hugs(body) {
            return None;
        }
        // The retained-paren arm's own gate, asked through the shared predicate so the two
        // askers cannot drift ([`Self::arrow_body_shell_holds_comments`], whose ⚠️ states why
        // the widened reading is currently unreachable from here). The freeze is resolved the
        // same way the body arm resolves it, over the same `=>`→body gap; asked behind the hug
        // so the scan is paid only where an arm could still be taken.
        let frozen = self.value_head_frozen_span(sig_end, body.span());
        if self.arrow_body_shell_holds_comments(body, span.end, frozen) {
            return None;
        }
        self.broke_after_value_leading_run(sig_end, body_start)
    }

    /// Build a Doc for an arrow function (simple, non-wrapping version for nested contexts)
    pub(super) fn build_arrow_doc(
        &self,
        arrow: &ast::ArrowFunctionExpression<'_>,
        span: Span,
    ) -> DocId {
        // For nested contexts where we don't want independent wrapping decisions,
        // use the wrapping version which will be evaluated in context
        self.build_arrow_doc_wrapping(arrow, span)
    }

    /// Build a Doc for just the function expression signature (type params, params, return type).
    /// Body is printed separately via imperative printer to preserve comments.
    ///
    /// One depth-tracked scan locates the params' close `)`; every boundary derived
    /// from it shares that scan (same contract as `build_callable_signature_doc`).
    /// Returns the doc plus the signature end — where comments before the body
    /// begin: the return type's end when present, otherwise just past the `)`
    /// (falling back to the body start if the paren can't be located).
    fn build_function_expression_signature_doc(
        &self,
        func: &ast::FunctionExpression<'_>,
    ) -> (DocId, u32) {
        let d = self.d();
        let mut sig_parts = DocBuf::new();

        let body_start = func.body.span.start;

        // Type parameters (TypeScript generics): <T, U>
        // Use _wrapping version for width-based line breaking
        if let Some(type_params) = &func.type_parameters {
            sig_parts.push(self.build_type_parameter_declaration_doc_wrapping(type_params));
        }

        // Params + return type in their own group, with the type parameters left OUTSIDE
        // it — the declaration twin's shape, and prettier's: `printFunction` emits
        // `print("typeParameters")` beside `group([parametersDoc, returnTypeDoc])`, never
        // inside it. Grouping all three together made a break forced inside `<…>` break the
        // parameter list along with it (`function <⏎// c⏎T>(⏎x: T⏎)`), which the declaration
        // and class-method paths — the same signature, through the same helper — never did.
        let (sig_doc, sig_end) = self.build_callable_signature_doc(
            func.params,
            func.type_parameters.as_ref(),
            func.return_type.as_ref(),
            func.params_start,
            body_start,
        );
        self.append_signature_head_gap_comments(
            &mut sig_parts,
            self.type_params_paren_gap(func.type_parameters.as_ref()),
            None,
            sig_doc,
        );

        (d.concat(&sig_parts), sig_end)
    }

    /// Build a Doc for function expression body (type params, params, return type, body).
    ///
    /// Used for method shorthand in objects where the key is printed separately.
    /// For standalone function expressions, use `build_function_doc` instead.
    pub(in crate::printer) fn build_function_doc_body(
        &self,
        func: &ast::FunctionExpression<'_>,
    ) -> DocId {
        let d = self.d();
        // sig_end bounds the outer comment detection before the body.
        let (sig_doc, sig_end) = self.build_function_expression_signature_doc(func);

        let mut parts: DocBuf = smallvec![sig_doc];
        self.append_body_with_sig_comments(&mut parts, sig_end, &func.body);
        d.concat(&parts)
    }

    /// Build a Doc for a standalone function expression with width-aware wrapping.
    ///
    /// This includes:
    /// - `async` keyword if present
    /// - `function` keyword
    /// - `*` for generators
    /// - optional name
    /// - type parameters
    /// - parameters and return type
    /// - body
    pub(in crate::printer) fn build_function_doc(
        &self,
        func: &ast::FunctionExpression<'_>,
    ) -> DocId {
        let d = self.d();
        let mut parts: DocBuf = DocBuf::new();

        // `async`, the gap before `function`, the keyword and a generator `*` — the
        // same head the declaration prints. The cursor it returns is where the
        // keyword→name gap starts; reading that gap from `func.span.start` instead
        // let it swallow the `async`→`function` comment and reprint it after the
        // keyword.
        let head_end = self.push_function_keyword_head(
            &mut parts,
            func.span.start,
            func.id
                .as_ref()
                .map_or(func.params_start, |id| id.span.start),
            FunctionHeadModifier::from_async(func.r#async),
            func.generator,
        );

        // Optional function name
        if let Some(id) = &func.id {
            // Comments between keywords and the name (same as FunctionDeclaration)
            parts.push(self.build_keyword_to_name_comments(head_end, id.span.start));
            parts.push(self.build_identifier_doc(id));

            // Comments between name and type params/parens: `function fn1/* c */ <T>()` or `fn1 /* c */()`
            self.push_signature_head_comments(
                &mut parts,
                id.span.end,
                func.type_parameters.as_ref(),
                func.params_start,
            );
        }

        // Space before type params or params if no name: `function <T>` or `function ()`
        // Also extract comments between keyword and next element: `function /* c */ ()`
        // Line comments get hardline to prevent absorbing parens: `function // c\n()`
        if func.id.is_none() {
            let next_start = func
                .type_parameters
                .as_ref()
                .map_or(func.params_start, |tp| tp.span.start);
            // From `head_end`, not from the span start: the `async`→`function` gap is
            // already printed, and re-reading it here printed those comments TWICE.
            parts.push(self.build_keyword_to_name_comments(head_end, next_start));
        }

        // Type params, params, return type, and body (signature_doc handles type params)
        parts.push(self.build_function_doc_body(func));

        d.concat(&parts)
    }

    /// A value-side parameter list item: the freeze-aware layer over
    /// `build_function_parameter_doc`. An alone-on-line format-ignore directive in
    /// parameter `i`'s leading gap freezes the parameter verbatim (Rule A); one written
    /// between its decorators and its binding freezes just the binding. The type-side
    /// twin is `build_function_type_param_item_doc`.
    ///
    /// `list_frozen` is the caller's already-resolved outer freeze
    /// ([`Printer::param_frozen_span`]) rather than a lookup of its own: the caller needs
    /// the same answer for the comment seam's claim anchor, and one lookup shared is what
    /// keeps the doc and the anchor from disagreeing about what was printed.
    fn build_function_parameter_item_doc(
        &self,
        list_frozen: Option<Span>,
        param: &ast::Expression<'_>,
    ) -> DocId {
        if let Some(frozen) = list_frozen {
            return self.build_frozen_span_doc(frozen);
        }
        // A parameter is a list element: a run its default deferred out of a stripped pair
        // flushes at its comma.
        self.build_list_element_doc(param.span().start, || {
            self.build_frozen_param_binding_doc(param)
                // FunctionParameter context for object patterns
                .unwrap_or_else(|| self.build_function_parameter_doc(param))
        })
    }

    /// Shared implementation for building params doc with comment handling
    ///
    /// Used by arrow functions, function expressions, function declarations, and class methods.
    pub(crate) fn build_params_doc_with_comments(
        &self,
        params: &[ast::Expression<'_>],
        params_start: Option<u32>,
        trailing_comments_end: Option<u32>,
    ) -> DocId {
        let d = self.d();
        // A test call's callback keeps its parameter LIST flat at any width — prettier's
        // `isParametersInTestCall` (`print/function-parameters.js`), which returns
        // `["(", ...printed, ")"]`: `", "` separators, no indent, no softlines, and each
        // parameter's OWN doc left breakable. Consumed here, at the top and before any child
        // doc is built, so it reaches this list and nothing under it — a function nested in a
        // parameter default keeps ordinary width-driven params. See the field doc on
        // `Printer::test_call_flat_params`.
        let test_call_flat = self.test_call_flat_params.replace(false);
        if params.is_empty() {
            // Search to the end of source rather than `trailing_comments_end` — that
            // boundary is clamped to the `)` position for non-empty params, which is
            // too tight here (the depth-tracked search must reach the `)` itself).
            return self
                .build_empty_params_with_comments_doc(params_start, self.source.len() as u32);
        }

        // Zero-comment fast gate: one binary search over the whole params window.
        // Every comment sub-query below (the hug/force-break predicates and the
        // per-gap lookups in the build loop) is bounded within
        // [window_start, window_end] — so when no comment lies inside the window, every
        // sub-query is provably empty/false. Skip them all, including the per-gap
        // `find_comma_after` trivia scans, whose results feed only comment placement.
        //
        // **On page**, not to-emit: this gate guards layout decisions (the single-pattern
        // hug, the force-break legs, the blank-line scan's comment-aware bound), and an
        // owned comment still occupies the page for every one of them. An emit-keyed gate
        // here would make an owned comment vanish from a decision it is visibly part of
        // (`Printer::has_comments_on_page_between`). The sub-queries stay emit-keyed —
        // they answer "what must *this* caller print", which is the other question.
        let comments_present = {
            let window_start = params_start.unwrap_or_else(|| params[0].span().start);
            let last_end = params[params.len() - 1].span().end;
            let window_end = trailing_comments_end.map_or(last_end, |end| end.max(last_end));
            self.has_comments_on_page_between(window_start, window_end)
        };

        // Prettier's shouldHugFunctionParameters: single param that's an object/array pattern
        // gets hugged - no breaks added around it, the pattern handles its own expansion.
        // This keeps `({` and `}: Type)` together, letting the pattern's content break:
        //   function fn({
        //       a,
        //       b,
        //   }: Type): void {}
        // NOT:
        //   function fn(
        //       {a, b}: Type,
        //   ): void {}
        //
        // Also applies to parameters with TypeLiteral type annotations like `a?: { b: T }`:
        //   function fn(a?: {
        //       b: T;
        //   }): void {}
        // NOT:
        //   function fn(
        //       a?: { b: T },
        //   ): void {}
        let should_hug_single_pattern = self.hugs_sole_parameter(
            params,
            params_start,
            trailing_comments_end,
            comments_present,
        );

        if should_hug_single_pattern {
            // Hug mode: `(` + param + `)`. An object pattern or an object-literal
            // annotation takes the shared group-less arm
            // (`build_group_less_hugged_param_doc`) so the object breaks before a breakable
            // return type; every other shape hugs its ordinary doc.
            let param_doc = self
                .build_group_less_hugged_param_doc(&params[0], comments_present)
                .unwrap_or_else(|| self.build_function_parameter_doc(&params[0]));
            return d.parens(param_doc);
        }

        // A line comment trailing the opening `(` (`fn( // c`) is kept on the `(`
        // line, matching the function-type / call-signature `(` and the whole
        // open-delimiter family — via the same `delimiter_line_comment_prefix`
        // helper as `build_type_params_multiline_parts`. Prettier relocates it to
        // the first param's own line (function expression / arrow) or floats it
        // past the declaration (function declaration). The pull fires only for a
        // same-line comment forcing expansion, so it always forces the break path
        // below. See conformance_prettier_ts_comments.md §Comment relocation and
        // open_paren_line_comment_prettier_divergence.
        //
        // The gap ends where the first param's doc STARTS PRINTING
        // ([`Printer::param_start_with_decorators`]), not at its binding: a decorated
        // param prints its own decorator region, comments included
        // (`build_param_decorators_doc`), so a gap reaching past the `@` is claimed
        // twice — once here and once by that builder — and one authored comment is
        // printed twice (`docs/comments.md` §The element-comma seam). The leading run
        // this pull partitions against (`build_leading_param_comments`) already stops
        // at the same position, which is why `skip_delim` cannot see, let alone
        // suppress, a comment pulled from inside the decorators.
        let (paren_prefix, paren_pull_pos) = match params_start {
            Some(open) if comments_present => self
                .delimiter_line_comment_prefix(open, self.param_start_with_decorators(&params[0])),
            _ => (None, None),
        };

        // Check if any trailing line comments exist on params
        // If so, we must use hardlines to force the group to break
        let has_trailing_line_comment = comments_present
            && self.has_trailing_line_comment_in_params(params, trailing_comments_end);

        // Check if any leading line comments exist on their own line before params
        // Line comments on their own line also force break
        let has_leading_own_line_comment =
            comments_present && self.has_leading_own_line_comment_in_params(params, params_start);

        // Prettier rule: force break when 2+ params and at least one is TSParameterProperty
        // (has access modifiers like private/public/protected/readonly)
        let should_break_for_param_properties = params.len() > 1
            && params
                .iter()
                .any(|p| matches!(p.kind, ast::ExpressionKind::TSParameterProperty(_)));

        // A blank line the author left between two params forces the list to expand,
        // and the separator emission preserves it — matching prettier and tsv's own
        // object-literal behavior (a bare blank is authorial intent, like one around
        // a comment).
        let has_blank_line_between_params = self.has_blank_line_between_params(params);

        // Force multiline when comments, param-property modifiers, or an author blank
        // line require it.
        // A test call's flat separator outranks the blank-line arm, as it does in prettier
        // (`isParametersInTestCall` is checked BEFORE `isNextLineEmpty`), so an author blank
        // inside the callback's parameter list does not open the list. It does NOT outrank the
        // comment arms: a comment there breaks the list in both formatters.
        let force_break = has_trailing_line_comment
            || has_leading_own_line_comment
            || should_break_for_param_properties
            || (has_blank_line_between_params && !test_call_flat)
            || paren_pull_pos.is_some();
        let flat_list = test_call_flat && !force_break;

        let mut inner_parts = d.pooled_docbuf();
        // The comma closing the PREVIOUS param, carried across the iteration rather than
        // re-scanned: the gap `params[i-1].end → params[i].start` holds exactly one comma,
        // and iteration `i-1` already located it as its own `comma_pos`. Scanning it again
        // as this iteration's `prev_comma_pos` would ask the same source range twice.
        let mut prev_comma_pos: Option<u32> = None;
        // The previous param's claim anchor (`Printer::element_claim_anchor`), carried for
        // the same reason as `prev_comma_pos`: it is one answer about one gap, and the
        // trailing side has already computed it.
        let mut prev_param_end: Option<u32> = None;
        for (i, param) in params.iter().enumerate() {
            let param_start = param.span().start;
            let is_last = i == params.len() - 1;

            // Where this param's leading gap opens: the previous param's CLAIM anchor
            // ([`Printer::element_claim_anchor`]), which its span end overshoots by a
            // stripped-paren shell (`a = (1 /* c */)`) whose interior would then belong to
            // no emitter at all (`docs/comments.md` §The element-comma seam). Carried from
            // the previous iteration rather than recomputed, so the two sides of the gap
            // cannot disagree — in particular about the FREEZE arm, where the anchor stays
            // at the frozen slice's end and a printed-end reading here would re-emit a
            // comment that slice already printed.
            //
            // Every question in this iteration opens here, the blank-line one included: it
            // takes the DISTANCE anchor derived from this position (`element_shell_end`,
            // below), never the raw span end, so the shell is peeled with a comment inside
            // it left measurable.
            let gap_start = prev_param_end.unwrap_or_else(|| {
                // First param: from just after `(`.
                params_start.map_or(param_start, |pos| pos + 1)
            });

            // The three facts that decide which comments lead this param, derived ONCE and
            // shared by the separator and the leading-comment emitter below. They are the
            // whole input to that split, so two derivations of them are two answers — the
            // separator would measure its gap against a boundary the emitter never agrees to.
            // (`prev_comma_pos` is carried from the previous iteration; both consumers sit
            // under `comments_present`, so a comment-free list never locates a comma at all.)
            //
            // The first param excludes any comment already pulled onto the `(`
            // line by `delimiter_line_comment_prefix`, so it isn't emitted twice.
            let skip_delim = if i == 0 { paren_pull_pos } else { None };
            let param_render_start = self.param_start_with_decorators(param);

            // Add separator before non-first params
            if i > 0 {
                // Use hardline when forcing break (trailing line comments or param properties)
                if force_break {
                    // Preserve a blank line the author left before this param's printed
                    // content — prettier keeps one blank line in the expanded list.
                    //
                    // The DISTANCE anchor: the previous param's shell end
                    // (`Printer::element_shell_end`), the same peel every list that shares
                    // the item separator takes (`Printer::push_item_blank_separator`). With
                    // no comment in the shell it lands on the span end, which is where the
                    // break gate (`has_blank_line_between_params`) measures from, so the
                    // gate and this emitter still cannot disagree about a bare blank — and
                    // where they could, a comment in the shell, that comment has already
                    // forced the break on its own.
                    //
                    // The scan stops at this param's content start, and `is_next_line_empty`
                    // steps past the previous param's same-line trailing comment (`a, // x`)
                    // rather than treating it as the boundary, so a blank line *after* it
                    // still counts.
                    let blank_start = self.element_shell_end(gap_start, param_start);
                    let content_start = if comments_present {
                        self.param_content_start(
                            gap_start,
                            param_render_start,
                            prev_comma_pos,
                            skip_delim,
                            param,
                        )
                    } else {
                        param_start
                    };
                    self.push_next_line_empty_hardline(
                        &mut inner_parts,
                        blank_start,
                        content_start,
                    );
                } else if flat_list {
                    inner_parts.push(d.text(" "));
                } else {
                    inner_parts.push(d.line());
                }
            }

            // Add leading comments for this param
            // Use proper line breaks for line comments on their own line
            if comments_present {
                inner_parts.push(self.build_leading_param_comments(
                    gap_start,
                    param_render_start,
                    prev_comma_pos,
                    skip_delim,
                ));
            }

            // A parameter has TWO freeze positions and the item doc takes whichever fired
            // — the list gap first, then the decorators→binding gap. Resolved here rather
            // than inside that builder because the claim anchor below needs the same
            // answer, and the second position is the one an outer-only reading misses.
            let list_frozen = self.param_frozen_span(params_start, params, i);
            inner_parts.push(self.build_function_parameter_item_doc(list_frozen, param));

            // Where this param's doc STOPS PRINTING. Every comment question in this
            // iteration takes it, so the trailing arms and the next param's leading run
            // partition one gap from one anchor.
            let param_end = Self::element_claim_anchor(
                list_frozen.or_else(|| self.param_binding_frozen_span(param)),
                param.printed_end(),
            );

            // Handle trailing same-line comments. One spelling for both arms
            // ([`Self::param_trailing_end`]) — the non-last bound is the next param's
            // printed start, which is also what the force-break gate reads, so the gate
            // and these emitters agree by construction rather than by coincidence.
            let search_end = self.param_trailing_end(params, i, trailing_comments_end);

            // Find this param's separator comma, bounded by `search_end` — the next param's
            // start, or (last param) the end of its trailing range. The bound is what makes
            // one arm serve both: a last param usually has NO comma, and an unbounded scan
            // would run to the next comma anywhere later in the file and read it as this
            // param's separator, relocating an after-comma block comment across it. Same
            // hazard the element-comma collector names (`collect_trailing_comments`).
            // Consumed only by comment placement, so the zero-comment gate skips the scan.
            let comma_pos = comments_present
                .then(|| self.find_comma_in_range(param_end, search_end))
                .flatten();

            if is_last {
                // The LAST param's whole trailing region — its printed end to the `)` — in
                // ONE ordered pass through the shared last-item→closer walk, since no comma
                // is emitted here to split it around. `true`: a `//` in the run defers
                // through `line_suffix` (zero width) and can only be the run's LAST member,
                // so nothing is emitted behind it on that line; the `)` this list is forced
                // open around ends it.
                //
                // The gate over this seam ([`Self::has_trailing_line_comment_in_params`])
                // reads the same source, and must: a gate that forces the break for a
                // comment this emitter trails inline opens the list around nothing.
                if comments_present {
                    inner_parts.extend(self.build_trailing_gap_comments(param_end, search_end));
                }
            } else {
                // The param's same-line **block** comments, split by side of the comma
                // below. Line comments are deliberately not in here: their claim asks the
                // comma as well as the param (`param_trailing_line_comment`), so a shared
                // "same-line run" would read as answering for them too while quietly using
                // the narrower anchor.
                //
                // "Same line" is the gap's anchor-line run ([`Printer::gap_anchor_line_end`]),
                // which FOLLOWS a multi-line block to its closing `*/` line — a bare
                // `is_same_line(param_end, …)` reads a comment glued past that `*/`
                // (`aaaa /* x⏎y */ /* c */,`) as own-line and hands it to the next param's
                // leading run. `leading_param_comments` reads the same split, so the two
                // still partition the gap.
                let anchor_line_end = if comments_present {
                    self.gap_anchor_line_end(param_end, search_end)
                } else {
                    param_end
                };
                let same_line_blocks: CommentVec<'_> = if comments_present {
                    self.comments_to_emit_between(param_end, search_end)
                        .filter(|c| c.is_block && c.span.start < anchor_line_end)
                        .collect()
                } else {
                    CommentVec::new()
                };

                // Block comments BEFORE comma go before comma
                for comment in same_line_blocks
                    .iter()
                    .filter(|c| comma_pos.is_none_or(|pos| c.span.start < pos))
                {
                    inner_parts.push(d.text(" "));
                    inner_parts.push(self.build_comment_doc(comment));
                }

                // Add inter-param separator comma (only between params; the last param
                // gets no trailing comma — trailingComma: 'none').
                inner_parts.push(d.text(","));
                // A stranded after-comma block (on the comma's line, but a newline
                // before the next param) trails the comma — preserving the author's
                // placement, matching call args / declarators (prettier relocates it
                // before the comma). A block hugging the next param leads it instead
                // (as a leading comment). See conformance_prettier_ts_comments.md §Comment relocation.
                if let Some(cp) = comma_pos {
                    let next_start = self.param_start_with_decorators(&params[i + 1]);
                    self.push_stranded_after_comma_blocks(&mut inner_parts, cp, next_start);
                }

                // Line comments trailing this param go after the comma (excluded from
                // width). Block comments AFTER the comma are handled as leading for the
                // next param.
                //
                // Scanned rather than filtered out of `same_line_blocks`: the claim's
                // anchor is the COMMA as well as the param (`param_trailing_line_comment`),
                // and a comment on a comma the author pushed onto its own line is not on
                // the param's line at all. `leading_param_comments` excludes exactly this
                // set, so the two partition the gap.
                if comments_present {
                    for comment in
                        self.comments_to_emit_between(param_end, search_end)
                            .filter(|c| {
                                self.param_trailing_line_comment(
                                    c,
                                    param_end,
                                    anchor_line_end,
                                    comma_pos,
                                )
                            })
                    {
                        inner_parts.push(self.build_trailing_line_comment_doc(comment));
                    }
                }
            }

            prev_comma_pos = comma_pos;
            prev_param_end = Some(param_end);
        }

        // No group - outer signature group controls breaking
        let mut result: DocBuf = smallvec![d.text("(")];
        // A pulled `( // c` comment renders on the `(` line before the break.
        if let Some(prefix) = paren_prefix {
            result.push(prefix);
        }

        if force_break {
            // When forcing break (trailing comments or param properties), use hardlines.
            result.push(d.indent_hardline(d.concat(&inner_parts)));
            result.push(d.hardline());
        } else if flat_list {
            // No indent and no softlines: the list itself offers no break point, exactly as
            // the single-pattern hug above already does. Each parameter's own doc is
            // untouched, so a destructured pattern still expands on its own.
            result.push(d.concat(&inner_parts));
        } else {
            // No trailing comma (trailingComma: 'none').
            result.push(d.indent_softline(d.concat(&inner_parts)));
            result.push(d.softline());
        }

        result.push(d.text(")"));

        d.concat(&result)
    }

    /// Whether any param is led by a comment on its own line — the single answer to "does a
    /// comment force this param list open?", shared by the value-level router
    /// (`build_function_params_doc`) and the type-level one (`function_types`), so the two
    /// cannot disagree about the same gap. See [`Self::has_own_line_comment_between`] for the
    /// per-gap rule.
    ///
    /// The gap opens at the previous param's PRINTED end, like every other gate over this
    /// seam (`docs/comments.md` §The element-comma seam): a comment inside a stripped paren
    /// shell (`a = (1⏎/* c */)`) sits before the span end, so a span-anchored gate calls the
    /// list comment-free while the leading-run emitter prints the comment anyway. The list
    /// then breaks on that comment's own hardline with `force_break` still false — and the
    /// separator, which is the only thing that preserves an author blank, never runs.
    pub(in crate::printer) fn has_leading_own_line_comment_in_params(
        &self,
        params: &[ast::Expression<'_>],
        params_start: Option<u32>,
    ) -> bool {
        for (i, param) in params.iter().enumerate() {
            let search_start = if i == 0 {
                params_start.map_or_else(|| param.span().start, |pos| pos + 1)
            } else {
                params[i - 1].printed_end()
            };

            // Check if there's a line comment on its own line before this param
            if self
                .has_own_line_comment_between(search_start, self.param_start_with_decorators(param))
            {
                return true;
            }
        }
        false
    }

    /// Whether a comment between two params forces the param list to expand.
    ///
    /// A **line** comment always forces it (it runs to end-of-line, so the following param
    /// can't share the line). A **block** comment forces it under the shared classification
    /// ([`Printer::block_comment_owns_its_line`], which carries the argument): either
    /// adjacency keeps it inline, matching prettier, which collapses `a,⏎/* c */ b` and
    /// `a /* c */,⏎b` both back to `a, /* c */ b`.
    ///
    /// A parameter list is the container `docs/conformance_prettier.md` §Comment Position
    /// Philosophy names outright — it flattens when it fits — so this gate exists for the
    /// comment the author gave a line of its own, and for nothing else.
    fn has_own_line_comment_between(&self, start: u32, end: u32) -> bool {
        self.comments_on_page_between(start, end).any(|c| {
            // `end` is the next param's start, so an item always follows; the trailing
            // position past the last param is `has_own_line_block_comment_before_closer`'s.
            !c.is_block || self.block_comment_owns_its_line(c, true)
        })
    }

    /// Whether the author left a blank line between any two consecutive params.
    /// A bare blank is authorial intent (like one around a comment), so it forces
    /// the param list to expand and the separator emission preserves it — matching
    /// prettier. Shared by regular function params and the type-level param lists
    /// (function/constructor types, method/call/construct signatures).
    ///
    /// This gate and the separator that *emits* the blank must answer **one** question:
    /// they both route through [`Printer::is_next_line_empty`]. They did not always — the
    /// gate measured the whole gap while the emitter measured only past the comma, so
    /// `f(a⏎⏎, b)` broke the list and then dropped the blank, and the second pass (no blank
    /// left to force the break) collapsed it again.
    pub(in crate::printer) fn has_blank_line_between_params(
        &self,
        params: &[ast::Expression<'_>],
    ) -> bool {
        params.windows(2).any(|pair| {
            // Measure to the next param's first decorator, not its binding — a
            // decorator written on its own line sits between the two bindings but
            // is not an author blank line.
            self.is_next_line_empty(
                pair[0].span().end,
                self.param_start_with_decorators(&pair[1]),
            )
        })
    }

    /// **to emit**: the comments this gap prints ahead of the param at `param_render_start` —
    /// the ones that lead it, as opposed to those trailing the *previous* param.
    ///
    /// The single definition of that split. Both the leading-comment emitter and the
    /// separator ([`Self::param_content_start`]) read it, so neither can drift from the
    /// other's idea of which comments belong to this param.
    fn leading_param_comments(
        &self,
        start: u32,
        param_render_start: u32,
        prev_comma_pos: Option<u32>,
        skip_delim: Option<u32>,
    ) -> CommentVec<'_> {
        // The previous param's anchor-line run, the same split its trailing arm claims
        // ([`Printer::gap_anchor_line_end`] — it follows a multi-line block to its closing
        // `*/` line, so a comment glued past that `*/` still trails the previous param).
        let anchor_line_end = self.gap_anchor_line_end(start, param_render_start);
        self.comments_to_emit_between(start, param_render_start)
            .filter(|c| {
                // A comment already pulled onto the opening `(` line (first param)
                // must not be re-emitted as a leading comment here.
                if let Some(dpos) = skip_delim
                    && self.comment_on_delimiter_line(dpos, c)
                {
                    return false;
                }
                let Some(comma) = prev_comma_pos else {
                    return true; // First param - keep all comments
                };
                // A stranded after-comma block (on the comma's line, newline before
                // this param) trails the comma — emitted by the loop's
                // `push_stranded_after_comma_blocks`, not led here.
                if c.span.start >= comma
                    && self.is_stranded_after_comma_block(c, comma, param_render_start)
                {
                    return false;
                }
                // A line comment trailing the previous param — on its line, or on the
                // line of the comma that closes it — is emitted by the loop's
                // trailing-line arm, so it never leads this one. The comma reading is
                // what the item reading cannot give: an author who pushed the comma onto
                // its own line (`a⏎, // c⏎ b`) wrote the comment against the comma.
                if self.param_trailing_line_comment(c, start, anchor_line_end, Some(comma)) {
                    return false;
                }
                // Past the prev param's anchor-line run - definitely a leading comment
                if c.span.start >= anchor_line_end {
                    return true;
                }
                // On the prev param's line: only keep block comments after the comma
                // (block comments before the comma are trailing)
                c.is_block && c.span.start >= comma
            })
            .collect()
    }

    /// Whether a line comment in a param's `[param_end, next_start)` gap **trails that
    /// param** — it sits inside the gap's anchor-line run, or on the line of the comma that
    /// closes it. The one statement of that claim, asked by the trailing-line emitter and by
    /// `leading_param_comments`'s exclusion: the two must PARTITION the gap, so a spelling
    /// that drifts either drops the comment or prints it twice.
    ///
    /// `anchor_line_end` is that run's end ([`Printer::gap_anchor_line_end`]), passed in so
    /// both callers hand it the same split the *block* arms partition on. It is not
    /// `is_same_line(param_end, …)`: the run follows a multi-line block to its closing `*/`
    /// line, and a `//` written after that `*/` (`aaaa /* x⏎y */ /* c */ // d⏎,`) is on the
    /// param's rendered line even though it is two source lines below the param's end.
    /// Answering with the bare anchor left it claimed by NEITHER arm — the block arm skips
    /// it for its kind, the leading arm for its line — which is a DROP.
    ///
    /// The **comma** half is what an item-anchored reading cannot give. The comma is
    /// re-emitted structure — the printer pulls it back onto the param's line whatever the
    /// author did with it — so a `//` written after a comma the author pushed onto a line
    /// of its own (`a⏎, // c⏎ b`) belongs to that comma, and reading only the param's line
    /// hands it to the next param's leading run, re-binding it to a param it was never
    /// written against. Block comments are not on this rule: they ask the hug question
    /// instead ([`Printer::is_stranded_after_comma_block`]).
    ///
    /// ⚠️ **At most ONE can trail**, which is why the two anchors alone do not answer it:
    /// the run ends at the first line comment in the gap, and the rest leads the next param
    /// on its own line, as it does in prettier. That stop condition is
    /// [`Printer::gap_emitted_line_comment_before`], shared with the type-side comma
    /// emitter so the two can't disagree about a gap they answer the same way.
    ///
    /// `comma_pos` is the comma the printer **emits**, so this is a NON-LAST param's
    /// predicate only: under `trailingComma: 'none'` a last param's source comma is deleted,
    /// and the anchor's whole argument is that the printer pulls the comma back onto the
    /// param's line. That region belongs to the shared last-item→closer walk
    /// ([`Printer::build_trailing_gap_comments`]), whose
    /// [`Printer::closer_trailing_comment_run`] asks the same question of a `//` (the param's
    /// line, since the comma is not in the output for it to be written against) inside one
    /// ordered pass that also places the block comments.
    fn param_trailing_line_comment(
        &self,
        comment: &ast::Comment,
        param_end: u32,
        anchor_line_end: u32,
        comma_pos: Option<u32>,
    ) -> bool {
        if comment.is_block {
            return false;
        }
        let anchored = comment.span.start < anchor_line_end
            || comma_pos.is_some_and(|comma| {
                comment.span.start >= comma && self.comment_on_comma_line(comma, comment)
            });
        anchored && !self.gap_emitted_line_comment_before(param_end, comment.span.start)
    }

    /// **on page**: where the param at `param_render_start`'s printed content begins in
    /// source — the position a blank-line scan over the gap before it must stop at, so that
    /// a blank line the author left ahead of that content is inside the measured range.
    ///
    /// Three answers, in order: a comment this gap leads with; else the comment the param
    /// OWNS, which prints from inside the param's own doc and so is invisible to the **to
    /// emit** axis above; else the param itself.
    ///
    /// Bounding at the first comment *in source* instead is the subtle wrong answer: that
    /// comment may be the **previous** param's trailing one (`a, // x`), which ends the
    /// previous param's line rather than starting this one's — leaving any blank line
    /// after it inside no one's range, and silently dropped.
    fn param_content_start(
        &self,
        start: u32,
        param_render_start: u32,
        prev_comma_pos: Option<u32>,
        skip_delim: Option<u32>,
        param: &ast::Expression<'_>,
    ) -> u32 {
        self.leading_param_comments(start, param_render_start, prev_comma_pos, skip_delim)
            .first()
            .map(|c| c.span.start)
            .or_else(|| {
                // Guarded to this gap: the lookup is keyed on the param's own span start,
                // which a leading decorator run sits ahead of, so a hit outside
                // `[start, param_render_start)` is not this gap's to measure against.
                self.owned_leading_comment_start(param)
                    .filter(|&p| p >= start && p < param_render_start)
            })
            .unwrap_or(param_render_start)
    }

    /// Build doc for leading comments before a parameter, through the shared
    /// leading-comment emitter ([`Printer::push_leading_comment_run`]) — so every
    /// separator here is prettier's `printLeadingComment`, read of the source around
    /// *that* comment: a space when nothing follows the `*/` on its line, a **soft
    /// `line`** when something precedes the `/*` but not follows it, a hardline only
    /// when the author isolated the comment on a line of its own.
    ///
    /// ⚠️ **The soft `line` is load-bearing and this site once lacked it.** Collapsing
    /// prettier's three separators into space-or-hardline gives one document two fixed
    /// points: a glued run the author gave its own line (`f(⏎/* c1 */ /* c2 */⏎a)`) took
    /// the hardline and forced the list open, while the same run written on the param's
    /// line stayed flat — and in a list broken on WIDTH the space glued the pair to a
    /// param prettier drops below it. One `line` answers both, because it is the only
    /// separator whose rendering follows the list's own group.
    ///
    /// `prev_comma_pos`: if Some, filter out trailing comments for the previous param
    ///
    /// `param_render_start` is where the param's rendered form begins — its first
    /// decorator when it carries parameter decorators, else the binding itself. It
    /// bounds the collection on **both** ends of the concern: only comments *before*
    /// the first decorator are leading param comments (anything interleaved with the
    /// decorators is emitted in place by `with_param_decorators`), and the final
    /// own-line/blank decision measures against it so an own-line decorator between
    /// the last comment and the binding isn't miscounted as an author blank line.
    /// Same decorator-aware anchor as `has_blank_line_between_params`.
    fn build_leading_param_comments(
        &self,
        start: u32,
        param_render_start: u32,
        prev_comma_pos: Option<u32>,
        skip_delim: Option<u32>,
    ) -> DocId {
        let d = self.d();
        let comments =
            self.leading_param_comments(start, param_render_start, prev_comma_pos, skip_delim);
        if comments.is_empty() {
            return d.empty();
        }

        let mut parts: DocBuf = DocBuf::new();
        self.push_leading_comment_run(
            &mut parts,
            comments.iter().copied(),
            param_render_start,
            LeadingGlue::Adjacent,
        );
        d.concat(&parts)
    }

    /// Build a Doc for a class expression (`class …`, named or anonymous).
    pub(in crate::printer) fn build_class_expression_doc(
        &self,
        class_expr: &ast::ClassExpression<'_>,
        class_expr_span: Span,
    ) -> DocId {
        let d = self.d();

        // With a decorated class expression (`@dec class {}`), span.start points
        // at the first decorator's `@`, so derive the first keyword's position
        // from after the decorators (falls back to span.start when undecorated). An
        // `abstract` one (`export default @dec abstract class {}`) leads with that
        // modifier, and the `class` keyword follows it.
        let first_keyword_start = self.find_keyword_after_decorators(
            class_expr.decorators,
            if class_expr.r#abstract {
                "abstract"
            } else {
                "class"
            },
            class_expr_span.start,
        );
        let abstract_end = class_expr
            .r#abstract
            .then(|| first_keyword_start + "abstract".len() as u32);
        let class_keyword_start = abstract_end
            .and_then(|end| self.find_keyword_in_range(end, class_expr_span.end, "class"))
            .unwrap_or(first_keyword_start);

        // Compute heritage positions once (shared with the class-declaration printer).
        let positions = self.class_heritage_positions(
            class_keyword_start,
            class_expr.id.as_ref(),
            class_expr.type_parameters.as_ref(),
            class_expr.super_class,
            class_expr.super_type_parameters.as_ref(),
            class_expr.implements,
        );

        // Heritage layout (shared with the class-declaration printer).
        let layout = self.class_header_layout(
            &positions,
            class_expr.super_class,
            class_expr.super_type_parameters.as_ref(),
            class_expr.implements,
        );

        let mut parts = DocBuf::new();

        // Leading decorators (`@dec class {}`), each on its own line.
        if let Some(dec_doc) = self.build_decorators_doc(class_expr.decorators, first_keyword_start)
        {
            parts.push(dec_doc);
        }

        // `abstract`, with any comment between it and `class` kept inline
        if let Some(end) = abstract_end {
            parts.push(d.text("abstract"));
            if let Some(c) = self.build_inline_comments_between_doc_opt(end, class_keyword_start) {
                parts.push(c);
            }
            parts.push(d.text(" "));
        }

        // 'class' keyword
        parts.push(d.text("class"));

        // Optional class name
        if let Some(id) = &class_expr.id {
            // Comments between `class` keyword and name
            parts.push(self.build_keyword_to_name_comments(class_keyword_start, id.span.start));
            parts.push(self.build_identifier_doc(id));
        }
        // The name→body and `class`→body gaps are NOT emitted here: `header_end` already
        // falls back to the name's end (or the `class` keyword's) when there is no heritage
        // and no type params, so `build_class_header_doc` resolves every class shape's
        // header→`{` gap through the one seam. Emitting them here instead is what made the
        // bare-name and anonymous forms answer that gap differently from their siblings.

        // Type parameters (`class<T>`) and the gap before them — shared with the
        // declaration printer, which is what keeps the anonymous arm's open gap a
        // single hole.
        self.push_class_type_params(
            &mut parts,
            class_expr.type_parameters.as_ref(),
            class_expr
                .id
                .as_ref()
                .map_or(ClassTypeParamsGap::Keyword(class_keyword_start), |id| {
                    ClassTypeParamsGap::Name(id.span.end)
                }),
        );

        // Build heritage docs (shared with the class-declaration printer).
        let extends_doc = self.build_class_extends_doc(
            class_expr.super_class,
            class_expr.super_type_parameters.as_ref(),
            positions.extends_keyword_start,
        );
        let implements_doc = self.build_class_implements_doc(
            class_expr.implements,
            layout.is_group(),
            positions.implements_keyword_start,
        );

        // Assemble the header (group-wrapped); the body is appended outside the
        // group so its hardlines don't affect the header's fit check.
        // Resolved once for the header placement and the body emission, as in the
        // declaration printer.
        let frozen_body = self.gap_frozen_span(positions.header_end, class_expr.body.span);
        let header_doc = self.build_class_header_doc(
            parts,
            &positions,
            extends_doc,
            implements_doc,
            class_expr.implements,
            ClassHeaderOptions {
                body_is_empty: class_expr.body.body.is_empty(),
                body_start: class_expr.body.span.start,
                layout,
                body_frozen: frozen_body.is_some(),
            },
        );

        d.concat(&[
            header_doc,
            self.build_class_body_doc(&class_expr.body, frozen_body),
        ])
    }
}