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
// Loop statement printing: for, for-in, for-of
//
// for-loop header layout (init/test/update clauses with comment placement),
// for-in/for-of left/right printing.
use super::HeadChainGrouping;
use crate::ast::{self, Expression, ExpressionKind, Statement, StatementKind};
use crate::printer::expressions::operators::SeqLayout;
use crate::printer::statements::StatementContext;
use crate::printer::statements::variable::{DeclaratorEqGap, DeclaratorInitInputs};
use crate::printer::{
CommentVec, ContinuationValue, LeadingGlue, ParenContext, Printer, RunLeadingBlank,
needs_parens,
};
use smallvec::smallvec;
use tsv_lang::Span;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::arena::DocId;
use tsv_lang::source_scan::{TriviaProfile, find_char};
/// Span positions for a for loop header
///
/// Groups the optional span positions for init, test, and update clauses
/// to avoid passing many Option parameters.
struct ForHeaderSpans {
open_paren: Option<u32>,
init_start: Option<u32>,
init_end: Option<u32>,
test_start: Option<u32>,
test_end: Option<u32>,
update_start: Option<u32>,
update_end: Option<u32>,
first_semi: Option<u32>,
second_semi: Option<u32>,
close_paren: Option<u32>,
}
impl ForHeaderSpans {
/// The end of the init clause's comment region: the clause itself when present,
/// else its `;`.
///
/// The three region accessors are what keep an ABSENT clause's comments from
/// leaking into the next clause's region. A boundary chained over the absent
/// clauses instead (`init_start.or(test_start).or(update_start)`) reaches past the
/// separators that delimit the slots, so one comment lands in two regions and is
/// printed twice — or, where only the skipped-over region has an emitter, in none
/// and is dropped. The `;` positions are the slot boundaries; every region is
/// bounded by them.
fn init_region_end(&self) -> Option<u32> {
self.init_start.or(self.first_semi)
}
/// The start of the init clause's comment region: just inside the `(`.
fn init_region_start(&self) -> Option<u32> {
self.open_paren.map(|p| p + 1)
}
/// The start of the test clause's comment region: the preceding clause's end when
/// there is one — its `content`→`;` gap belongs to it — else just past that `;`.
fn test_region_start(&self) -> Option<u32> {
self.init_end.or_else(|| self.first_semi.map(|s| s + 1))
}
/// The start of the update clause's comment region. See
/// [`Self::test_region_start`].
fn update_region_start(&self) -> Option<u32> {
self.test_end.or_else(|| self.second_semi.map(|s| s + 1))
}
/// The start of the region that runs to the header's `)` — just past the update
/// clause when there is one, else its whole (empty) slot. Unlike the init and test
/// slots, nothing but `)` terminates this one, so the clause and the gap after it
/// share a single trailing region.
fn update_trailing_start(&self) -> Option<u32> {
self.update_end.or_else(|| self.second_semi.map(|s| s + 1))
}
/// The end of the test clause's comment region: the clause itself when present,
/// else its `;`. See [`Self::init_region_end`].
fn test_region_end(&self) -> Option<u32> {
self.test_start.or(self.second_semi)
}
/// The end of the update clause's comment region: the clause itself when present,
/// else the header's `)`. See [`Self::init_region_end`].
fn update_region_end(&self) -> Option<u32> {
self.update_start.or(self.close_paren)
}
}
/// The C-style `for` header's own parens, located once per statement.
///
/// [`Printer::matching_close_paren`] is a depth-tracked scan across the whole header,
/// so locating the pair once and threading it is the difference between one such scan
/// per `for` and three — the header-end probe, the header builder, and the empty-header
/// builder would each redo it. Every consumer has to agree on the same pair anyway:
/// the `)` is what bounds the header's comment regions, so two callers disagreeing
/// about it would bound them differently.
///
/// Both fields are `Option` because a degenerate header may have no locatable paren;
/// each consumer already carries its own fallback for that.
#[derive(Clone, Copy)]
struct ForParens {
open: Option<u32>,
close: Option<u32>,
}
/// Source positions for a for-in/for-of header
///
/// Groups the resolved header positions to avoid passing many `u32` parameters
/// to the structural-comment check and the two layout builders. Mirrors
/// `ForHeaderSpans` (the C-style `for` header). Built once by
/// `Printer::for_in_of_spans`.
struct ForInOfSpans {
open_paren: Option<u32>,
close_paren: Option<u32>,
left_start: u32,
/// Start of the binding *target*, skipping the declaration keyword (the
/// first declarator's pattern for a `VariableDeclaration` left, the pattern
/// itself for a bare `Pattern` left) — so the keyword→binding gap
/// (`const // c⏎x`) reads as header-structural while the binding pattern's
/// own interior does not. See `get_for_in_of_binding_start`.
binding_start: u32,
left_end: u32,
keyword_pos: u32,
keyword_end: u32,
right_start: u32,
right_end: u32,
}
impl ForInOfSpans {
/// The closing-paren anchor for the iterable→`)` gap scan, falling back to
/// just past the iterable when no `)` is locatable. Kept in one place so
/// every caller derives it identically.
fn close(&self) -> u32 {
self.close_paren.unwrap_or(self.right_end + 1)
}
}
/// Mutable cursor state while laying out an empty `for (;;)` header's comments.
struct EmptyForCursor {
/// A `//` line comment was just emitted: it runs to end-of-line, so the next
/// item must start on a new line.
pending_break: bool,
/// The previously emitted item was a block comment, so a separating space is
/// owed before a following `;`.
prev_block: bool,
}
impl<'a> Printer<'a> {
/// Append `)` + comments + non-block body for for-in/for-of statements — the
/// for-x anchor for the shared header→body emitters, where
/// `append_close_paren_with_comments` is the block-body one (a block body needs no
/// indent, so the two differ only in that).
///
/// The gap's own rules are NOT here: a breaking gap is the body's leading run and
/// goes to [`Printer::push_indented_header_to_body_gap`], exactly as `if` / `while` /
/// the C-style `for` / `do` reach it. This family hand-rolled that arm until it was
/// measured against theirs — it kept the run whole but left it on the `)` line, so a
/// bare `for (k of o) // c⏎fn();` stayed up there where every sibling construct (and
/// prettier) drops it to the body. Only the two arms below are for-x's own.
fn append_close_paren_with_non_block_body(
&self,
parts: &mut DocBuf,
paren_end: u32,
body: &Statement<'_>,
body_ctx: StatementContext,
) {
let d = self.d();
let body_start = body.span().start;
let body_doc = self
.build_statement_head_doc(paren_end, body, || self.build_statement_doc(body, body_ctx));
if !self.has_comments_to_emit_between(paren_end, body_start) {
parts.push(d.text(")"));
if matches!(&body.kind, StatementKind::EmptyStatement(_)) {
// Prettier's `adjustClause` returns `";"` directly for an empty
// body (no leading `line`) → `for (x of y);`, not `for (x of y) ;`.
parts.push(body_doc);
} else {
// Mirror Prettier's `adjustClause`: `indent([line, body])`. The
// enclosing for-in/for-of group (see `build_for_in_of_statement_with_body_doc`)
// breaks on overflow, dropping the body to its own indented line;
// when it fits, `line` is a space → `for (x of y) stmt;`.
parts.push(d.indent_line(body_doc));
}
return;
}
parts.push(d.text(")"));
if self.header_to_body_gap_breaks(paren_end, body_start) {
self.push_indented_header_to_body_gap(parts, paren_end, body_start, body_doc);
} else {
// Nothing forces a break, so by `header_to_body_gap_breaks` every comment in
// the gap is a block already trailing `)` — the partition this arm used to
// build had `own_line` provably empty and `inline_prev` provably the whole
// range, so it is the range. Spelled exactly like the `if`/`while` twin
// (`Printer::build_adjust_clause_with_comments`), which is the same doc:
// `indent(line, c1, " ", …, cn, " ", body)`. adjustClause keeps
// `) /* a */ body` flat, dropping the comment(s) + body to their own indented
// line when the enclosing for-in/for-of group breaks (overflow).
let comment_doc =
self.build_inline_comments_between_doc_no_leading_space(paren_end, body_start);
parts.push(d.indent_line(d.concat(&[comment_doc, d.text(" "), body_doc])));
}
}
/// Locate a C-style `for` header's parens. See [`ForParens`] — call this once per
/// statement and thread the result.
fn for_parens(&self, stmt_start: u32) -> ForParens {
let open = self.find_open_paren_after(stmt_start);
ForParens {
open,
close: open.and_then(|p| self.matching_close_paren(p)),
}
}
/// Build a complete for statement doc including the body
///
/// This includes the body in the doc so the width calculation accounts for ` {`.
fn build_for_statement_with_body_doc(
&self,
stmt: &ast::ForStatement<'_>,
span: Span,
parens: ForParens,
ctx: StatementContext,
) -> DocId {
let d = self.d();
let header_doc = self.build_for_header_doc(stmt, span, parens, None);
if matches!(&stmt.body.kind, StatementKind::EmptyStatement(_)) {
// No space before empty statement: `for (...);` (the ctx is inert — an
// EmptyStatement is bare `";"` with no terminator gap)
d.concat(&[
header_doc,
self.build_statement_doc(stmt.body, ctx.clause_body(false, true)),
])
} else if let StatementKind::BlockStatement(block) = &stmt.body.kind {
// Block body: `for (...) { ... }`
// Note: Unlike for-in/for-of, standard for loops keep empty blocks inline `{}`
d.concat(&[
header_doc,
d.text(" "),
self.build_statement_head_doc(
self.get_for_header_end(stmt, span, parens),
stmt.body,
|| self.build_block_statement_doc(block),
),
])
} else {
// Non-block body. Mirror Prettier's `adjustClause`: the body is
// `indent([line, body])` wrapped with the header in an outer group.
// Flat → `for (...) stmt;`. When the header force-breaks (a comment
// hardline propagates via `will_break`) or the whole thing overflows,
// the outer group breaks and the body drops to its own indented line;
// the inner header group still decides its own flat/break, so a
// width-only overflow keeps the header flat (matching Prettier).
let body_doc = self.build_statement_head_doc(
self.get_for_header_end(stmt, span, parens),
stmt.body,
// `adjustClause` wraps the body in one indent; nothing continues on
// the tail's line.
|| self.build_statement_doc(stmt.body, ctx.clause_body(false, true)),
);
d.group(d.concat(&[header_doc, d.indent_line(body_doc)]))
}
}
/// Get the end position of a for loop header (position after the closing paren)
///
/// `parens.close` is depth-tracked, so redundant parens or parens inside a clause
/// don't yield a premature match; the last clause's end is the fallback when the
/// header has no locatable `)`.
fn get_for_header_end(
&self,
stmt: &ast::ForStatement<'_>,
span: Span,
parens: ForParens,
) -> u32 {
// `map_or_else` so the located-paren path — every well-formed header — costs one map
// and never walks the clause spans for a fallback it discards.
parens.close.map_or_else(
|| {
stmt.update
.as_ref()
.map(|u| u.span().end)
.or_else(|| stmt.test.as_ref().map(|t| t.span().end))
.or_else(|| stmt.init.as_ref().map(|i| self.get_for_init_span_end(i)))
.unwrap_or(span.start + "for ".len() as u32)
},
|p| p + 1,
)
}
/// Build doc for an empty `for (;;)` header that has comments inside the parens.
///
/// Preserves comments in their authored positions — a divergence from prettier,
/// which relocates every comment outside the parens once all three clauses are
/// empty (prettier itself keeps them inline when any clause is non-empty, so its
/// relocation is internally inconsistent). See the
/// `empty_clauses*_comment_prettier_divergence` fixtures.
///
/// The header breaks only where a `//` line comment forces a line end: with
/// block comments alone the whole header stays on one line (`for (/* a */ ;;)`);
/// a line comment drops the rest of the header to the next line, but the `;;`
/// stay together when nothing separates them (`for ( // c⏎\t;;⏎)`). `for_open`
/// is the already-built `for (` prefix (carrying any `for`→`(` keyword comment).
///
/// A *partially*-empty header preserves its empty slots' comments too, but through
/// the ordinary path's [`Self::push_for_empty_slot_comments`] and with the ordinary
/// separators — a slot there sits between real clauses, so it takes the same
/// `softline`/`line` breaks they do. This dedicated emitter exists for the
/// separator rules above, which only make sense when the parens hold nothing else.
fn build_for_empty_with_comments(
&self,
stmt: &ast::ForStatement<'_>,
parens: ForParens,
for_open: DocId,
) -> DocId {
let d = self.d();
let (Some(open), Some(close)) = (parens.open, parens.close) else {
return d.concat(&[for_open, d.text(";;)")]);
};
let (Some(s1), Some(s2)) = self.find_for_semicolons(stmt, open, Some(close)) else {
return d.concat(&[for_open, d.text(";;)")]);
};
// A `//` line comment anywhere in the header runs to end-of-line, so it
// forces the following tokens onto new lines; with only block comments the
// header stays inline.
let breaking = self.has_line_comments_between(open + 1, close);
let mut inner = DocBuf::new();
let mut cur = EmptyForCursor {
pending_break: false,
prev_block: false,
};
// Region before the first `;` is anchored on `(` (a leading block comment
// hugs it: `for (/* a */`); regions after a `;` space-separate block
// comments (`; /* b */`).
self.emit_empty_for_comments(&mut inner, &mut cur, open + 1, s1, open, true);
self.emit_empty_for_semicolon(&mut inner, &mut cur);
self.emit_empty_for_comments(&mut inner, &mut cur, s1 + 1, s2, s1, false);
self.emit_empty_for_semicolon(&mut inner, &mut cur);
self.emit_empty_for_comments(&mut inner, &mut cur, s2 + 1, close, s2, false);
// A `//` forces breaks: indent the body and drop `)` to its own line.
// Block-only headers stay on the single `for (…)` line.
let body = d.concat(&inner);
if breaking {
d.concat(&[for_open, d.indent(body), d.hardline(), d.text(")")])
} else {
d.concat(&[for_open, body, d.text(")")])
}
}
/// Emit the comments of one empty-`for` header region (`[start, end)`) into
/// `inner`, advancing `cur`. `anchor` is the end of the token the region
/// follows (used for same-line classification); `hug` is set for the leading
/// region so a block comment hugs the `(` with no separating space.
fn emit_empty_for_comments(
&self,
inner: &mut DocBuf,
cur: &mut EmptyForCursor,
start: u32,
end: u32,
anchor: u32,
hug: bool,
) {
let d = self.d();
let mut prev = anchor;
let mut first = true;
for comment in self.comments_to_emit_between(start, end) {
if comment.is_block {
if cur.pending_break {
inner.push(d.hardline());
cur.pending_break = false;
} else if !(first && hug) {
inner.push(d.text(" "));
}
inner.push(self.build_comment_doc(comment));
cur.prev_block = true;
} else {
// Line comment: breaks the line after itself (`pending_break`).
if cur.pending_break || !self.is_same_line(prev, comment.span.start) {
inner.push(d.hardline());
} else {
inner.push(d.text(" "));
}
inner.push(self.build_comment_doc(comment));
cur.pending_break = true;
cur.prev_block = false;
}
prev = comment.span.end;
first = false;
}
}
/// Emit one `;` of an empty-`for` header into `inner`, advancing `cur`: a
/// pending line comment forces it to a new line, a preceding block comment
/// owes it a separating space, otherwise it joins the run (`;;`).
fn emit_empty_for_semicolon(&self, inner: &mut DocBuf, cur: &mut EmptyForCursor) {
let d = self.d();
if cur.pending_break {
inner.push(d.hardline());
cur.pending_break = false;
} else if cur.prev_block {
inner.push(d.text(" "));
}
inner.push(d.text(";"));
cur.prev_block = false;
}
/// Build a Doc for the for loop header with wrapping support
///
/// Handles comments in each clause position:
/// ```js
/// for (
/// // before init
/// let i = 0; // inline with init
/// // before test
/// i < 10; // inline with test
/// // before update
/// i++ // inline with update
/// ) {
/// ```
///
/// `keyword_comments` is any `for`→`(` gap comment, already built by the caller;
/// `parens` is the header's paren pair, located once per statement ([`ForParens`]).
fn build_for_header_doc(
&self,
stmt: &ast::ForStatement<'_>,
span: Span,
parens: ForParens,
keyword_comments: Option<DocId>,
) -> DocId {
let d = self.d();
let has_init = stmt.init.is_some();
let has_test = stmt.test.is_some();
let has_update = stmt.update.is_some();
let has_any = has_init || has_test || has_update;
// Build "for" + optional keyword comments + " (" prefix
let for_open = if let Some(kc) = keyword_comments {
// `kc` carries its own trailing space (block) or hardline (line).
d.concat(&[d.text("for"), kc, d.text("(")])
} else {
d.text("for (")
};
let ForParens {
open: open_paren,
close: close_paren_approx,
} = parens;
// The whole paren interior, for the two header-wide gates below. `None` for a
// degenerate header with no locatable parens, where neither gate has a range to
// ask about.
let paren_interior = open_paren.zip(close_paren_approx);
// Check if there are any comments inside the for parens
let has_comments_inside = paren_interior
.is_some_and(|(open, close)| self.has_comments_to_emit_between(open, close));
if !has_any && !has_comments_inside {
// Empty for (;;) with no comments - no wrapping needed
return d.concat(&[for_open, d.text(";;)")]);
}
if !has_any && has_comments_inside {
// Empty for (;;) with comments — preserve them inline where authored
// (divergence from prettier; see empty_clauses*_comment_prettier_divergence).
return self.build_for_empty_with_comments(stmt, parens, for_open);
}
// Determine spans for each part
let (init_end, test_end) = self.for_clause_ends(stmt);
let update_end = stmt.update.as_ref().map(|u| u.span().end);
// Find semicolon positions for proper comment boundary detection.
// The semicolons in `for (init; test; update)` are at specific positions in
// source. Anchored at the clause ends, not `span.start` — see
// `find_for_semicolons`. `open_paren` is only the fallback for an absent init,
// so a header with no open paren to find (already degenerate) keeps the
// previous keyword-relative behavior.
let (first_semi, second_semi) =
self.find_for_semicolons(stmt, open_paren.unwrap_or(span.start), close_paren_approx);
let spans = ForHeaderSpans {
open_paren,
init_start: stmt.init.as_ref().map(|i| match i {
ast::ForInit::VariableDeclaration(d) => d.span.start,
ast::ForInit::Expression(e) => e.span().start,
}),
init_end,
test_start: stmt.test.as_ref().map(|t| t.span().start),
test_end,
update_start: stmt.update.as_ref().map(|u| u.span().start),
update_end,
first_semi,
second_semi,
// The statement's own paren pair, threaded in rather than rescanned — see
// [`ForParens`].
close_paren: close_paren_approx,
};
// Where each clause's leading run emits from. Resolved once, so the freeze gate
// below and the emitter further down cannot read different gaps — the directive
// that freezes a clause has to be exactly the one printed above it.
let test_search_start =
self.for_clause_search_start(span.start, open_paren, first_semi, init_end);
let update_search_start = self.for_clause_search_start(
span.start,
open_paren,
second_semi,
test_end.or(init_end),
);
// Rule: an own-line directive in a clause's leading gap freezes that WHOLE clause
// ([`Printer::value_head_frozen_span`]). The slice is the clause's node span, so
// the header's `;` stays parent-owned — prettier's slice swallows it and emits a
// header that no longer parses
// (`init_declaration_prettier_ignore_head_prettier_divergence`).
// Each clause is absent-able independently of its gap, so the clause span is the
// `Option` and the gap is a plain offset.
let clause_frozen = |gap: u32, start: Option<u32>, end: Option<u32>| {
start
.zip(end)
.and_then(|(start, end)| self.value_head_frozen_span(gap, Span::new(start, end)))
};
// Init's gap is itself absent when there is no `(` to open one.
let init_frozen = spans
.init_region_start()
.and_then(|gap| clause_frozen(gap, spans.init_start, init_end));
let test_frozen = clause_frozen(test_search_start, spans.test_start, test_end);
let update_frozen = clause_frozen(update_search_start, spans.update_start, update_end);
// The opening-delimiter rule at the `for` header's `(`: a `//` the author glued to
// it keeps that line ([`Printer::split_open_delimiter_glued_run`]), as at every
// other opening delimiter and at the condition-headed statements
// (`OpenParenLineBlockComment`'s ⚠️). Only the INIT region is `(`-anchored — the
// later clauses open past a `;`, where a comment on the previous clause's line is
// that clause's (`push_for_clause_same_line_comments`), so the rule cannot reach
// them. Both init arms take it, since an empty init slot still sits behind the `(`.
let (paren_glued, init_region_start) =
match (spans.init_region_start(), spans.init_region_end()) {
(Some(start), Some(end)) => {
let (glued, resume) = self.split_open_delimiter_glued_run(start, end);
(glued, Some(resume))
}
// No locatable region — a degenerate header with no `(`, or one whose init
// slot has neither a clause nor a `;` to bound it.
(start, _) => (None, start),
};
// Check if we have any own-line comments that force expansion. A line
// comment anywhere in the header also forces it: the `//` runs to end of
// line, so the clauses after it must move to their own lines (matching
// prettier) — otherwise the comment swallows the rest of the header.
//
// A glued `//` is the same fact reached without both parens: it ends its own line,
// so the first clause can never pull up beside it. The range read below can't see
// that on a degenerate header (it needs the `)` too), and a header left flat around
// one would let the comment swallow the clause — so the split reports it here
// rather than hardening the init separator alone, which left the header's OPENING
// and CLOSING separators free to disagree.
let has_line_comment_in_header = paren_interior
.is_some_and(|(open, close)| self.has_line_comments_between(open + 1, close));
let has_own_line_comments = has_line_comment_in_header
|| paren_glued.is_some()
|| self.for_header_has_own_line_comments(&spans);
let mut inner_parts = DocBuf::new();
inner_parts.extend(paren_glued);
// Every clause is laid out the same way: its region's comments, then the
// clause (or nothing, when the slot is empty), then its `;`. Each region is
// bounded by the header's own separators (`ForHeaderSpans::*_region_end`), so
// exactly one emitter owns each comment.
// Init clause. Its separator is the header's own `softline` — `for (` and the
// first clause together when the header fits, the clause on its own line when
// it breaks — where the later clauses take the `line` that follows their `;`.
if let (Some(start), Some(init_start)) = (init_region_start, spans.init_start) {
self.push_for_clause_leading_section(
&mut inner_parts,
start,
init_start,
None,
d.softline(),
);
} else {
inner_parts.push(d.softline());
if let (Some(start), Some(region_end)) = (init_region_start, spans.init_region_end())
&& self.push_for_empty_slot_comments(&mut inner_parts, start, region_end)
{
// The `;` that terminates the slot starts a fresh line (or is
// space-separated when the header fits).
inner_parts.push(d.line());
}
}
if let Some(init) = &stmt.init {
// Each clause is built with its own END recorded, so a value shell that closes
// there knows the `;` behind it SEPARATES clauses
// ([`Printer::shell_closes_for_clause`]). The header is where the three ends are
// already resolved, and the one frame that holds all three; the clause builders
// below see only their own expression, whose span end is the same number but says
// nothing about which separator follows it.
inner_parts.push(self.with_for_clause_end(init_end, || {
init_frozen.map_or_else(
|| self.build_for_init_doc(init),
|frozen| self.build_frozen_init_clause_doc(init, frozen),
)
}));
}
// The init clause→`;` gap comments bind to the `;` like a list separator.
self.push_for_clause_semicolon(&mut inner_parts, init_end, first_semi);
// Test clause, same shape as init.
if let Some(start) = spans.test_start {
// Inline comments after init (after the `;`, on the same line as init)
if let (Some(semi), Some(end)) = (first_semi, init_end) {
self.push_for_clause_same_line_comments(&mut inner_parts, semi + 1, start, end);
}
self.push_for_clause_leading_section(
&mut inner_parts,
test_search_start,
start,
init_end,
d.line(),
);
} else {
// The post-`;` separator is emitted even with nothing to separate, so the
// header isn't collapsed to `;;` — prettier keeps it whenever the header
// isn't fully empty (`for (x = 0; ;)`, not `for (x = 0;;)`; the fully-empty
// `for (;;)` returned above).
inner_parts.push(d.line());
if let (Some(semi), Some(region_end)) = (first_semi, spans.test_region_end())
&& self.push_for_empty_slot_comments(&mut inner_parts, semi + 1, region_end)
{
inner_parts.push(d.line());
}
}
if let Some(test) = &stmt.test {
// Wrap in group so binary chains (Ungrouped mode) have a tight parent
// to evaluate fit against — matching how if/while use build_condition_group.
// Without this, logical operators break with the for-header group (too wide)
// instead of their own condition width.
// TODO: a test clause value that takes CLARITY PARENS costs a second pass on the
// authored shell (`for (; a = (b /* c */); )` prints `(a = b /* c */)`, whose
// reparse reads the comment in the clause's own gap and moves it behind the pair).
// Both forms converge on `(a = b) /* c */`, prettier included and in the same two
// passes, so this is a pass count rather than an end state — closing it means
// routing the clause's own value through a shell builder, the same routing
// [`Self::build_for_init_doc`]'s Expression arm wants (and it would print
// prettier's SECOND-pass form on pass 1, a pass-count divergence rather than
// parity). The same two-pass shape, prettier-identical pass for pass, shows at
// any clause-terminal value whose trailing block spans lines
// (`for (a = ('k' in o /*⏎⏎ t */); ;)` hangs the value under `=` on pass 1 and
// collapses it on pass 2) — a non-last declarator does the same, so it is the
// multi-line-block class, not this clause's.
inner_parts.push(self.with_for_clause_end(test_end, || {
test_frozen.map_or_else(
|| d.group(self.build_condition_doc(test, HeadChainGrouping::ParenGroupDrives)),
// The clarity parens an assignment test prints (`for (; (a = b); )`) are
// the printer's, not the author's, so they wrap the frozen slice instead
// of riding inside it — the same `StatementTest` shell, and the same
// context, the unfrozen clause above applies.
|frozen| self.build_frozen_value_doc(test, frozen, ParenContext::StatementTest),
)
}));
}
// The test clause→`;` gap comments bind to the `;` like a list separator.
self.push_for_clause_semicolon(&mut inner_parts, test_end, second_semi);
// Update clause. Unlike init and test, nothing terminates its region but the
// header's own closing `softline`/`hardline` — so the clause and the gap after
// it share one trailing region (`push_for_update_trailing_comments`, below),
// which is also the whole slot when the clause is absent.
if let Some(start) = spans.update_start {
// Inline comments after test (after the `;`, on the same line as test)
if let (Some(semi), Some(end)) = (second_semi, test_end) {
self.push_for_clause_same_line_comments(&mut inner_parts, semi + 1, start, end);
}
self.push_for_clause_leading_section(
&mut inner_parts,
update_search_start,
start,
test_end,
d.line(),
);
}
if let Some(update) = &stmt.update {
inner_parts.push(self.with_for_clause_end(update_end, || {
update_frozen.map_or_else(
|| self.build_for_update_doc(update),
// The clause prints BARE, exactly as the init clause's frozen arm does
// ([`Self::build_frozen_init_clause_doc`]) and for the same reason: a
// `SequenceExpression` clause is the one position that wants no grouping
// pair, where [`Printer::build_frozen_expression_doc`] re-synthesizes the
// one every other position needs. The update clause is `[+In]` and heads
// no statement, so nothing else can want a pair here either — and the
// re-synthesized one printed a grouping pair the author never wrote and
// prettier does not print.
|frozen| self.build_frozen_node_doc(frozen),
)
}));
}
if let Some(start) = spans.update_trailing_start() {
self.push_for_update_trailing_comments(
&mut inner_parts,
start,
spans.close_paren.unwrap_or(span.end),
update_end,
);
}
let closing = if has_own_line_comments {
d.hardline()
} else {
d.softline()
};
d.group(d.concat(&[
for_open,
d.indent(d.concat(&inner_parts)),
closing,
d.text(")"),
]))
}
/// Check if for header has any own-line comments that force expansion
///
/// One check per clause region, each bounded by the header's separators exactly as
/// the emitters are (`ForHeaderSpans::*_region_end`) — so a comment in an EMPTY
/// slot is seen here too, and the header it forces open is the one that prints it.
/// A region starts at the preceding clause's end when there is one (its `content`→`;`
/// gap belongs to it) and just past the preceding `;` otherwise.
fn for_header_has_own_line_comments(&self, spans: &ForHeaderSpans) -> bool {
let region = |start: Option<u32>, end: Option<u32>| {
start
.zip(end)
.is_some_and(|(start, end)| self.has_isolated_comment_between(start, end))
};
region(spans.init_region_start(), spans.init_region_end())
|| region(spans.test_region_start(), spans.test_region_end())
|| region(spans.update_region_start(), spans.update_region_end())
// The update→`)` gap, when an update clause splits it off from the region
// above. Scanned separately rather than by widening that region's end to
// `)`, so the update expression's own interior comments stay the
// expression printer's business.
|| region(spans.update_end, spans.close_paren)
}
/// Emit a for-header clause terminator `;` with its content→`;` gap comments
/// bound to the `;` **like a list separator** (the `split_comma_gap_comments`
/// binding, via `split_for_header_gap_comments`): a same-line block stays before the `;`
/// (`a /* c */;`), a same-line line trails it via `line_suffix` (`a; // c`),
/// and an own-line comment defers **after** the `;`, opening on the header's own
/// `line` rather than on a break of its own
/// ([`Printer::split_for_header_gap_comments`] — the header decides its own width,
/// so `x = 0⏎/* c1 */ /* c2 */;⏎b` collapses back onto one line the way prettier
/// prints it). A blank
/// line before an own-line comment is not preserved, as prettier collapses it
/// in a for-header gap. `clause_end`/`semi` are the clause's end and the
/// source `;` position; either being absent emits a bare `;`.
fn push_for_clause_semicolon(
&self,
parts: &mut DocBuf,
clause_end: Option<u32>,
semi: Option<u32>,
) {
let d = self.d();
let after = match (clause_end, semi) {
(Some(start), Some(sep)) => self.split_for_header_gap_comments(parts, start, sep),
_ => DocBuf::new(),
};
parts.push(d.text(";"));
parts.extend(after);
}
/// Find the two `;` separators in a for-header. Returns `(first_semi,
/// second_semi)`; the second is only sought once the first is found.
///
/// Each scan is anchored at the **end of the clause its separator follows**, taken
/// from the AST — never at the `for` keyword or the open paren. That is what makes
/// first-match correct: from a clause's own end, only trivia and closing parens can
/// precede the `;`, so the first hit is the separator. A scan anchored ahead of the
/// clause instead walks *through* its source, and `TriviaProfile::JS` skips comments
/// and strings but tracks **no brace depth** — so a `;` inside a nested block
/// (`for (let f = () => { a(); b(); } /* c */; …)`) reads as the header separator,
/// mis-binding that clause's trailing comments. It double-printed one. The anchor
/// does this work, not the profile; widening the profile would not help.
///
/// A clause that is absent falls back to just past the preceding delimiter, where
/// the same adjacency holds (nothing but trivia sits between them).
///
/// The search is bounded by `close_paren`, so a separator can never be picked up from
/// a *later statement*: both separators are inside the header by definition, and a
/// header missing one is degenerate, which every caller already handles. That also
/// keeps the scan O(header) rather than O(rest of file).
fn find_for_semicolons(
&self,
stmt: &ast::ForStatement<'_>,
open_paren: u32,
close_paren: Option<u32>,
) -> (Option<u32>, Option<u32>) {
let bytes = self.source.as_bytes();
let end = close_paren.map_or(bytes.len(), |c| c as usize);
let (init_end, test_end) = self.for_clause_ends(stmt);
let scan = |from: u32| {
find_char(bytes, from as usize, end, b';', TriviaProfile::JS).map(|p| p as u32)
};
let first_semi = scan(init_end.unwrap_or(open_paren + 1));
let second_semi = first_semi.and_then(|first| scan(test_end.unwrap_or(first + 1)));
(first_semi, second_semi)
}
/// The end positions of the `init` and `test` clauses — the AST anchors the header's
/// `;` separators are located from (see [`Self::find_for_semicolons`]). Derived in one
/// place so the two scan call sites and the `ForHeaderSpans` build cannot disagree.
fn for_clause_ends(&self, stmt: &ast::ForStatement<'_>) -> (Option<u32>, Option<u32>) {
(
stmt.init.as_ref().map(|i| self.get_for_init_span_end(i)),
stmt.test.as_ref().map(|t| t.span().end),
)
}
/// Resolve where to start searching for a for-clause's leading comments: just
/// past the preceding `;` if present, else the previous clause's end, else just
/// inside the open paren (or past `for (` when the paren is unknown).
///
/// The `;`-first preference is the deliberate mirror of
/// [`ForHeaderSpans::test_region_start`], which prefers the previous clause's
/// *end*. Two starts because two questions: a comment before the `;` belongs to the
/// separator gap and is emitted by [`Self::push_for_clause_semicolon`], so the
/// leading run must start *after* it or print it twice — while the break scan must
/// see it, since it is what forces the header open.
fn for_clause_search_start(
&self,
stmt_start: u32,
open_paren: Option<u32>,
semi: Option<u32>,
prev_end: Option<u32>,
) -> u32 {
semi.map_or_else(
|| {
prev_end.unwrap_or_else(|| {
open_paren.map_or_else(|| stmt_start + "for (".len() as u32, |p| p + 1)
})
},
|s| s + 1,
)
}
/// Push comments in `range_start..boundary` that sit on the same source line as
/// `end`, each inline with a leading space. Used for the inline comments
/// trailing a for-clause: after init's `;`, after test's `;`, and after the
/// update expression. Unlike `push_for_clause_semicolon` (the content→`;` gap,
/// bound to the `;`), this emits every comment kind that shares a line with the
/// clause end, from the region *after* the `;`.
fn push_for_clause_same_line_comments(
&self,
parts: &mut DocBuf,
range_start: u32,
boundary: u32,
end: u32,
) {
let d = self.d();
for comment in self.comments_to_emit_between(range_start, boundary) {
if self.is_same_line(end, comment.span.start) {
parts.push(d.text(" "));
parts.push(self.build_comment_doc(comment));
}
}
}
/// Emit the lead-in before a for-clause: the leading-comment run, then any comment
/// hugging the clause on its own line (`for (let i = 0; /* before test */ i < 10;
/// …)`) — or just `separator` when the gap is empty.
///
/// `separator` is what follows the preceding token when no comment takes that
/// place — the `line` after the `;` for the test and update clauses, the header's
/// opening `softline` for init.
///
/// One pass **partitions** the gap, so every comment is printed exactly once and no
/// comment can fall between two filters that must agree: what shares the *previous*
/// clause's line was already emitted by
/// [`Self::push_for_clause_same_line_comments`], a **block** sharing the clause's
/// line hugs it, and everything else is the leading run. The run is the default arm
/// on purpose — a `//` normally can't share a line with what follows it, but the
/// line-break table records only `\n` while the lexer also ends a `//` at a lone
/// `\r`, so `// c\r i < 10` does read as same-line. Landing that in the hug arm
/// would emit `// c i < 10` and swallow the clause; the run gives it its own line.
///
/// **No separator here is the run's own**: the header's `separator` leads it and the
/// shared [`Printer::push_leading_comment_run`] supplies every break inside it and
/// the one before the clause, so this gap follows the same rules as every other
/// leading run — an author blank line between two comments survives, and a run glued
/// onto one line stays glued. Hand-rolling a `hardline` per comment lost both.
///
/// ⚠️ **And the site must not pre-empt the header's width decision either.** Asking
/// [`Printer::is_own_line_comment`] of the run's FIRST comment and pushing a
/// `hardline` for it reads as preserving the authored line and is the one-sided
/// reading: in `x = 0;⏎/* c1 */ /* c2 */⏎b` only `c1` has a newline before it and
/// only `c2` has one after, so neither owns a line, and prettier keeps the whole
/// header flat (`docs/comments.md` §Own-line-ness is a SOURCE question). A run whose
/// first comment IS isolated needs no help from here: it takes the emitter's
/// `hardline`, which opens the header through `DocArena::will_break` and breaks this
/// `separator` with it — so the two arms rendered identically wherever the pre-empt
/// was right, and differed only where it was wrong.
///
/// `search_start` - where to start looking for comments
/// `clause_start` - start of the next clause
/// `prev_end` - end of the previous expression (whose own trailing comments are
/// already emitted); `None` for the init clause, which no expression precedes
fn push_for_clause_leading_section(
&self,
parts: &mut DocBuf,
search_start: u32,
clause_start: u32,
prev_end: Option<u32>,
separator: DocId,
) {
// A comment trailing the previous clause on its line belongs to that clause, not
// to this run. What remains splits at the clause the way every gap does: the
// glued suffix leads it inline, the rest take their own lines.
let (run, hug) = self.split_glued_comments(
self.comments_to_emit_between(search_start, clause_start)
.filter(|c| !prev_end.is_some_and(|pe| self.is_same_line(pe, c.span.start))),
);
parts.push(separator);
self.push_leading_comment_run(
parts,
run.iter().copied(),
clause_start,
LeadingGlue::Adjacent,
);
self.push_glued_comment_run(parts, &hug);
}
/// Emit the comments an **absent** clause's slot holds, joined by `line`, and
/// report whether any were emitted.
///
/// An empty slot has no other emitter — the clause whose leading run would print
/// them isn't there — so without this the comments are dropped. They stay in the
/// slot the author wrote them in, which is what the fully-empty header already
/// does (`build_for_empty_with_comments`) and a divergence from prettier, which
/// relocates them into the next clause or out of the header entirely (see the
/// `empty_slot_comment_prettier_divergence` fixture).
///
/// Only the init and test slots come through here — the ones a `;` terminates. The
/// caller supplies the separators around the run: the header's leading `softline`
/// or the `line` after the preceding `;` before it, and a `line` after it so a `//`
/// can't swallow that `;`. The update slot has no terminator of its own and shares
/// the update clause's trailing region instead
/// ([`Self::push_for_update_trailing_comments`]).
fn push_for_empty_slot_comments(&self, parts: &mut DocBuf, start: u32, end: u32) -> bool {
let d = self.d();
let mut emitted = false;
for comment in self.comments_to_emit_between(start, end) {
if emitted {
parts.push(d.line());
}
parts.push(self.build_comment_doc(comment));
emitted = true;
}
emitted
}
/// Emit the update slot's trailing region — the update→`)` gap, and the whole
/// (empty) slot when there is no update clause. One region either way, since `)` is
/// all that closes it.
///
/// The separator goes *before* each comment and none after: a comment sharing the
/// update's line trails it, every other one takes its own line, and the header's
/// own closing `softline`/`hardline` terminates the last. That is also why an
/// absent update clause with nothing to say adds no separator at all — prettier 3.9
/// (#19188) dropped the space it used to put before `)` → `for (…; cond;)`, not
/// `for (…; cond; )`.
///
/// Emitting only the trailing form would drop an own-line comment here.
fn push_for_update_trailing_comments(
&self,
parts: &mut DocBuf,
start: u32,
close: u32,
update_end: Option<u32>,
) {
let d = self.d();
for comment in self.comments_to_emit_between(start, close) {
if update_end.is_some_and(|end| self.is_same_line(end, comment.span.start)) {
parts.push(d.text(" "));
} else {
parts.push(d.line());
}
parts.push(self.build_comment_doc(comment));
}
}
/// Build a for-header init/update clause that is a `SequenceExpression`
/// (`for (a = 1, b = 2; …)` / `for (…; a++, b++)`), preserving comments in the
/// inter-operand comma gaps — a same-line block leads the next operand inline
/// (`, /* c */ b`), a line comment trails the comma and forces the per-operand
/// break (`a, // c⏎\tb`) — the same gap handling as a multi-declarator init
/// clause (`push_for_clause_comma_gap`). `build_elem` renders one operand: the init
/// clause wraps it in `wrap_for_init_in` for the `[~In]` restriction, the update
/// clause does not.
///
/// The `for` head is one of prettier's two parent-keyed
/// `printSequenceExpression` arms (`ExpressionStatement` is the other): operands
/// after the first take a continuation indent when the clause breaks, and no parens
/// are added (`needs-parentheses.js` excludes a `ForStatement` parent). The
/// separator is the comma gap's own `,` + `line`, so a clause too wide for the
/// header breaks per operand instead of running past the print width.
///
/// ⚠️ **This is a THIRD sequence printer**, beside `operators.rs`'s
/// `build_sequence_doc_inner` and its line-comment twin, and it stays separate on
/// purpose: the head's comma gaps take the DECLARATOR's comment rules
/// ([`Printer::push_for_clause_comma_gap`], shared with a multi-declarator init) rather
/// than the sequence printer's own, and `build_elem` carries the init clause's `[~In]`
/// wrap. Only the geometry is common — `SeqLayout::Indented` is the same shape this
/// builds by hand — so a change to how a sequence BREAKS belongs in both, while a change
/// to how its comments bind does not.
///
/// Before this, both sequence branches emitted a comment-blind `", "` join,
/// silently dropping every inter-operand comment (`for (a = 1, /* c */ b = 2;
/// …)` lost `/* c */`). The comment-FREE fast path kept that join until the width
/// fix; it was the same doc the loop below builds when every gap is bare
/// ([`Printer::push_for_clause_comma_gap`] emits exactly `,` + `line` there), so it
/// is gone rather than duplicated.
fn build_for_sequence_clause_doc(
&self,
seq: &ast::SequenceExpression<'_>,
seq_span: Span,
build_elem: impl Fn(&Expression<'_>) -> DocId,
) -> DocId {
self.mark_relational_sibling_authored_pairs(seq.expressions.iter().copied().map(Some));
// A MULTI-LINE block the FIRST operand OWNS prints ahead of the run, outside the
// layout's group ([`Printer::build_doc_with_outermost_owned_comment_at`]) — the
// general sequence printer's rule, at the clause that keeps its own copy of the
// run. There is no pair here at all: the author's grouping parens are stripped in
// a for header, so the comment simply leads the clause, which is where prettier
// prints it too. Only the BREAK differs, and the two agree once it is gone.
self.build_doc_with_outermost_owned_comment_at(
seq_span.start,
seq.expressions.first().copied(),
|| {
let d = self.d();
let last = seq.expressions.len() - 1;
let first_start = seq.expressions[0].span().start;
let mut parts = DocBuf::new();
// The LEADING EDGE: the grouping `(` the parser erased ahead of the first
// operand, and any comment inside it — a region that lies INSIDE the
// sequence's own span (which opens at that `(`), so the clause's leading
// section, which stops where the clause starts, cannot reach it. Nothing
// else emits it here: the general sequence printer hands this run to its
// paren ENVELOPE ([`Printer::append_floated_leading_comments`]) and a for
// header has no envelope at all, so unemitted it is DROPPED
// (`docs/comments.md` hazard 4).
//
// Emitted OUTSIDE the layout's group, like every other hoisted left-spine
// shell run (`docs/comments.md` §The left-spine shell run): a hardline
// inside it would break the operands apart for a comment the reparse reads
// ahead of the whole clause — where it leads the sequence node and leaves
// the operands flat — so the two passes would disagree.
//
// The canonical emitter ([`Printer::push_leading_comment_run`]) is called
// here rather than through the general left-spine seam
// ([`Printer::build_left_spine_operand_doc`]) because that seam applies
// [`Printer::wrap_frozen_position_pair`] to what it builds, and a `for`
// header's operand needs the header's own `[~In]` pair instead
// ([`Printer::wrap_frozen_for_init_in`]) — the run itself is the same one.
if first_start != seq_span.start {
self.push_leading_comment_run(
&mut parts,
self.comments_to_emit_between(seq_span.start, first_start),
first_start,
LeadingGlue::Adjacent,
);
}
let mut docs = DocBuf::new();
// Where the FIRST operand's docs end — `build_sequence_layout_doc`'s `first_end`,
// tracked rather than assumed to be 1 so the layout does not depend on how many
// docs an operand pushes.
let mut first_end = 0;
for (i, e) in seq.expressions.iter().enumerate() {
let frozen = if i > 0 {
let prev_end = seq.expressions[i - 1].span().end;
self.push_for_clause_comma_gap(&mut docs, prev_end, e.span().start);
// Rule A, the same as the general sequence printer's: an own-line
// directive in the comma gap freezes the FOLLOWING operand. The `[~In]`
// wrap `build_elem` would apply is owed by the frozen arm too — the
// pair sits outside the operand's node span, so a verbatim slice drops
// it — and this site asks no `needs_parens`, so it spells the wrap
// itself, below, over the SLICE
// ([`Printer::wrap_frozen_for_init_in`]). Nothing else parenthesizes
// an operand, so `already_parenthesized` is false.
self.gap_frozen_span(prev_end, e.span())
} else {
// The leading edge's own freeze, the same rule the general sequence
// printer applies to its first operand
// ([`Printer::left_spine_operand_frozen_span`]): an own-line directive
// inside the erased shell freezes THAT operand, Rule A's child scope.
self.left_spine_operand_frozen_span(seq_span.start, e)
};
docs.push(if i == last {
// The TRAILING EDGE: the last operand's own erased shell closes at the
// sequence's span end, so `[operand.end, seq_span.end)` is its gap —
// and, unlike every earlier operand's, no comma gap follows to claim
// it. Handed to the header's own shell builder, which owns the
// question at every other `for`-clause position: the block strips
// inline before the clause's `;`, a `//` or an own-line comment
// RETAINS the shell, and nothing defers past a separator that
// terminates no statement ([`Printer::build_for_init_value_doc`]).
// That builder also applies the `[~In]` wrap `build_elem` would —
// keyed on the same ambient flag, so the init clause wraps and the
// update clause does not — and places it INSIDE the trailing comment
// (`(aaa in bbb) /* c */`), which is why the operand is built there
// rather than wrapped here.
self.build_for_clause_operand_doc(e, seq_span.end, frozen)
} else {
// The authored pair the clause keeps around a comparison
// ([`Printer::mark_relational_sibling_authored_pairs`]) is asked
// FIRST, because it is also a pair the header's `[~In]` rule would
// otherwise add: the frozen arm is told so and adds none, and the
// unfrozen arm's `build_elem` adds its own only around an `in`
// binary, which then supplies the kept pair.
let kept = self.relational_sibling_pair_is_kept(e);
let core = frozen.map_or_else(
|| build_elem(e),
|frozen| {
self.wrap_frozen_for_init_in(
e,
frozen,
kept,
self.build_frozen_expression_doc(e, frozen),
)
},
);
let in_pair_printed = frozen.is_none() && self.for_init_in_needs_parens(e);
self.wrap_relational_sibling_pair(e, in_pair_printed, core)
});
if i == 0 {
first_end = docs.len();
}
}
// Prettier's `ForStatement` arm of `printSequenceExpression` — the same geometry
// the general sequence printer states once, so this clause cannot answer it
// differently: the indent starts AFTER the first operand, and an operand that
// breaks internally keeps its own lines at the clause's base column. Wrapping the
// whole run instead added a level to the FIRST operand's internals, visible on a
// plain call (`for (fn(⏎…⏎), cc; ;)`) as well as on a binary.
parts.push(self.build_sequence_layout_doc(&docs, first_end, SeqLayout::Indented));
d.concat(&parts)
},
)
}
/// Render a for-header init/update clause expression. A `SequenceExpression`
/// (`a = 1, b = 2`) routes through `build_for_sequence_clause_doc` for
/// inter-operand comment handling; any other expression is rendered directly
/// by `build_elem`. Sharing this dispatch keeps the init and update clauses
/// from diverging on how a comma sequence is detected and routed. `build_elem`
/// renders one operand — the init clause wraps it in `wrap_for_init_in` for the
/// `[~In]` restriction, the update clause does not.
fn build_for_expr_clause(
&self,
expr: &Expression<'_>,
build_elem: impl Fn(&Expression<'_>) -> DocId,
) -> DocId {
if let ExpressionKind::SequenceExpression(seq) = &expr.kind {
// A sequence's ELEMENTS are not `shouldNotIndent`: their parent is the
// sequence, not the `for`, so a binary element keeps the continuation-indent
// default — which is why the mark below is on the clause and not inside
// `build_elem`.
return self.build_for_sequence_clause_doc(seq, expr.span, build_elem);
}
// The clause itself is `shouldNotIndent`'s own `ForStatement` term (`node !==
// parent.body && parent.type === "ForStatement"`, `shouldNotIndent` in `print/binaryish.js`), so a binary
// clause is FLAT. Marked rather than built directly because the builder is the
// caller's — the init clause wraps each operand for `[~In]`, the update clause does
// not (`Printer::mark_flat_chain`). `build_elem` runs immediately below, so nothing
// can clear the mark in between.
self.mark_flat_chain(expr);
build_elem(expr)
}
/// Build a Doc for a for loop update expression
fn build_for_update_doc(&self, expr: &Expression<'_>) -> DocId {
self.build_for_expr_clause(expr, |e| self.build_expression_doc(e))
}
/// Build a complete for-in statement doc including the body
pub(in crate::printer::statements) fn build_for_in_statement_doc(
&self,
stmt: &ast::ForInStatement<'_>,
span: Span,
ctx: StatementContext,
) -> DocId {
self.build_for_in_of_statement_with_body_doc(
stmt.left, stmt.right, stmt.body, span.start, "in", false, ctx,
)
}
/// Build a complete for-of statement doc including the body
pub(in crate::printer::statements) fn build_for_of_statement_doc(
&self,
stmt: &ast::ForOfStatement<'_>,
span: Span,
ctx: StatementContext,
) -> DocId {
self.build_for_in_of_statement_with_body_doc(
stmt.left,
stmt.right,
stmt.body,
span.start,
"of",
stmt.r#await,
ctx,
)
}
/// Build a complete for-in/for-of statement doc including the body.
///
/// Shared by [`Self::build_for_in_statement_doc`] and
/// [`Self::build_for_of_statement_doc`]: the two differ only in the
/// `"in"`/`"of"` keyword and for-of's `for await` handling, which collapses
/// to a no-op when `is_await` is false (for-in has no `await` form). The
/// `for (` opening is built in split form (`" "` + `"("`) so the optional
/// `await` keyword slots in between — render-identical to for-in's fused
/// `" ("`.
#[expect(clippy::too_many_arguments)] // one cohesive for-in/of assembly; a bundle would re-thread the same values
fn build_for_in_of_statement_with_body_doc(
&self,
left: &ast::ForInOfLeft<'_>,
right: &Expression<'_>,
body: &Statement<'_>,
stmt_start: u32,
keyword: &'static str, // `"in"` or `"of"` — a literal, so it doubles as the emitted token
is_await: bool, // for-of `for await`; always false for for-in
ctx: StatementContext,
) -> DocId {
let d = self.d();
let spans = self.for_in_of_spans(left, right, keyword, stmt_start);
// Every non-block body arm below wraps the body in one `adjustClause` indent
// (the empty statement, which ignores it, aside); nothing continues on the
// tail's line.
let body_ctx = ctx.clause_body(false, true);
// The keyword as a static literal (`d.text` needs `&'static str`), carrying the
// separator that precedes it — the inline layout's gap emitter writes none.
let kw_spaced = if keyword == "of" { " of" } else { " in" };
// Preserve comments between keywords and `(`
// for await: two gaps — for-to-await and await-to-paren
// for (non-await): one gap — for-to-paren
let for_keyword_end = stmt_start + "for".len() as u32;
let (for_await_comments, await_paren_comments) = if is_await {
let await_pos = self.find_keyword_in_range(for_keyword_end, spans.left_start, "await");
// Same line-safe builder as the `await`→`(` gap below: a line comment in
// the `for`→`await` gap breaks `await` onto the next line so the `//`
// can't swallow it; a block comment keeps its glue space.
let for_await_c = await_pos
.and_then(|ap| self.build_keyword_paren_comments(for_keyword_end, Some(ap)));
let await_paren_c = await_pos
.map(|ap| ap + "await".len() as u32)
.and_then(|ae| self.build_keyword_paren_comments(ae, spans.open_paren));
(for_await_c, await_paren_c)
} else {
(None, None)
};
let keyword_comments = if is_await {
None
} else {
self.build_keyword_paren_comments(for_keyword_end, spans.open_paren)
};
// Check for a comment in the header's *structural gaps* that needs its own line
// — if present, use the breaking layout that preserves it where the author
// placed it. Only gap comments count: a `//` *inside* the binding or the
// iterable expression is that expression's own content (printed by its doc) and
// must NOT force the header open — prettier keeps the head inline and only the
// iterable breaks. See `in_of_iterable_line_comment`.
let breaks_for_gap_comment = self.for_in_of_header_gap_comment_forces_break(&spans);
// Build the `for ... (` opening once — shared by both the inline and the
// breaking (line-comment) layouts, so each preserves any `for`-to-`(`
// comment and emits `await` from the AST.
let mut parts = d.pooled_docbuf();
self.push_for_open_paren(
&mut parts,
keyword_comments,
for_await_comments,
await_paren_comments,
is_await,
);
let async_lhs_paren = self.for_lhs_needs_async_paren(left, keyword, is_await);
if breaks_for_gap_comment {
let left_doc = self.build_for_in_of_left_doc(left, async_lhs_paren, &spans);
return self.build_for_in_of_with_line_comments(
right, body, keyword, &spans, left_doc, &mut parts, body_ctx,
);
}
// Comments between ( and left
if let Some(open) = spans.open_paren {
for comment in self.comments_to_emit_between(open + 1, spans.left_start) {
if comment.is_block {
parts.push(self.build_comment_doc(comment));
parts.push(d.text(" "));
}
}
}
parts.push(self.build_for_in_of_left_doc(left, async_lhs_paren, &spans));
// Comments after left, before the keyword
self.append_for_in_of_block_comments(&mut parts, spans.left_end, spans.keyword_pos);
parts.push(d.text(kw_spaced));
// Comments after the keyword, before right
self.append_for_in_of_block_comments(&mut parts, spans.keyword_end, spans.right_start);
parts.push(d.text(" "));
parts.push(self.build_for_in_of_right_doc(right));
// Comments after right, before close paren — the `)` follows with no separator
if let Some(close) = spans.close_paren {
self.append_for_in_of_block_comments(&mut parts, spans.right_end, close);
}
// `)` + comments + body (shared with the breaking layout)
self.push_for_close_paren_and_body(
&mut parts,
body,
spans.right_end,
spans.close_paren,
body_ctx,
);
// Group so a non-block body's `adjustClause` line breaks on overflow
// (matches Prettier's `printForXStatement`).
d.group(d.concat(&parts))
}
/// The for-in/for-of iterable's doc, carrying the clarity parens its value position
/// takes (`for (const x of (y = z))` — see [`ParenContext::ForInOfRight`]).
///
/// One seam for both header layouts (inline + line-comment), so an iterable cannot be
/// parenthesized in one and bare in the other — the same reason a ternary's two
/// layouts share `parenthesize_ternary_branch`. A bare `build_expression_doc`
/// in each is how the pair goes missing from both.
fn build_for_in_of_right_doc(&self, right: &Expression<'_>) -> DocId {
// A binary iterable takes the continuation-indent default — unlike the C-style
// header's clauses, which are `shouldNotIndent`'s own `ForStatement` term
// (`node !== parent.body && parent.type === "ForStatement"`, which a
// ForOf/ForIn statement is not).
let doc = self.build_expression_doc_claiming_outermost(right);
if needs_parens(right, ParenContext::ForInOfRight, self.in_for_init.get()) {
self.d().parens(doc)
} else {
doc
}
}
/// Resolve the for-in/for-of header's source positions into a `ForInOfSpans`,
/// computed once and shared by the structural-line-comment check and both the
/// inline and breaking layouts. Preserves each getter's semantics — notably
/// `keyword_pos` falls back to `left_end` when the `in`/`of` keyword can't be
/// located, and `close_paren` follows the depth-tracked open paren.
fn for_in_of_spans(
&self,
left: &ast::ForInOfLeft<'_>,
right: &Expression<'_>,
keyword: &str,
stmt_start: u32,
) -> ForInOfSpans {
let left_end = self.get_for_in_of_left_end(left);
let right_start = right.span().start;
// The `in`/`of` keyword, through the shared trivia-aware scan the rest of the
// printer uses (`tsv_lang::source_scan::find_keyword`) rather than a raw
// substring walk of this file's own — same whole-word rule, and it skips strings
// and templates as well as comments.
let keyword_found = self.find_keyword_in_range(left_end, right_start, keyword);
let keyword_pos = keyword_found.unwrap_or(left_end);
let keyword_end = keyword_pos + keyword.len() as u32;
let open_paren = self.find_open_paren_after(stmt_start);
// The right side is the header's last item, so its `)` is read short from there
// once the keyword is located; without the keyword, the full scan.
let close_paren = open_paren.and_then(|o| match keyword_found {
Some(_) => self.close_paren_around(o, keyword_end, right.span()),
None => self.matching_close_paren(o),
});
ForInOfSpans {
open_paren,
close_paren,
left_start: self.get_for_in_of_left_start(left),
binding_start: self.get_for_in_of_binding_start(left),
left_end,
keyword_pos,
keyword_end,
right_start,
right_end: right.span().end,
}
}
/// Whether a comment in one of the for-in/for-of header's *structural gaps* needs a
/// line of its own, forcing the breaking layout — after `(` up to the binding target
/// (covering the declaration keyword→binding gap, `const // c⏎x`), between the binding
/// and the `in`/`of` keyword, between the keyword and the iterable, or between the
/// iterable and `)`.
///
/// Two kinds do. A `//` line comment, because inline it would swallow the header
/// tokens after it (the reason below). And, in the `(`→binding region only, an
/// **honored format-ignore directive** of either spelling, because its own-line
/// placement is the thing that makes it honored: collapsed into the inline layout it
/// becomes glued to the following token, hence inert, and the freeze it won on the
/// first pass is lost on the second — an F1 non-idempotency. An ordinary block comment
/// still rides inline.
///
/// The directive half is **deliberately not** asked at the three later gaps. Their
/// emitters TRAIL a block comment onto the preceding token (`const x /* c */⏎of`), so
/// breaking the header there would not give the directive its own line anyway — it
/// would only lose that line on the next pass, when the gate reads the trailing
/// placement and collapses the header again. A break is worth forcing for a comment
/// only where the broken layout actually gives that comment a line of its own.
///
/// Deliberately excludes the interiors of the binding *pattern*
/// (`[binding_start, left_end)`) and the iterable (`[right_start, right_end)`): a
/// line comment *inside* the iterable (`for (const x of [\n\t'a' // c\n])`) — or
/// inside a destructuring binding — is that expression's own content, printed by
/// its doc, and must not force the header-breaking layout
/// (`build_for_in_of_with_line_comments`). Prettier keeps the head inline and
/// only that expression breaks. A gap comment, by contrast, has no other line
/// break to ride, so inline the `//` would swallow the following header tokens —
/// tsv breaks the header and preserves it in place. See the
/// `in_of_iterable_line_comment` (excluded) and
/// `of_in_keyword_binding_line_comment_prettier_divergence` (keyword→binding gap,
/// included) fixtures.
fn for_in_of_header_gap_comment_forces_break(&self, spans: &ForInOfSpans) -> bool {
// `(` → binding target (spans the declaration keyword + its keyword→binding
// gap). Absent open paren (degenerate header) has no locatable gap. The one
// region whose broken layout puts a comment on its own line, so the one that
// also asks about an honored directive — which makes it exactly the
// declaration header's own gap question (`keyword_gap_breaks`), asked here
// rather than re-spelled, so the two can never drift on what forces a break.
spans
.open_paren
.is_some_and(|open| self.keyword_gap_breaks(open + 1, spans.binding_start))
// binding → keyword
|| self.has_line_comments_between(spans.left_end, spans.keyword_pos)
// keyword → iterable
|| self.has_line_comments_between(spans.keyword_end, spans.right_start)
// iterable → `)`
|| self.has_line_comments_between(spans.right_end, spans.close())
}
/// Build for-in/for-of statement with line comments preserved in their positions
///
/// This is our divergence from Prettier - we preserve line comments where
/// the user wrote them rather than relocating them.
///
/// ⚠️ The three gaps that follow a token — binding→keyword, keyword→iterable,
/// iterable→`)` — are **runs**, and each routes through the shared
/// [`Printer::push_anchored_trailing_run`], which puts one separator BEFORE each
/// comment. A per-comment `" "` instead emitted the whole run on the anchor's line,
/// so a `//` anywhere but last swallowed every comment behind it (`x // c1 /* c2 */`,
/// the second comment becoming the first's text) and a following multiline block
/// produced output that does not reparse — `docs/comments.md` §Trailing and dangling
/// runs, the rule that a run's separator asks each comment's own neighbours.
///
/// The fourth gap, `(`→binding, is a **leading** run and goes to
/// [`Printer::push_leading_comment_run`] the way its C-style twin
/// ([`Self::push_for_clause_leading_section`]) does — the `(`'s own `hardline` leads
/// it and the emitter owns every break inside it and the one before the binding. A
/// hand-rolled `hardline` per comment there split a run the author glued and erased
/// an author blank between two own-line comments, which is that twin's rustdoc
/// verbatim.
#[expect(clippy::too_many_arguments)] // the breaking layout shares the inline one's prebuilt parts; a bundle would re-thread them
fn build_for_in_of_with_line_comments(
&self,
right: &Expression<'_>,
body: &Statement<'_>,
keyword: &'static str, // `"in"` or `"of"`, emitted directly
// Resolved header positions, computed once by the caller (see
// `for_in_of_spans`) — shared with the structural-comment check and the
// inline layout.
spans: &ForInOfSpans,
// The LHS doc (`const y`, `(async)`, …), prebuilt by the caller so the
// bare-`async` paren decision (`for_lhs_needs_async_paren`, which needs the
// `is_await` flag this method doesn't carry) stays on the caller's side.
left_doc: DocId,
// The `for ... (` opening, prebuilt by the caller (comments preserved,
// `await` from the AST) — shared with the inline layout. Filled in place
// (a pooled buffer owned by the caller) rather than taken by value.
parts: &mut DocBuf,
body_ctx: StatementContext,
) -> DocId {
let d = self.d();
// Inner content with hardline breaks
let mut inner = DocBuf::new();
// Comments between `(` and the binding: a LEADING run, so it splits at the
// binding the way `push_for_clause_leading_section` splits at its clause — the
// glued suffix leads the binding inline, the rest go to the shared
// `push_leading_comment_run`. The `(`'s own `hardline` leads the run and the
// emitter supplies every break inside it and the one before the binding, so no
// separator here is this site's. See the header-gap note above this function.
//
// Ahead of it, the opening-delimiter rule: a `//` the author glued to the `(`
// keeps that line ([`Printer::split_open_delimiter_glued_run`]), as at the C-style
// header and every other opening delimiter. It is emitted OUTSIDE this `inner`
// (into the caller's `parts`, right behind the `(`) so no break precedes it, and
// the `hardline` below then places the binding.
let (leading_run, leading_glued) = if let Some(open) = spans.open_paren {
// The doc and the position the rest of the run resumes at travel together, so
// the two emitters cannot disagree about where the claim ended.
let (glued, resume) = self.split_open_delimiter_glued_run(open + 1, spans.left_start);
parts.extend(glued);
self.split_glued_comments(self.comments_to_emit_between(resume, spans.left_start))
} else {
Default::default()
};
inner.push(d.hardline());
self.push_leading_comment_run(
&mut inner,
leading_run.iter().copied(),
spans.left_start,
LeadingGlue::Adjacent,
);
self.push_glued_comment_run(&mut inner, &leading_glued);
// Left side (const y)
inner.push(left_doc);
// Comments after left, before the keyword. The shared anchored-run emitter, one
// separator BEFORE each comment — see the header-gap note above this function.
self.push_anchored_trailing_run(
&mut inner,
spans.left_end,
spans.keyword_pos,
RunLeadingBlank::Keep,
);
// Keyword with extra indent (hardline is INSIDE the indent so keyword gets extra indent)
let mut keyword_parts: DocBuf = smallvec![d.hardline(), d.text(keyword)];
// Comments after the keyword, before the iterable — the same run rule.
self.push_anchored_trailing_run(
&mut keyword_parts,
spans.keyword_end,
spans.right_start,
RunLeadingBlank::Keep,
);
// Right side (items)
keyword_parts.push(d.hardline());
keyword_parts.push(self.build_for_in_of_right_doc(right));
// Comments after the iterable, before the `)` — the same run rule.
if let Some(close) = spans.close_paren {
self.push_anchored_trailing_run(
&mut keyword_parts,
spans.right_end,
close,
RunLeadingBlank::Keep,
);
}
inner.push(d.indent(d.concat(&keyword_parts)));
parts.push(d.indent(d.concat(&inner)));
parts.push(d.hardline());
// `)` + comments + body (shared with the inline layout)
self.push_for_close_paren_and_body(
parts,
body,
spans.right_end,
spans.close_paren,
body_ctx,
);
// Group so the non-block body's `adjustClause` line breaks (the
// hardline-broken header forces this group open via `will_break`).
d.group(d.concat(parts))
}
/// Push the `for [comments] [await] (` opening into `parts`.
///
/// Shared by the inline and breaking for-in/for-of header layouts so both
/// preserve any comment in the `for`-to-`(` region (`keyword_comments` /
/// `for_await_comments` / `await_paren_comments`) and emit `await` from
/// `is_await` (the AST) — a comment that merely contains the word `await`
/// stays a comment, never promoted to a `for await` keyword.
fn push_for_open_paren(
&self,
parts: &mut DocBuf,
keyword_comments: Option<DocId>,
for_await_comments: Option<DocId>,
await_paren_comments: Option<DocId>,
is_await: bool,
) {
let d = self.d();
parts.push(d.text("for"));
// `for` → (`await` | `(`) transition. Both `keyword_comments` (the non-await
// `for`→`(` gap) and `for_await_comments` (the `for`→`await` gap) are built by
// `build_keyword_paren_comments`, so each already carries its own trailing
// space (block) or hardline (line) — a line comment breaks the next token
// (`(` or `await`) onto its own line so the `//` can't swallow it. The two are
// mutually exclusive (keyword_comments only non-await, for_await_comments only
// await).
if let Some(kc) = keyword_comments {
parts.push(kc);
} else if let Some(fac) = for_await_comments {
parts.push(fac);
} else {
parts.push(d.text(" "));
}
if is_await {
parts.push(d.text("await"));
// `await` → `(` transition: `await_paren_comments` carries its own
// trailing space/break; otherwise a plain space.
if let Some(apc) = await_paren_comments {
parts.push(apc);
} else {
parts.push(d.text(" "));
}
}
parts.push(d.text("("));
}
/// Push `)` + comments + body for a for-in/for-of statement.
///
/// Shared by the inline and breaking layouts: a block body expands an empty
/// `{}` (`build_block_statement_expand_empty_doc`); a non-block body uses
/// Prettier's `adjustClause` indentation.
fn push_for_close_paren_and_body(
&self,
parts: &mut DocBuf,
body: &Statement<'_>,
right_end: u32,
close_paren: Option<u32>,
body_ctx: StatementContext,
) {
let paren_end = close_paren.map_or(right_end + 1, |p| p + 1);
if let StatementKind::BlockStatement(block) = &body.kind {
self.append_close_paren_with_comments(parts, paren_end, block.span.start);
parts.push(self.build_statement_head_doc(paren_end, body, || {
self.build_block_statement_expand_empty_doc(block)
}));
} else if matches!(&body.kind, StatementKind::EmptyStatement(_)) {
// An empty body is NOT an `adjustClause` body — prettier returns `";"`
// directly, so the gap's run stays trailing `)` and the `;` sits flush
// beneath it, never indented. `if` and `while` already routed here; for-x
// did not, so its run took the indented non-block path instead.
self.append_close_paren_empty_stmt_with_comments(parts, paren_end, body.span().start);
} else {
self.append_close_paren_with_non_block_body(parts, paren_end, body, body_ctx);
}
}
/// Get the end position of the left side of a for-in/for-of statement
fn get_for_in_of_left_end(&self, left: &ast::ForInOfLeft<'_>) -> u32 {
match left {
ast::ForInOfLeft::VariableDeclaration(decl) => decl.span.end,
ast::ForInOfLeft::Pattern(expr) => expr.span().end,
}
}
/// Get the start position of the left side of a for-in/for-of statement
fn get_for_in_of_left_start(&self, left: &ast::ForInOfLeft<'_>) -> u32 {
match left {
ast::ForInOfLeft::VariableDeclaration(decl) => decl.span.start,
ast::ForInOfLeft::Pattern(expr) => expr.span().start,
}
}
/// Get the start position of the for-in/for-of binding *target* — the first
/// declarator's pattern for a `VariableDeclaration` left (`const [a, b]` → the
/// `[`), or the pattern itself for a bare `Pattern` left. Unlike
/// `get_for_in_of_left_start` (which points at the `const`/`let` keyword), this
/// skips the declaration kind so the keyword→binding gap (`const // c⏎x`) reads
/// as a header-structural position while the binding pattern's own interior does
/// not — see `for_in_of_header_gap_comment_forces_break`.
fn get_for_in_of_binding_start(&self, left: &ast::ForInOfLeft<'_>) -> u32 {
match left {
ast::ForInOfLeft::VariableDeclaration(decl) => decl
.declarations
.first()
.map_or(decl.span.start, |declarator| declarator.id.span().start),
ast::ForInOfLeft::Pattern(expr) => expr.span().start,
}
}
/// Append one for-in/for-of header gap's comments in the INLINE layout: ` comment`
/// per block comment, and nothing else — **the separator toward whatever follows is
/// the caller's**, so the three gaps that use this (binding→keyword,
/// keyword→iterable, iterable→`)`) differ only in what they push next, never in how
/// the run is written.
///
/// A trailing space of its own, plus a `bool` saying whether it wrote one, was the
/// same separator said twice: each caller then chose a spaced or bare next token
/// from the flag, which is `" " + tok` either way.
///
/// Line comments are skipped because they cannot reach here —
/// [`Self::for_in_of_header_gap_comment_forces_break`] routes a `//` in any of
/// these gaps to [`Self::build_for_in_of_with_line_comments`], which is the only
/// layout that can give one a line to end.
fn append_for_in_of_block_comments(&self, parts: &mut DocBuf, start: u32, end: u32) {
let d = self.d();
for comment in self.comments_to_emit_between(start, end) {
if comment.is_block {
parts.push(d.text(" "));
parts.push(self.build_comment_doc(comment));
}
}
}
pub(in crate::printer::statements) fn build_for_statement_doc(
&self,
stmt: &ast::ForStatement<'_>,
span: Span,
ctx: StatementContext,
) -> DocId {
let d = self.d();
// Preserve comments between `for` keyword and `(` in place:
// for/* c */(;;){} → for /* c */ (;;) {}
let for_keyword_end = span.start + "for".len() as u32;
// Located once here and threaded through every consumer — see `ForParens`.
let parens = self.for_parens(span.start);
let keyword_comments = self.build_keyword_paren_comments(for_keyword_end, parens.open);
let has_pre_paren_comments = keyword_comments.is_some();
// Check for comments between ) and body (Prettier 3.7 #18108)
let header_end = self.get_for_header_end(stmt, span, parens);
let body_start = stmt.body.span().start;
if has_pre_paren_comments || self.has_comments_to_emit_between(header_end, body_start) {
// Build parts with proper comment handling. A comment between `)` and the
// body does NOT force the header to break — the header decides its own
// flat/break on its own width (prettier 3.9 collapses `for (i; c; u)` and
// trails the comment after `)`). Only comments *inside* the parens (handled
// in `build_for_header_doc`) or overflow expand the header.
let mut parts: DocBuf =
smallvec![self.build_for_header_doc(stmt, span, parens, keyword_comments)];
// Post-header comments. Non-block bodies use Prettier's `adjustClause`
// (`indent([line, body])`) wrapped with the header in an outer group, so
// the body drops to its own indented line when the header breaks (a
// comment hardline propagates) or the whole thing overflows — while the
// header group still decides its own flat/break.
let is_block_body = matches!(&stmt.body.kind, StatementKind::BlockStatement(_));
// A C-style `for` collapses its empty block body (`for (…) {}`) — unless an
// own-line directive in the `)`→body gap freezes it.
let body_doc = self.build_statement_head_doc(header_end, stmt.body, || {
// Every arm below that prints a non-block body wraps it in one indent
// (`adjustClause`); nothing continues on the tail's line.
self.build_collapsing_body_doc(stmt.body, ctx.clause_body(false, true))
});
let gap_breaks = self.header_to_body_gap_breaks(header_end, body_start);
let (tail, group_it) = if self.has_comments_to_emit_between(header_end, body_start) {
if matches!(&stmt.body.kind, StatementKind::EmptyStatement(_)) {
// Asked FIRST: the empty-body arm below is guarded by this branch;
// asked later, a comment in the gap would route the `;` through
// `adjustClause` and indent it. An empty body has no clause — prettier returns `";"`
// — so the run stays trailing `)` and the `;` sits flush, which is
// what the shared emitter (`if` / `while` / for-x) delivers.
let mut tail = DocBuf::new();
self.push_empty_statement_gap(&mut tail, header_end, body_start);
(d.concat(&tail), false)
} else if gap_breaks && !is_block_body {
// Non-block body, and something in the gap forces the break: the
// shared indented emitter — each own-line comment on its own
// indented line, then the body — break-safe so a `//` can't swallow
// the next comment or the body (Prettier's `adjustClause`).
let mut tail = DocBuf::new();
self.push_indented_header_to_body_gap(
&mut tail, header_end, body_start, body_doc,
);
(d.concat(&tail), false)
} else if gap_breaks {
// Block body, and something in the gap forces the break — the shared
// header→body gap. The C-style `for` pushes no anchor of its own: its
// `)` is already inside the header doc. Given this branch's guard, the
// gap's separator is the hardline that drops the block to the next line.
let mut tail = DocBuf::new();
self.push_header_to_body_gap(&mut tail, header_end, body_start);
tail.push(body_doc);
(d.concat(&tail), false)
} else {
// Nothing in the gap forces a break, so every comment is a block
// comment already trailing the `)` — built here so the breaking
// paths above don't compute a doc they discard.
let comment_doc = self
.build_inline_comments_between_doc_no_leading_space(header_end, body_start);
if is_block_body {
// Block comment, block body: `) /* c */ {`
(
d.concat(&[d.text(" "), comment_doc, d.text(" "), body_doc]),
false,
)
} else {
// Block comment, non-block body: adjustClause keeps
// `) /* c */ body` flat but drops `\n\t/* c */ body` when the
// header breaks.
(
d.indent_line(d.concat(&[comment_doc, d.text(" "), body_doc])),
true,
)
}
}
} else if matches!(&stmt.body.kind, StatementKind::EmptyStatement(_)) {
// Empty body attaches directly: `);` (no space, no adjustClause).
// Matches the main path (`build_for_statement_with_body_doc`) and Prettier.
(body_doc, false)
} else if is_block_body {
(d.concat(&[d.text(" "), body_doc]), false)
} else {
(d.indent_line(body_doc), true)
};
parts.push(tail);
if group_it {
d.group(d.concat(&parts))
} else {
d.concat(&parts)
}
} else {
// Delegate to the sophisticated version that handles all edge cases
self.build_for_statement_with_body_doc(stmt, span, parens, ctx)
}
}
/// Emit the separator between two comma-separated for-header operands (the
/// `prev_end → curr_start` gap): the comma plus any inter-operand comments,
/// kept on the author's side of the comma — a before-comma block trails the
/// previous operand (`… = 0 /* c */,`), an after-comma comment leads the next
/// one (`, /* c */ x`). A line comment trails the comma via `line_suffix` and,
/// like an own-line block, forces the per-operand break; inline blocks stay
/// width-based (the `line` collapses when the group fits). Mirrors the
/// variable-declarator inter-declarator comment placement. Shared by the
/// multi-declarator init clause and the init/update `SequenceExpression`
/// clauses (`build_for_sequence_clause_doc`).
fn push_for_clause_comma_gap(&self, decl_docs: &mut DocBuf, prev_end: u32, curr_start: u32) {
let d = self.d();
if !self.has_comments_to_emit_between(prev_end, curr_start) {
decl_docs.push(d.text(","));
decl_docs.push(d.line());
return;
}
let comma_pos = self.comma_between(prev_end, curr_start);
if self.has_line_comments_between(prev_end, curr_start) {
// A line comment forces the break, which the gap owns. The whole declarator
// run is wrapped in a `d.indent()` by the caller, so continuation lines need
// no explicit indent text (empty).
self.push_inter_item_line_comment_gap(decl_docs, prev_end, comma_pos, curr_start);
} else {
// Blocks only: a before-comma block trails the previous initializer; the
// width-based `line` separates; after-comma blocks lead the next
// declarator (an own-line block drops to its own line and forces the group
// to break, an inline block hugs `, /* c */ x`). A stranded after-comma
// block (on the comma's line, newline before the next declarator) trails
// the comma instead — preserving the author's placement; prettier relocates
// it before the comma.
self.push_before_comma_blocks(decl_docs, prev_end, comma_pos);
decl_docs.push(d.text(","));
self.push_stranded_after_comma_blocks(decl_docs, comma_pos, curr_start);
decl_docs.push(d.line());
let after: CommentVec<'_> = self
.comments_to_emit_between(comma_pos, curr_start)
.filter(|c| !self.is_stranded_after_comma_block(c, comma_pos, curr_start))
.collect();
self.push_leading_comment_run(
decl_docs,
after.iter().copied(),
curr_start,
LeadingGlue::Adjacent,
);
}
}
/// Prefix a for-header declaration's `continuation` (the declarator run, or the
/// for-of/for-in binding) with its `kind` keyword plus any comment in the
/// keyword→binding gap (`for (const /* c */ x of y)`, `for (let /* c */ i = 0;
/// …)`). Routes through `build_keyword_to_name_continuation` — the same helper the
/// standalone declaration uses — so the gap comment isn't dropped; byte-identical
/// to `kind + " " + continuation` when the gap is comment-free, so a caller's
/// enclosing `group`/`indent` is preserved. A for-header declaration is never
/// `declare`, but its kind may still be two words (`await using`), whose own
/// interior gap is emitted by `build_keyword_words_doc`.
fn build_for_decl_keyword_gap(
&self,
decl: &ast::VariableDeclaration<'_>,
binding_start: u32,
continuation: DocId,
) -> DocId {
self.build_keyword_header_doc(
decl.kind.words(),
decl.span.start,
binding_start,
continuation,
)
}
/// The frozen `(`→init clause doc: the verbatim slice, plus the `[~In]` pair the clause
/// owes when the whole clause IS an `in` binary.
///
/// Those parens are the printer's, not the author's — they sit outside the clause's own
/// node span, so the slice drops them and the header reparses as a for-in head
/// (`for (a in b; ;)` does not parse at all). The header's own `(` is no substitute: it
/// is exactly the delimiter the restriction exists to disambiguate.
///
/// The question is the SLICE's, not the clause node's: a clause whose own root is not an
/// `in` binary can still hand the header one through a `[?In]`-threaded position, and
/// [`Printer::frozen_slice_hands_header_a_bare_in`] states which those are. The walk is
/// asked directly rather than through [`Printer::wrap_frozen_for_init_in`] because the
/// ambient flag that wrapper reads is turned on INSIDE `build_for_init_doc`, which this
/// arm replaces. Nothing else parenthesizes this position — the header's own `(` is the
/// delimiter the restriction exists to disambiguate.
///
/// The clause is the one value head whose sibling rule runs the other way, which is why
/// this is spelled here rather than through [`Printer::build_frozen_expression_doc`]: a
/// `SequenceExpression` clause prints BARE here (`for (a, b; ;)`), where that builder
/// re-synthesizes the grouping pair every other position needs.
fn build_frozen_init_clause_doc(&self, init: &ast::ForInit<'_>, frozen: Span) -> DocId {
let doc = self.build_frozen_node_doc(frozen);
match init {
// This clause IS the init; it needs no ambient flag to know it.
ast::ForInit::Expression(expr)
if self.frozen_slice_hands_header_a_bare_in(expr, frozen.end) =>
{
self.d().parens(doc)
}
ast::ForInit::Expression(_) => doc,
ast::ForInit::VariableDeclaration(_) => doc,
}
}
fn build_for_init_doc(&self, init: &ast::ForInit<'_>) -> DocId {
let d = self.d();
// The init clause is `[~In]`: an `in` binary must be parenthesized so it
// isn't read as the `for (x in y)` separator. Set for the whole init
// subtree (prettier parenthesizes every `in` lexically under the init,
// including inside nested function/class bodies); a nested for-header
// re-enables it for its own init. The `wrap_for_init_in` calls cover the
// positions that build an expression without a `needs_parens` check;
// everything else routes through `needs_parens`, now flag-aware. The
// DECLARATION arm's wrap is not spelled here — it lives inside
// `build_for_init_value_doc`, which has to place the parens relative to the
// grouping shell's trailing comment rather than simply around the value.
let saved_in_for_init = self.in_for_init.replace(true);
let result = match init {
ast::ForInit::VariableDeclaration(decl) => {
// The keyword→first-declarator gap carries a comment (`for (let /* c */
// i = 0; …)`) that must not be dropped — see `build_for_decl_keyword_gap`.
// Built here rather than through that helper because the declarator loop
// needs the keyword's end as its Rule A anchor for the first declarator.
let first_decl_start = decl.declarations[0].span.start;
let (keyword_doc, keyword_end) = self.build_keyword_words_doc(
decl.kind.words(),
decl.span.start,
first_decl_start,
);
let item_span = |j: usize| decl.declarations[j].span;
// Build each declarator's `id = value` doc.
let mut decl_docs: DocBuf = DocBuf::new();
for (i, declarator) in decl.declarations.iter().enumerate() {
if i > 0 {
let prev_end = decl.declarations[i - 1].span.end;
self.push_for_clause_comma_gap(
&mut decl_docs,
prev_end,
declarator.span.start,
);
}
// Rule A over the init clause's declarators, anchored exactly as the
// statement-level list (`build_variable_declaration_doc`): an own-line
// directive in the keyword→first-declarator gap or between two
// declarators freezes the FOLLOWING one over its own node span.
if self.list_item_frozen(keyword_end, &item_span, i) {
decl_docs.push(self.build_frozen_node_doc(declarator.span));
continue;
}
let id_doc = self.build_expression_doc(declarator.id);
let one = if let Some(init) = &declarator.init {
let id_end = declarator.id.span().end;
let init_start = init.span().start;
let eq_pos = self.find_equals_position(id_end, init_start);
// Every branch below builds this declarator's value the SAME way —
// through the header's own shell handler, which owns both the
// trailing-comment gap and the `[~In]` parens. Naming it once is what
// stops the branches drifting: them each spelling out a bare
// `build_expression_doc` is exactly how that gap came to have no
// emitter, dropping every comment written in it.
//
// A header declarator is a declarator: its initializer takes the same
// `ParenContext::VariableInit` pair the statement-level one does
// (`build_init_value_doc`), and skipping it here dropped an
// assignment's clarity parens outright (`for (let i = (a = b); ;)` →
// `let i = a = b`). Prettier's `for` exemption is for the init
// **clause's own expression** (`for (a = b = c; ;)`, handled by the
// Expression arm below), not for a value one binding deeper.
//
// ⚠️ The ambient `[~In]` argument is `false` HERE and only here: the
// header's `in` parens are the shell builder's to place (they must
// land inside the shell's trailing comment, not around it —
// `build_shell_value_doc`), so reading `self.in_for_init` would
// spell that one wrap twice and double the pair
// (`for (let k = (a in b); ;)` → `((a in b))`). This flag answers
// only "does the declarator POSITION parenthesize its value?".
let position_parens = needs_parens(init, ParenContext::VariableInit, false);
// The `=`→value head, resolved exactly as the statement-level
// declarator resolves it ([`Printer::value_head_frozen_span`]): an
// own-line directive in the gap freezes the whole value. Handed to
// the shell builder rather than emitted here, so the slice→`)` gap
// keeps the answer the unfrozen form gives it — the header's
// `ForClauseSeparator` tail, which never defers past the clause's
// `;`. Every branch below routes through `build_value`, so the
// freeze is stated once. The predicate opens on the document-level
// flag, so a directive-free document pays one predicted branch.
let init_frozen = self.value_head_frozen_span(eq_pos + 1, init.span());
// A header declarator is a declarator here too: prettier's
// call-object clause keys on the `VariableDeclarator` parent and
// never asks where the declaration sits, so this marks exactly
// what the statement-level twin marks
// (`build_init_value_doc` → [`Printer::mark_member_call_tail_operand`]),
// the assignment-value mark included.
self.mark_member_call_tail_operand(init);
self.mark_assignment_value(init);
let build_value = || {
let inner = self.build_for_init_value_doc(
init,
declarator.span.end,
position_parens,
init_frozen,
);
self.wrap_value_position_parens(
init,
declarator.span.end,
position_parens,
inner,
)
};
// An init declarator's `=` is a value gap, exactly as the
// statement-level one is (`build_variable_declaration_doc`): an
// own-line JSDoc cast hangs after the `=` rather than printing its
// hardline mid-line, which had no fixed point (pass 1 stranded the
// `(`, pass 2 read the comment as mid-line and collapsed the whole
// header). Marked before any branch below builds the value; the
// flag is span-keyed, so it is read wherever that build lands.
self.mark_jsdoc_cast_value_gap(init);
// The binding→`=` gap, answered exactly as the statement-level
// declarator answers it (`build_variable_declaration_doc`): a
// line comment — or a multiline block the author broke after —
// keeps its place and drops `= value` to a continuation line
// indented one level; anything else stays inline before the `=`
// (`let a /* c */ = 0`). A gap this printer skips is a gap whose
// comment is dropped outright.
let before_eq = self.has_comments_to_emit_between(id_end, eq_pos);
let after_eq = self.has_comments_to_emit_between(eq_pos + 1, init_start);
// prettier's `chooseLayout` fourth disjunct
// ([`Printer::indentable_block_leads_value`]) — a header
// declarator's `=` takes it exactly as a statement-level one does.
// **on page**, unlike `after_eq`: a JSDoc cast's comment is OWNED,
// so the gap emits nothing for it and it still hangs.
let indentable_leads_value =
self.indentable_block_leads_value(eq_pos + 1, init_start);
let continuation = before_eq
.then(|| {
self.build_initializer_line_continuation(
id_end,
eq_pos,
ContinuationValue::Expression(init),
|| {
self.prepend_rhs_comments(
build_value(),
eq_pos + 1,
init_start,
)
},
)
})
.flatten();
if let Some(cont) = continuation {
d.concat(&[id_doc, cont])
} else {
// Everything the `=` still has to decide is the declarator's own
// `printAssignment`, which a for header's declarator takes exactly
// as a statement-level one does — the layout selection, the
// after-`=` comment breaks, and the owned-comment hang all live in
// the shared builder ([`Printer::build_declarator_init_doc`]). Only
// the VALUE differs, and it arrives as the closure above.
self.build_declarator_init_doc(
&DeclaratorInitInputs {
declarator,
init,
id_doc,
gap: DeclaratorEqGap {
id_end,
equals_pos: eq_pos,
init_start,
has_comments_before_eq: before_eq,
has_comments_after_eq: after_eq,
indentable_leads_value,
},
},
&build_value,
)
}
} else {
id_doc
};
decl_docs.push(one);
}
// Multiple declarators break on width: they stay on one line when the init
// clause fits and drop onto their own lines (continuation indented one
// level) when it doesn't — matching prettier's `printVariableDeclaration`. A
// declarator whose `=` comment forces a break also breaks the group (its
// hardline propagates).
let body = if decl.declarations.len() > 1 {
d.indent(d.concat(&decl_docs))
} else {
d.concat(&decl_docs)
};
let header = d.concat(&[
keyword_doc,
self.build_keyword_to_name_continuation(keyword_end, first_decl_start, body),
]);
if decl.declarations.len() > 1 {
d.group(header)
} else {
header
}
}
ast::ForInit::Expression(expr) => {
// Sequence expressions in for loop init don't need outer parens
// e.g., `for (i = 0, j = 0; ...)` not `for ((i = 0, j = 0); ...)`.
// Same dispatch as build_for_update_doc, but each operand is `[~In]`
// wrapped (`wrap_for_init_in`).
//
// The init is a statement-head position for the `let [` lookahead
// restriction too (`for ((let)[0] = 1; ;)`), so a `let` heading it keeps
// its parens — as does a `using` / `let` heading a cast chain, which bare
// would open a declaration (`for ((using) as T; ;)`).
//
// TODO: the clause value is built with no shell builder, so a grouping
// shell the author wrote around the WHOLE clause has its trailing gap
// answered by the clause→`;` emitter instead — a `//` in it rides past the
// separator, and the next pass, reading it from the header's own gap, puts
// it on its own line (`for ((b // c⏎); ;)`, two fixed points for one
// source). A header DECLARATOR answers the same shell inside the construct
// ([`Printer::build_for_init_value_doc`]), as does a sequence clause's last
// operand; the bare clause and the update clause want that routing too.
self.with_expr_stmt_paren_target(self.for_init_head_target(expr), || {
self.build_for_expr_clause(expr, |e| {
self.wrap_for_init_in(e, self.build_expression_doc(e))
})
})
}
};
self.in_for_init.set(saved_in_for_init);
result
}
/// The for-in/for-of header's LEFT clause.
///
/// Rule: an own-line directive in the `(`→left gap freezes the clause WHOLE
/// ([`Printer::value_head_frozen_span`]) — the same delimiter-owned value head as a
/// `for` header's init. The slice is the clause's own span, so the `in`/`of` keyword
/// and the iterable stay parent-owned and normalize; the `(async)` clarity parens are
/// the printer's, so they wrap the frozen slice rather than ride inside it.
///
/// Span-shaped for the same reason the init clause is: a left is a
/// `VariableDeclaration` as often as a pattern, so the freeze is resolved and emitted
/// once here rather than per arm below.
fn build_for_in_of_left_doc(
&self,
left: &ast::ForInOfLeft<'_>,
wrap_async_paren: bool,
spans: &ForInOfSpans,
) -> DocId {
let d = self.d();
// A `let` heading the clause keeps its parens. Both head forms restrict it, and
// prettier draws one line across them, so tsv does too: the for-of head's own
// `[lookahead ∉ { let }]` makes a bare `for (let of x)` a syntax error, and a
// for-in head — restricted only on `let [` — takes the same paren, matching
// prettier's `startsWithNoLookaheadToken` clause, which finds ANY enclosing
// for-in/of. Unlike `(async)`, the paren can belong to a node *inside* the clause
// (`for ((let).a of x)`), so it is handed to that node rather than wrapped here.
let let_target = match left {
ast::ForInOfLeft::Pattern(expr) => self.for_in_of_let_head_target(expr),
ast::ForInOfLeft::VariableDeclaration(_) => None,
};
if let Some(open) = spans.open_paren
&& let Some(frozen) =
self.value_head_frozen_span(open + 1, Span::new(spans.left_start, spans.left_end))
{
// A frozen slice is verbatim, so there is no interior to hand the target to:
// the parens go around the WHOLE slice, as the expression statement's
// nested-target path does for the same reason. Only when the target IS the
// whole slice, though — a `let` heading a member or call is not the leftmost
// BYTE of its node, whose span opens at the author's own `(`
// (`for ((let).a of x)` freezes as `(let).a`), and wrapping that again would
// double the paren INSIDE an ignored region. `(async)` never hits this: an
// identifier's span stops at the word, so the shell really is the printer's.
let doc = self.build_frozen_node_doc(frozen);
let wrap_let_paren = let_target.is_some_and(|target| target.start == frozen.start);
return if wrap_async_paren || wrap_let_paren {
d.parens(doc)
} else {
doc
};
}
match left {
ast::ForInOfLeft::VariableDeclaration(decl) => {
let Some(declarator) = decl.declarations.first() else {
// A for-in/of head always binds something (`for (const of x)` is a
// parse error), so there is no declarator to bound a gap search at
// and nothing to print but the kind. `as_str()` is the joined text —
// the very thing `words()` exists to avoid, since it emits `await
// using`'s interior gap as a fixed space and would drop a comment
// authored there. Safe only because this arm is unreachable; assert
// that rather than let a future caller reach it silently.
debug_assert!(
false,
"a for-in/of variable declaration always has a declarator"
);
return d.concat(&[d.text(decl.kind.as_str()), d.text(" ")]);
};
// The keyword→binding gap carries a comment (`for (const /* c */ x of y)`)
// that must not be dropped — see `build_for_decl_keyword_gap`. Covers
// `const`/`let`/`var`/`using`/`await using` uniformly.
let id_doc = self.build_expression_doc(declarator.id);
self.build_for_decl_keyword_gap(decl, declarator.span.start, id_doc)
}
// `for ((async) of x)` keeps parens around the bare `async` identifier
// (the caller decides via `wrap_async_paren` — a non-await for-of, where
// bare `for (async of x)` is a syntax error).
ast::ForInOfLeft::Pattern(expr) => {
let doc = self
.with_expr_stmt_paren_target(let_target, || self.build_expression_doc(expr));
if wrap_async_paren { d.parens(doc) } else { doc }
}
}
}
/// Whether the for-in/for-of LHS is a bare `async` identifier that must be
/// parenthesized: only in a **non-await for-of** (bare `for (async of x)` is a
/// syntax error — the parser can't tell it from `for (async ... )`). Mirrors
/// prettier's identifier rule (parentheses/identifier.js:
/// `name === "async" && !parent.await && parent.type === "ForOfStatement"`).
fn for_lhs_needs_async_paren(
&self,
left: &ast::ForInOfLeft<'_>,
keyword: &str,
is_await: bool,
) -> bool {
keyword == "of"
&& !is_await
&& matches!(
left,
ast::ForInOfLeft::Pattern(Expression { kind: ExpressionKind::Identifier(id), .. })
if self.with_ident_name(id, |s| s == "async")
)
}
/// Get the end position of a ForInit
fn get_for_init_span_end(&self, init: &ast::ForInit<'_>) -> u32 {
match init {
ast::ForInit::VariableDeclaration(decl) => decl.span.end,
ast::ForInit::Expression(expr) => expr.span().end,
}
}
}