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
// Object expression printing for TypeScript
//
// Handles printing of object expressions with:
// - Width-based wrapping via doc-builder
// - Comment preservation (block and line comments)
// - Property shorthand detection
// - String key normalization (unquote valid identifiers)
// - Blank line preservation between properties
use crate::ast::{self, Expression, ExpressionKind, Literal, LiteralValue};
use crate::printer::comments::ValueGap;
use crate::printer::expressions::assignment::{AssignmentLeft, RhsCommentInfo};
use crate::printer::expressions::literals::is_valid_js_identifier;
use crate::printer::{CommentVec, Printer, StandaloneGlue};
use smallvec::{SmallVec, smallvec};
use tsv_lang::Span;
use tsv_lang::TAB_WIDTH;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::after_operator::hang_after_operator;
use tsv_lang::doc::arena::DocId;
use tsv_lang::printing::visual_width;
use tsv_lang::source_scan::find_char_skipping_comments;
/// What an object or array LITERAL is printed as.
///
/// A literal is an expression everywhere but one position: a compound assignment's left
/// (`({ a } += x)`), which ecma262 never reparses as a pattern (§13.15.1), so the literal
/// stays — acorn keeps it, and so does tsv. Prettier's TypeScript parser converts it to a
/// pattern anyway and prints it as one, and tsv prints that layout around the literal it
/// keeps ([`Printer::build_compound_target_doc`]): no authored first-line expansion, a
/// break on a directly nested literal, an `=` value or element printed as the default
/// prettier reads there. Passed down the literal's own builders as a parameter, never held
/// as printer state, so a doc built for one role is never read back under the other.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(in crate::printer) enum LiteralRole {
/// An ordinary object or array literal.
Expression,
/// A literal on a compound assignment's left, or nested in one through property values
/// and elements.
CompoundTarget,
}
impl LiteralRole {
/// Where a literal's element or property value STOPS PRINTING in this role — the anchor
/// every list seam of the literal takes for the trailing run
/// (`docs/comments.md` §The element-comma seam), and the end of the span its expansion
/// gates read as the item's own.
///
/// The span end, except for an `=` value in a compound target: that value prints as the
/// default prettier reads there ([`Printer::build_compound_target_doc`]), whose doc stops
/// at its own value, as [`Expression::printed_end`] says of an `AssignmentPattern`. The
/// assignment's span runs on over the paren shell the parser erased from that value
/// (`[a = (b /* c */)] += x`), which holds nothing but `)`, whitespace and comments, and
/// which the ordinary role's assignment prints itself — so anchoring there in this role
/// leaves the shell's comments to nobody, and anchoring inside in the other prints them
/// twice. A frozen element or value is read through its slice instead
/// ([`Printer::element_claim_anchor`]): the slice prints the shell itself.
pub(in crate::printer) fn printed_end(self, expr: &Expression<'_>) -> u32 {
match (self, &expr.kind) {
(Self::CompoundTarget, ExpressionKind::AssignmentExpression(assign))
if assign.operator == ast::AssignmentOperator::Assign =>
{
assign.right.printed_end()
}
_ => expr.span().end,
}
}
/// [`Self::printed_end`] for an object property: [`ast::ObjectProperty::value_end`],
/// with the value read in this role.
pub(in crate::printer) fn property_printed_end(self, prop: &ast::ObjectProperty<'_>) -> u32 {
match prop {
ast::ObjectProperty::Property(p) => self.printed_end(p.value),
ast::ObjectProperty::SpreadElement(_) => prop.value_end(),
}
}
}
/// Whether a value inside a [`LiteralRole::CompoundTarget`] literal takes the target's own
/// print: a nested object or array literal (which prettier reads as a nested pattern), or
/// an `=` assignment (which it reads as a default, printed as that default). Any other value — a
/// compound assignment the literal holds included (`[(a += b)]`) — prints as it would in
/// any literal.
pub(in crate::printer) fn is_compound_target_value(expr: &Expression<'_>) -> bool {
match &expr.kind {
ExpressionKind::ObjectExpression(_) | ExpressionKind::ArrayExpression(_) => true,
ExpressionKind::AssignmentExpression(assign) => {
assign.operator == ast::AssignmentOperator::Assign
}
_ => false,
}
}
/// Whether a [`LiteralRole::CompoundTarget`] object breaks for a nested pattern —
/// prettier's `shouldBreak` for an `ObjectPattern` (`print/object.js`): some property's
/// value is directly an object or array pattern. A default (`a: [b] = c`) is not one.
fn compound_target_object_breaks(obj: &ast::ObjectExpression<'_>) -> bool {
obj.properties.iter().any(|prop| {
matches!(
prop,
ast::ObjectProperty::Property(p)
if matches!(
p.value.kind,
ExpressionKind::ObjectExpression(_) | ExpressionKind::ArrayExpression(_)
)
)
})
}
impl<'a> Printer<'a> {
/// Build a Doc for an object expression
///
/// Handles comments between properties, blank line preservation, and trailing comments.
pub(in crate::printer) fn build_object_doc(
&self,
obj: &ast::ObjectExpression<'_>,
obj_span: Span,
) -> DocId {
self.build_object_doc_as(obj, obj_span, LiteralRole::Expression)
}
/// [`Self::build_object_doc`] in a [`LiteralRole`].
pub(in crate::printer) fn build_object_doc_as(
&self,
obj: &ast::ObjectExpression<'_>,
obj_span: Span,
role: LiteralRole,
) -> DocId {
let d = self.d();
// Check for comments inside the object.
//
// **on page**: this is the object-wide fast gate, and it short-circuits the
// *layout* work too — a `false` here routes every property to the plain
// `key: value` form. An owned annotation on a value is on the page and hangs the
// value onto a continuation line exactly as any other own-line comment does, so
// the gate has to see it. (`build_object_doc_expanded` carries the twin gate.)
let has_comments = self.has_comments_on_page_between(obj_span.start, obj_span.end);
// Check if object contains line comments or block comments on their own line (force multiline)
let has_line_comments = self.has_line_comments_between(obj_span.start, obj_span.end);
// Check for block comments on their own line (not same line as any property).
// Only relevant when the object has comments at all — otherwise there are no
// block comments to be standalone, so skip the per-property span collection
// (the common comment-free object pays nothing). The glue half is the SOURCE
// reading: the object's own comma is re-emitted structure outside every property
// span, so a comment it follows is not standalone — see `StandaloneGlue` for why
// the type literal answers this differently.
let has_standalone_block_comment = has_comments && {
let property_spans: SmallVec<[_; 8]> = obj
.properties
.iter()
.map(ast::ObjectProperty::span)
.collect();
match role {
LiteralRole::Expression => self.has_standalone_block_comment(
obj_span.start,
obj_span.end,
&property_spans,
StandaloneGlue::Source,
),
// The target's key→`:` gap prints its block glued (`k /* c */:`), so a block
// the author gave a line of its own there is no line of its own in the output.
// With no authored first-line break to hold an expansion, breaking for it
// collapses on the next pass; the `=` pattern prints it collapsed in one.
LiteralRole::CompoundTarget => self
.comments_on_page_between(obj_span.start, obj_span.end)
.any(|c| {
c.is_block
&& !self.comment_in_property_key_colon_gap(obj, c.span)
&& self.block_comment_owns_its_line(
c,
property_spans.iter().any(|s| s.start >= c.span.end),
)
}),
}
};
if obj.properties.is_empty() {
// Handle empty object with comments
return self.build_empty_braces_inline_with_comments_doc(obj_span);
}
// Check if source has newline after opening brace.
//
// ⚠️ This rule is the object LITERAL's alone — the object PATTERN deliberately has
// no counterpart, and the asymmetry is prettier's: it guards the whole preserve on
// `node.type !== "ObjectPattern"` (`print/object.js`). A pattern that opened on an
// authored newline would also be its own second fixed point, since the expanded
// form reprints one newline and never the author's blank
// (`patterns.rs::collection_formatting_hints`). Don't mirror this line over there.
//
// A compound target takes the pattern's own break instead, which the same group
// carries ([`compound_target_object_breaks`]).
let first_prop_start = obj.properties[0].span().start;
let has_source_newline = match role {
LiteralRole::Expression => {
self.has_newline_between(obj_span.start + 1, first_prop_start)
}
LiteralRole::CompoundTarget => compound_target_object_breaks(obj),
};
// Decide the formatting strategy
// must_break: conditions that require hardlines (comments)
// has_source_newline: prefers expanded, but uses group_break for proper propagation
//
// A property value carrying its own newline — a line-continuation string, a
// multiline template — needs no term here: its text node reports
// `CachedWidth::HasNewline`, so `will_break` breaks this object exactly as
// prettier's `literalline`-borne `breakParent` does.
let must_break = has_line_comments || has_standalone_block_comment;
if has_comments || must_break {
// Comment-aware path
// Use hardlines when must_break, use line() when only has_comments
// This allows inline objects with block comments to stay inline if they fit
let mut parts = d.pooled_docbuf();
let mut prev_end = obj_span.start + 1; // After opening brace
// The previous property's run displaced past its comma — behind a spread's
// stripped-paren interior — and whether it was: the one leads this property
// (`Printer::push_run_leading_next_item`), and the other moves where an author
// blank before it is measured from.
let mut prev_leads_next: SmallVec<[&tsv_lang::Comment; 2]> = SmallVec::new();
let mut prev_behind_interior = false;
// A comment trailing the opening `{` is kept on the `{` line when the
// object expands — both a line comment and a block comment before a
// first property on a later line (divergence from prettier, which
// relocates it to its own line as the first property's leading
// comment). See conformance_prettier_ts_comments.md §Comment relocation (Object
// literal `{`).
let (brace_line_prefix, brace_pull_pos) =
self.delimiter_line_comment_prefix_object(obj_span.start, first_prop_start);
// The prefix is only emitted on the break path, so a fired pull forces
// must-break (an expanding object with a block on the `{` line breaks
// via has_source_newline, not the must_break conditions above).
let must_break = must_break || brace_pull_pos.is_some();
for (i, prop) in obj.properties.iter().enumerate() {
let prop_start = prop.span().start;
let is_first = i == 0;
// The rest of the gap, resuming where the previous property's trailing run
// stopped — the element-comma partition (see `collect_item_leading_comments`).
let comments = self.collect_item_leading_comments(
prev_end,
prop_start,
is_first.then_some(brace_pull_pos).flatten(),
);
// For non-first properties, add separator. An author BLANK line takes the
// hardline separator even when nothing else forces the break: a soft
// `line` cannot carry a blank, so routing a blank gap through `line()`
// DROPS it — and the comment-free path below preserves the identical
// authoring (`{ a,⏎⏎b }`), so a commented object dropping it was the two
// paths disagreeing about one gap. Preserving it forces the object open,
// which is what the comment-free path's `literalline` does too.
if !is_first {
if prev_behind_interior {
// The comma was emitted against the spread, ahead of its interior,
// so a comma the author gave a line of its own is not a line here
// and a blank below it is still the author's.
if self.blank_before_next_item(prev_end, prop_start) {
parts.push(d.literalline());
}
parts.push(d.hardline());
} else if must_break || self.item_gap_has_blank_line(prev_end, prop_start) {
// Must break: check for blank line preservation
self.push_item_blank_separator(&mut parts, prev_end, prop_start);
} else {
// May stay inline: use line() for group-based breaking
parts.push(d.line());
}
}
// Print the leading-comment run on the shared rule (prettier's
// `printLeadingComment`), the one the block / class / interface / member
// lists use: the separator after each comment is keyed on the source around
// *that comment*, never on where the property starts. Keying it on the
// property split a run the author glued (`/* c1 */ /* c2 */⏎x: 1`) — the bug
// family docs/comments.md §"Leading comments" names. The emitter owns the
// blank-line preservation on both sides
// (between two comments, and between the last one and the property), and
// emits a soft `line` where the run may still collapse, so an object that
// stays inline is decided by its group rather than by a hardcoded space.
// TODO: the object literal is a third case in the array-family / params-family
// split (docs/comments.md §Array family vs params family) and it is not named
// there. It gives a property no group of its own, so a leading run's soft
// `line` breaks — `p1: 1,⏎/* c */⏎p2: 2` — where the ARRAY family collapses it
// onto the element (`'aaaa',⏎/* c */ 'bbbb'`) from the identical authoring.
// Prettier relocates the block before the comma at both sites (the sanctioned
// §Array element end-of-line block comment rule, currently cataloged for the
// array only), so its own grouping is not observable here and neither form is
// validated against it. Settle which family the object literal belongs to
// before cataloging the object / specifier / enum face of that divergence —
// sanctioning the own-line form first would pin whichever one this is.
self.push_run_leading_next_item(&mut parts, &prev_leads_next, prop_start);
self.push_leading_comments_before(&mut parts, &comments, prop_start);
// Build property doc — a preceding format-ignore directive keeps the
// property's source verbatim (trailing comment/comma handled normally).
// Same window as the leading scan: a directive trailing the previous
// property is inert by the placement floor (`is_honored_directive`), not
// by where the window starts.
// Resolved once as the SLICE rather than a bool, because the trailing
// seam below needs the same answer (`Printer::element_claim_anchor`).
let frozen_span = self
.member_gap_frozen(prev_end, prop_start)
.then(|| prop.span());
parts.push(match frozen_span {
Some(slice) => self.raw_source_doc(slice),
None => self.build_object_property_doc(prop, has_comments, role),
});
// Trailing comments around the separator comma — block comments
// before the comma, the comma, an after-comma block on the last
// property preserved in place (`trailingComma: 'none'`), then line
// comments as a suffix. Shared with the destructuring-pattern
// builders via `collect_trailing_comments` /
// `push_element_comma_trailing`.
// Under a freeze the verbatim slice has already printed the property's
// stripped-paren interior, so the seam must start at the END of that
// slice — `value_end()` is inside it, and re-claiming a comment already
// on the page prints it twice, then three times, then four: the emitted
// form still carries the directive, so it re-freezes and the run grows
// on every pass.
let prop_end =
Self::element_claim_anchor(frozen_span, self.property_printed_end(prop, role));
let upper_bound = obj
.properties
.get(i + 1)
.map_or(obj_span.end, |next| next.span().start);
let is_last = i == obj.properties.len() - 1;
// A spread's stripped-paren interior: the own-line comments its own doc
// leaves behind are the object's share, each a sibling line the object
// cannot stay collapsed around, and the run past the `)` follows them
// (`Printer::push_element_share_and_run`). A frozen spread's verbatim slice
// already printed its interior, so it has none.
let trailing = self.collect_element_trailing_comments(
prop_end,
upper_bound,
is_last,
prop.paren_interior().filter(|_| frozen_span.is_none()),
);
let comma = (!is_last).then(|| d.text(","));
self.push_element_comma_trailing(&mut parts, &trailing, comma);
prev_end = trailing.end_pos;
prev_behind_interior = trailing.is_behind_interior();
prev_leads_next = trailing.leads_next;
}
// Trailing comments before the closing brace, through the shared end-of-body
// run (`Printer::push_trailing_body_comments`) rather than a copy of it:
// the same walk, the same "already trailed by the last property" question, and
// the same stripped-shell blank anchor every other container gets. The copy
// this replaces had drifted from it on all three. An object that may still
// COLLAPSE takes a soft `line` separator its group decides; a broken one takes
// the hardline, like every other body.
let closing_brace_pos = obj_span.end - 1;
let separator = if must_break { d.hardline() } else { d.line() };
self.push_trailing_closer_comments(
&mut parts,
prev_end,
closing_brace_pos,
false,
separator,
);
if must_break {
// Forced multiline - use hardlines for predictable formatting
let inner = d.concat(&[d.hardline(), d.concat(&parts)]);
self.build_delimited_doc(
d.text("{"),
brace_line_prefix,
d.indent(inner),
d.hardline(),
d.text("}"),
)
} else {
// May stay inline - use group with bracketSpacing boundaries for
// width-based breaking: a space when flat (`{ foo }`), a newline when
// it breaks (brace_line_prefix is `None` here — pulling implies must_break).
let inner = d.concat(&[d.line(), d.concat(&parts)]);
self.wrap_object_braces(d.indent(inner), d.line(), has_source_newline)
}
} else {
// No comments, no forced multiline: use width-based wrapping with soft lines
let mut parts = d.pooled_docbuf();
// Whether each gap between consecutive properties carries an author blank line.
// Derived ONCE per gap: the loop below asks the same question from both sides —
// "is there a blank before me?" at property `i`, and "before the next one?" when
// emitting `i`'s separator — which is the same gap, and computing it twice invites
// the two answers to drift apart.
//
// Through the shared predicate rather than a raw `is_next_line_empty`, for the
// stripped-shell anchor it carries (`Printer::item_gap_has_blank_line`): a value's
// erased grouping parens are not an author blank (`{ k: (1⏎⏎), b }`), and a copy
// of this scan is how the comment-bearing path above and this one came to answer
// that differently. With no comment in the gap the bound is the next property
// either way, so the two spellings agree by construction.
let gap_blank: SmallVec<[bool; 8]> = obj
.properties
.windows(2)
.map(|pair| self.item_gap_has_blank_line(pair[0].value_end(), pair[1].span().start))
.collect();
for (i, prop) in obj.properties.iter().enumerate() {
// Check for blank line before this property (preserved in multiline).
let has_blank_before = i > 0 && gap_blank[i - 1];
if has_blank_before {
// Blank line preservation
parts.push(d.literalline());
parts.push(d.hardline());
}
// Build property doc
let prop_doc = self.build_object_property_doc(prop, has_comments, role);
parts.push(prop_doc);
// Add comma and line break
if i < obj.properties.len() - 1 {
parts.push(d.text(","));
// Only add a line break when the next property has no blank line before
// it — the blank's own `literalline` + `hardline` already separates them.
if !gap_blank[i] {
parts.push(d.line());
}
}
// No trailing comma on the last property (trailingComma: 'none').
}
// Width-based wrapping: bracketSpacing boundaries (space when flat
// `{ foo }`, newline when broken).
let inner = d.concat(&[d.line(), d.concat(&parts)]);
self.wrap_object_braces(d.indent(inner), d.line(), has_source_newline)
}
}
/// Wrap content in braces with appropriate grouping for object expressions.
///
/// Uses `group_break` when source had newlines (propagates break upward),
/// otherwise uses `group` for width-based breaking.
fn wrap_object_braces(
&self,
indented_content: DocId,
closing_line: DocId,
has_source_newline: bool,
) -> DocId {
let d = self.d();
let object_doc = d.concat(&[d.text("{"), indented_content, closing_line, d.text("}")]);
if has_source_newline {
d.group_break(object_doc)
} else {
d.group(object_doc)
}
}
/// Build a Doc for an object expression with forced expansion (hardlines).
///
/// Used by chain arg formatting when we need the object to expand internally
/// with hardlines so fits() can correctly measure the first line.
/// Produces: `{\n prop,\n}` with actual hardlines.
pub(in crate::printer) fn build_object_doc_expanded(
&self,
obj: &ast::ObjectExpression<'_>,
span: Span,
) -> DocId {
let d = self.d();
// A commented object hands off to `build_object_doc` wholesale: the loop below
// emits property docs only, so every structural comment — the `{`→first-property
// gap, the inter-property gaps, the trailing gap before `}`, and a dangling
// comment in an empty `{}` — would be DROPPED here (content loss, not
// relocation), which is why the gate also precedes the empty-object arm. The
// forced-hardline form the caller wants for its `fits()` measurement is only ever
// needed on the comment-free path, and that is exactly where the two agree.
// **on page**, in lockstep with the twin gate in `build_object_doc`.
if self.has_comments_on_page_between(span.start, span.end) {
return self.build_object_doc(obj, span);
}
if obj.properties.is_empty() {
return d.text("{}");
}
let mut parts: DocBuf = DocBuf::new();
for (i, prop) in obj.properties.iter().enumerate() {
// Comment-free past the gate, so the per-property comment queries are dead.
let prop_doc = self.build_object_property_doc(prop, false, LiteralRole::Expression);
parts.push(prop_doc);
if i < obj.properties.len() - 1 {
parts.push(d.text(","));
parts.push(d.hardline());
}
// No trailing comma on the last property under `trailingComma: 'none'`.
}
d.concat(&[
d.text("{"),
d.indent_hardline(d.concat(&parts)),
d.hardline(),
d.text("}"),
])
}
/// Build a Doc for an object property (either Property or SpreadElement)
///
/// `has_comments` is the object-wide comment-presence flag (one binary search
/// over the whole `{…}` span); it gates the per-property key→value comment
/// queries in `build_property_doc`.
fn build_object_property_doc(
&self,
prop: &ast::ObjectProperty<'_>,
has_comments: bool,
role: LiteralRole,
) -> DocId {
match prop {
ast::ObjectProperty::Property(p) => self.build_property_doc(p, has_comments, role),
ast::ObjectProperty::SpreadElement(s) => self.build_spread_doc(s),
}
}
/// An object property's value doc for an arm that does NOT route through
/// [`Printer::build_assignment_layout`] — the arms below that emit their own
/// `key: value` shell.
///
/// That builder marks the value for itself; every other arm owes the same mark,
/// because `isObjectProperty` is one of prettier's `shouldIndentIfInlining` parents
/// (`shouldNotIndent`, `print/binaryish.js`) and the mark is the only way a binary value learns it
/// ([`Printer::mark_assignment_value`] — tsv has no parent pointer). An arm that
/// skipped it printed the property's chain with the continuation indent of an
/// UNEXEMPT position while its sibling arm printed the same property flush, which is
/// one construct with two layouts.
fn build_object_property_value_doc(
&self,
value: &Expression<'_>,
frozen: Option<Span>,
) -> DocId {
self.mark_assignment_value(value);
match frozen {
Some(frozen) => self.build_frozen_expression_doc(value, frozen),
None => self.build_expression_doc(value),
}
}
/// [`Self::build_object_property_value_doc`], for a value a compound target prints its
/// own way ([`is_compound_target_value`]) when `target` says so.
fn build_property_value_doc_as(
&self,
value: &Expression<'_>,
frozen: Option<Span>,
target: bool,
) -> DocId {
if target && frozen.is_none() {
self.mark_assignment_value(value);
return self.build_compound_target_doc(value);
}
self.build_object_property_value_doc(value, frozen)
}
/// [`LiteralRole::property_printed_end`] read through a `:`→value head freeze: a frozen
/// value's verbatim slice prints its whole span, the value shell included, so the trailing
/// run starts past it ([`Self::property_value_frozen_span`]).
fn property_printed_end(&self, prop: &ast::ObjectProperty<'_>, role: LiteralRole) -> u32 {
let printed_end = role.property_printed_end(prop);
match prop {
ast::ObjectProperty::Property(p)
if !p.shorthand
&& printed_end != prop.value_end()
&& self
.property_value_frozen_span(p, self.property_key_region_end(p))
.is_some() =>
{
prop.value_end()
}
_ => printed_end,
}
}
/// Whether `span` lies in some regular property's key→`:` gap.
fn comment_in_property_key_colon_gap(
&self,
obj: &ast::ObjectExpression<'_>,
span: Span,
) -> bool {
obj.properties.iter().any(|prop| match prop {
ast::ObjectProperty::Property(p) if !p.shorthand && !p.method => {
let key_region_end = self.property_key_region_end(p);
key_region_end <= span.start && span.end <= self.find_colon_after(key_region_end)
}
_ => false,
})
}
/// Where a regular property's KEY region ends: past the `]` of a computed key, else at
/// the key's own end — the `key_region_end` [`Self::build_property_doc`] scans from.
fn property_key_region_end(&self, prop: &ast::Property<'_>) -> u32 {
if prop.computed {
self.find_closing_bracket_after(prop.key.span().end) + 1
} else {
prop.key.span().end
}
}
/// The verbatim slice a regular property's value prints as: the `:`→value head freeze
/// ([`Printer::value_head_frozen_span`]) on every arm of [`Self::build_property_doc`] but
/// the key→`:` own-line one, which builds the value unfrozen. One answer for the builder
/// and the trailing seam, so the seam never anchors past a shell the value's doc left
/// unprinted.
fn property_value_frozen_span(
&self,
prop: &ast::Property<'_>,
key_region_end: u32,
) -> Option<Span> {
if !self.has_format_ignore {
return None;
}
let colon_pos = self.find_colon_after(key_region_end);
if self.comments_force_own_line_between(key_region_end, colon_pos) {
return None;
}
self.value_head_frozen_span(colon_pos + 1, prop.value.span())
}
/// Build a Doc for a single property
///
/// `has_comments` is the object-wide comment-presence flag: when it is false,
/// no comment lies anywhere in the object span, so none can lie in this
/// property's key→value gap either — the colon scan and the per-gap comment
/// lookups are skipped (canonical reference: `build_params_doc_with_comments`).
fn build_property_doc(
&self,
prop: &ast::Property<'_>,
has_comments: bool,
role: LiteralRole,
) -> DocId {
let d = self.d();
// For computed keys, use expression doc (preserves string quotes)
// For regular keys, use property key doc (converts strings to bare identifiers when valid)
// Track where comments after the key region end (after `]` for computed, after key for normal)
let key_region_end;
let key_doc = if prop.computed {
// Assignment expressions need parens in computed keys: {[(a = b)]: c}
let (doc, end) = self.build_computed_key_bracket_doc(
prop.span.start,
prop.key,
Some(super::ParenContext::ComputedPropertyKey),
|| self.build_computed_key_expr_doc(prop.key),
);
key_region_end = end;
doc
} else {
key_region_end = prop.key.span().end;
self.build_property_key_doc(prop.key)
};
// Add getter/setter prefix if applicable, preserving comments between
// keyword and name (e.g., `get /* c */ a()`)
let key_doc = match prop.kind {
ast::PropertyKind::Get | ast::PropertyKind::Set => {
let kind_text = if matches!(prop.kind, ast::PropertyKind::Get) {
"get "
} else {
"set "
};
let mut kw_parts = DocBuf::new();
self.push_accessor_keyword_doc(
&mut kw_parts,
kind_text,
prop.span.start,
prop.key.span().start,
prop.computed,
);
kw_parts.push(key_doc);
d.concat(&kw_parts)
}
ast::PropertyKind::Init => key_doc,
};
// Handle getter/setter vs method vs regular property
if matches!(prop.kind, ast::PropertyKind::Get | ast::PropertyKind::Set) {
// Getter/setter: `get x() {}` or `set x(v) {}`
if let ExpressionKind::FunctionExpression(func) = &prop.value.kind {
let func_doc = self.build_function_doc_body(func);
// Comments between key and type params/parens: `get [x] /* c */() {}`
// or `get x/* c */ <T>() {}`
match self.build_signature_head_comments_opt(
key_region_end,
func.type_parameters.as_ref(),
func.params_start,
) {
Some(comments) => d.concat(&[key_doc, comments, func_doc]),
None => d.concat(&[key_doc, func_doc]),
}
} else {
key_doc
}
} else if prop.method {
// Method shorthand: `foo() {}`, `async foo() {}`, `*gen() {}`, or `async *gen() {}`
if let ExpressionKind::FunctionExpression(func) = &prop.value.kind {
let func_doc = self.build_function_doc_body(func);
// Build prefix: async? + *?, preserving comments after `async`
// (e.g., `async /* c */ m()`)
let key_start = prop.key.span().start;
let mut parts = DocBuf::new();
let mut cursor = prop.span.start;
if func.r#async {
self.push_member_keyword_doc(&mut parts, "async ", &mut cursor, key_start);
}
if func.generator {
self.push_generator_star_doc(&mut parts, cursor, key_start, prop.computed);
} else if func.r#async {
// Comments before the name (bounded at `[` for computed keys,
// whose inner comments the bracket builder handles)
let bound = self.computed_key_name_bound(cursor, key_start, prop.computed);
self.push_pre_name_comments_doc(&mut parts, cursor, bound);
}
parts.push(key_doc);
// Handle comments between method name and type params/parameters: foo /* comment */ ()
// Use key_region_end (after `]` for computed) to avoid re-finding bracket comments
self.push_signature_head_comments(
&mut parts,
key_region_end,
func.type_parameters.as_ref(),
func.params_start,
);
parts.push(func_doc);
d.concat(&parts)
} else {
// Fallback for malformed AST
let value_doc = self.build_object_property_value_doc(prop.value, None);
d.concat(&[key_doc, d.text(": "), value_doc])
}
} else if prop.shorthand {
// Shorthand with an initializer (`{a = 1}`) — a `CoverInitializedName`, whose
// early error tsv defers, so the value is an `AssignmentExpression` spanning the
// whole `a = 1` (an `AssignmentPattern` where a pattern was refined in place).
//
// ⚠️ Printed by the VALUE's own doc, not reassembled from `key + " = " + right`:
// that spelling emits no name→`=` gap, so a comment the author wrote there
// (`{a /* c */ = 1}`) had no emitter at all. It survived only because the
// element-comma seam, anchored at the KEY's end, claimed it and printed it past
// the initializer — a relocation across the binding, and a DROP the moment the
// anchor was corrected. The value's doc prints the key and that gap alike, and
// is not parenthesized here: the shorthand form is the syntax.
match &prop.value.kind {
ExpressionKind::AssignmentExpression(_) if role == LiteralRole::CompoundTarget => {
self.build_compound_target_doc(prop.value)
}
ExpressionKind::AssignmentExpression(_) | ExpressionKind::AssignmentPattern(_) => {
self.build_expression_doc(prop.value)
}
_ => key_doc,
}
} else {
// Regular property.
//
// A compound target's nested literal or `=` value prints as prettier prints the
// pattern it reads there — no pair around the default, the nested literal under
// the target's own rules — on a plain `key: value` line: a pattern value has no
// layout of its own to choose.
let target =
role == LiteralRole::CompoundTarget && is_compound_target_value(prop.value);
// Zero-comment fast gate: when the object has no comments at all, none
// can lie between this key and its value, so skip the colon scan and the
// per-gap comment lookups and emit the plain `key: value` layout directly
// (canonical reference: build_params_doc_with_comments).
if !has_comments {
if target {
let value_doc = self.build_property_value_doc_as(prop.value, None, true);
return d.concat(&[key_doc, d.text(": "), value_doc]);
}
let needs_parens =
self.needs_parens(prop.value, super::ParenContext::ObjectPropertyValue);
return if needs_parens {
let value_doc = d.concat(&[
d.text("("),
self.build_object_property_value_doc(prop.value, None),
d.text(")"),
]);
d.concat(&[key_doc, d.text(": "), value_doc])
} else {
let is_short_key = self.is_short_property_key(prop.key, prop.computed);
// A comment-free object provably holds no directive either.
self.build_assignment_layout(
key_doc,
d.text(":"),
prop.value,
AssignmentLeft::short_key(is_short_key),
RhsCommentInfo::frozen_only(None),
)
};
}
// Find colon position and check for comments
// Use key_region_end (after `]` for computed, after key for normal)
// to avoid double-counting comments already inside brackets
let colon_pos = self.find_colon_after(key_region_end);
let value_start = prop.value.span().start;
// A line comment — or a multiline block the author broke after — between
// the key and `:` keeps the comment after the key and drops `: value` to
// a continuation line indented one level (prettier relocates it —
// conformance_prettier_ts_comments.md §Comment relocation), bypassing the assignment
// layout below; a glued block stays inline via the ordinary path.
if self.comments_force_own_line_between(key_region_end, colon_pos) {
let value_doc = {
let v = self.build_property_value_doc_as(prop.value, None, target);
let v = if !target
&& self.needs_parens(prop.value, super::ParenContext::ObjectPropertyValue)
{
d.parens(v)
} else {
v
};
self.prepend_rhs_comments(v, colon_pos + 1, value_start)
};
let tail = d.concat(&[d.text(": "), value_doc]);
return d.concat(&[
key_doc,
self.build_continuation_indent(key_region_end, colon_pos, tail),
]);
}
// Comments between key region and colon (e.g., {key /* comment */: value})
let pre_colon_comments: CommentVec<'_> = self
.comments_to_emit_between(key_region_end, colon_pos)
.collect();
// Comments between colon and value (e.g., {key: /* comment */ value})
let post_colon_comments: CommentVec<'_> = self
.comments_to_emit_between(colon_pos + 1, value_start)
.collect();
// Check if value needs parens (e.g., assignment expressions)
let needs_parens =
!target && self.needs_parens(prop.value, super::ParenContext::ObjectPropertyValue);
// A post-colon comment forces break-after-operator when it's a line
// comment (extends to end of line), an *indentable* block (its reprint is
// hard lines, which break the group), or the author broke after it (a
// newline toward the next comment, or the value for the last — an own-line
// leading comment); a block whose glue chain reaches the value stays
// inline — single-line (`: /* c */ v`), preserved multi-line
// (`: /* line1⏎line2 */ v`), and a glued run with a multiline member
// (`: /* c */ /* line1⏎line2 */ v`) alike, since none carries a break out.
// Keying the newline test on `value_start` instead of the next comment
// called a run's head own-line whenever a later member spanned lines.
// Prettier ref: hasLeadingOwnLineComment → break-after-operator in chooseLayout
//
// **on page**, not `post_colon_comments` (which is emit-keyed): hanging the
// value is a LAYOUT decision, so an owned annotation hangs it exactly as any
// other own-line comment does — even though this gap emits nothing for it (the
// value's own node prints it, and the `comments_doc` below is empty).
//
// Two rules, not one fused per-comment test, because only one of them is this
// family's: the indentable half is prettier's `chooseLayout` fourth disjunct
// ([`Printer::indentable_block_leads_value`], shared with the declarator and
// `build_assignment_layout`, and handed to the layout below), the own-line half
// is `hasLeadingOwnLineComment`, which every operator→value gap asks
// ([`Printer::comment_hangs_value_after_operator`]). The class field's paren arm
// asks the same pair.
let indentable_leads_value =
self.indentable_block_leads_value(colon_pos + 1, value_start);
let has_own_line_comment_post_colon = indentable_leads_value
|| self.comment_hangs_value_after_operator(colon_pos + 1, value_start);
// The `:`→value head: an own-line directive there freezes the whole value.
let value_frozen = self.property_value_frozen_span(prop, key_region_end);
if pre_colon_comments.is_empty()
&& post_colon_comments.is_empty()
&& !has_own_line_comment_post_colon
{
if target {
let value_doc = self.build_property_value_doc_as(prop.value, None, true);
d.concat(&[key_doc, d.text(": "), value_doc])
} else if needs_parens {
// Build manually with parens
let value_doc = d.concat(&[
d.text("("),
self.build_object_property_value_doc(prop.value, None),
d.text(")"),
]);
d.concat(&[key_doc, d.text(": "), value_doc])
} else {
// No parens needed: use unified assignment layout
let is_short_key = self.is_short_property_key(prop.key, prop.computed);
self.build_assignment_layout(
key_doc,
d.text(":"),
prop.value,
AssignmentLeft::short_key(is_short_key),
RhsCommentInfo {
comments: None,
has_line_comment: false,
glued_through: false,
// ⚠️ NOT `frozen_only`, whose `gap: None` claims the gap is
// provably empty. The two emptiness tests above are **emit**-keyed
// and this branch is exactly where a comment the value OWNS lands
// — invisible to both (`docs/comments.md` hazard 2) — so the HOIST
// still has work here even though nothing is emitted:
// `: /* c⏎d */ t + u + v` broke the binary chain until this gap
// was handed over. `indentable_leads_value` is `false` by
// construction (it is the first disjunct of the gate this arm
// declined), so it is written, not re-asked.
gap: Some(ValueGap {
start: colon_pos + 1,
indentable_leads_value: false,
}),
boundary: None,
frozen: value_frozen,
},
)
}
} else {
if has_own_line_comment_post_colon {
// Line comment or multiline block comment after colon: BreakAfterOperator
// Structure: group([group(key + pre_colon), ":", group(indent([line, rhs]))])
let mut lhs_parts: DocBuf = smallvec![key_doc];
for comment in &pre_colon_comments {
lhs_parts.push(d.text(" "));
lhs_parts.push(self.build_comment_doc(comment));
}
// `concat` short-circuits the no-pre-colon-comment case to `key_doc`.
let lhs_doc = d.concat(&lhs_parts);
// Build RHS: comments (with proper separators) + value
//
// This arm hangs the value itself instead of routing through
// `build_assignment_layout`, so it owes that builder's value-gap mark:
// a `:`→value gap is a value gap whichever arm prints it, and a JSDoc
// cast here reflows its comment→`(` break like any other value's.
// Without the mark the cast took the width-decided soft `line` and this
// arm's own hang then split the comment from its `(`.
// …and the assignment-value mark for the same reason: a `:`→value
// gap is an `isObjectProperty` value gap whichever arm prints it, so
// the chain here is FLAT like its sibling arms', not indented.
self.mark_jsdoc_cast_value_gap(prop.value);
// A MULTI-LINE block's run is hoisted OUT of the value's doc when the
// value OWNS it, so the comment's hard break cannot reach the value's
// own group ([`Printer::hoist_owned_value_gap_run`]). This arm builds
// its own hang, so it takes the run-only form and owes the paired
// suppression below — exactly the debt that function's ⚠️ names.
let hoisted_run = self.hoisted_owned_value_gap_run_opt(
colon_pos + 1,
prop.value,
needs_parens,
);
// A LINE comment forces the break, and the declarator `=`'s partition
// places it ([`Printer::build_operator_line_comment_hang`]): a comment on
// the `:` line stays there, trailing the `:`, and an own-line one keeps
// its line — both authorings stable. The hang below would push a
// `:`-line `//` down onto a line of its own, a placement the author never
// wrote. The value still takes the outermost claim
// (`build_gap_value_doc`): built bare, a multi-line block it owns
// explodes a conditional (`k: // x⏎/* y⏎*/ a ? b : c`).
if hoisted_run.is_none()
&& self.has_line_comments_between(colon_pos + 1, value_start)
{
let value_doc =
self.build_hung_value_doc(prop.value, colon_pos + 1, || {
self.build_gap_value_doc(None, prop.value, || {
self.build_property_value_doc_as(
prop.value,
value_frozen,
target,
)
})
});
let value_doc = if needs_parens {
d.parens(value_doc)
} else {
value_doc
};
return d.group(d.concat(&[
d.group(lhs_doc),
d.text(":"),
self.build_operator_line_comment_hang(
colon_pos,
value_start,
value_doc,
),
]));
}
let comments_doc = hoisted_run
.or_else(|| self.build_value_gap_comments_opt(colon_pos + 1, value_start))
.unwrap_or_else(|| d.empty());
let mut value_parts: DocBuf = smallvec![comments_doc];
if needs_parens {
value_parts.push(d.text("("));
}
value_parts.push(self.build_hung_value_doc(prop.value, colon_pos + 1, || {
self.build_gap_value_doc(hoisted_run, prop.value, || {
self.build_property_value_doc_as(prop.value, value_frozen, target)
})
}));
if needs_parens {
value_parts.push(d.text(")"));
}
let rhs_doc = d.concat(&value_parts);
// BreakAfterOperator: group([group(left), ":", group(indent([line, rhs]))])
d.group(d.concat(&[
d.group(lhs_doc),
d.text(":"),
hang_after_operator(d, rhs_doc),
]))
} else {
// Inline block comments: use assignment layout so choose_layout
// applies (e.g., ternary with binaryish test → BreakAfterOperator).
// Pre-colon comments become part of the LHS doc.
let lhs_doc = if pre_colon_comments.is_empty() {
key_doc
} else {
let mut lhs_parts: DocBuf = smallvec![key_doc];
for comment in &pre_colon_comments {
lhs_parts.push(d.text(" "));
lhs_parts.push(self.build_comment_doc(comment));
}
d.concat(&lhs_parts)
};
// Post-colon inline comments become rhs_comments
let rhs_comments = if post_colon_comments.is_empty() {
None
} else {
let mut comment_parts: DocBuf = DocBuf::new();
for comment in &post_colon_comments {
comment_parts.push(self.build_comment_doc(comment));
comment_parts.push(d.text(" "));
}
Some(d.concat(&comment_parts))
};
if needs_parens || target {
// Rare: an assignment value in its parens, or a compound target's
// own value, neither of which takes the assignment layout
let mut parts: DocBuf = smallvec![lhs_doc, d.text(": ")];
if let Some(rc) = rhs_comments {
parts.push(rc);
}
if needs_parens {
parts.push(d.text("("));
}
parts.push(self.build_property_value_doc_as(prop.value, None, target));
if needs_parens {
parts.push(d.text(")"));
}
d.concat(&parts)
} else {
let is_short_key = self.is_short_property_key(prop.key, prop.computed);
// `value_frozen` is provably `None` on this arm (an own-line
// directive is an own-line comment, which took the arm above);
// threaded rather than hardcoded so the two can't drift.
self.build_assignment_layout(
lhs_doc,
d.text(":"),
prop.value,
AssignmentLeft::short_key(is_short_key),
RhsCommentInfo {
comments: rhs_comments,
has_line_comment: false,
// This arm is only reached when the gate above found
// no newline after any gap comment, so the run is
// glued through by construction — computed anyway so
// the two can't drift.
glued_through: self
.comment_run_glued_through(colon_pos + 1, value_start),
// Provably `false` on this arm — an indentable block in the
// gap took `has_own_line_comment_post_colon` above, which
// hangs the value itself. Threaded rather than hardcoded, and
// it is literally that gate's own first disjunct, so the two
// cannot drift.
gap: Some(ValueGap {
start: colon_pos + 1,
indentable_leads_value,
}),
boundary: None,
frozen: value_frozen,
},
)
}
}
}
}
}
/// Check if a property key is "short" for layout decisions.
///
/// Short keys don't benefit from breaking after the colon.
/// Complex expressions (calls, binary, etc.) are never short - they can't
/// be reduced to a simple width, matching Prettier's `cleanDoc` behavior.
///
/// Prettier ref: `isObjectPropertyWithShortKey` in `print/assignment.js`
/// Uses `getStringWidth(cleanDoc(keyDoc)) < tabWidth + MIN_OVERLAP_FOR_BREAK`
fn is_short_property_key(&self, key: &Expression<'_>, computed: bool) -> bool {
// Prettier: MIN_OVERLAP_FOR_BREAK = 3 (`isObjectPropertyWithShortKey`, `print/assignment.js`)
let threshold = TAB_WIDTH + super::assignment::MIN_OVERLAP_FOR_BREAK;
let base_width = match &key.kind {
// Prettier: cleanDoc reduces identifier keys to their name string.
//
// ⭐ **A plain-ASCII name is not measured at all.** An identifier holds no
// `\t` and no `\n`, so a plain-ASCII one is one column a byte and its width
// IS `raw_len` — the answer the lexer already recorded
// (`IdentName::plain_ascii`, the same claim `Printer::ident_name_doc`
// spends). Three quarters of every `visual_width` call a TypeScript format
// run makes are this arm (51,042 of 67,654 on a 1,666-file corpus, mean 7.3
// bytes — too short for either of `visual_width`'s vector loops to engage),
// and it asks only whether the width is under `threshold`.
ExpressionKind::Identifier(id) => {
let name = id.ident_name();
if name.escaped.is_none() && name.plain_ascii {
// Graded on every key in every debug build: over-claiming is a silent
// layout error (a key deemed short that is not), under-claiming
// silently retires the lever.
debug_assert_eq!(
name.raw_len as usize,
self.with_ident_name_at(name, id.span.start, |s| visual_width(
s, TAB_WIDTH
)),
"a plain-ASCII key's `raw_len` disagrees with its measured width"
);
name.raw_len as usize
} else {
self.with_ident_name_at(name, id.span.start, |s| visual_width(s, TAB_WIDTH))
}
}
ExpressionKind::Literal(lit) => match &lit.value {
LiteralValue::String(cooked) => {
let content = cooked.resolve(lit.span, self.source);
// For computed keys, quotes are always preserved: ["x"] prints as ['x']
// For non-computed keys, valid identifiers are unquoted: {"x":1} → {x:1}
// Escape-bearing keys keep their quotes (see `string_key_unquotes`).
if computed || !self.string_key_unquotes(lit, content) {
visual_width(content, TAB_WIDTH) + 2 // Include quotes
} else {
visual_width(content, TAB_WIDTH)
}
}
LiteralValue::Number(_) => {
// Use span to get actual source width
(lit.span.end - lit.span.start) as usize
}
// Other literals (bool, null, etc.) - rare as keys, not short
_ => return false,
},
// Complex expressions (calls, binary, member, etc.) are never "short".
// Prettier's cleanDoc can't reduce them to strings, so it returns false.
_ => return false,
};
let total_width = if computed {
base_width + 2 // Add brackets
} else {
base_width
};
total_width < threshold
}
/// A quoted string key may be unquoted only when its *raw* source (escape
/// sequences intact) is already a valid identifier. Keys whose raw form
/// differs from the decoded value carry escapes (`'b'`, `'\a'`,
/// `'\x66\x69\x73\x6b\x65\x72'`) and keep their quotes so the escapes are
/// preserved — matching Prettier, which only unquotes when
/// `rawText.slice(1, -1) === value`. Unquoting from the decoded value would
/// silently rewrite the source text (data loss).
pub(in crate::printer) fn string_key_unquotes(&self, lit: &Literal<'_>, content: &str) -> bool {
if !is_valid_js_identifier(content) {
return false;
}
let raw = lit.span.extract(self.source);
// Strip the surrounding quotes; compare the raw inner text to the
// decoded value. Equal ⇒ no escapes ⇒ safe to unquote.
raw.len() >= 2 && raw[1..raw.len() - 1] == *content
}
/// Emit a string-literal key with prettier's `quoteProps: as-needed`: drop the
/// quotes when the raw text is already a valid identifier (`'type'` → `type`),
/// else keep them and normalize the quote style. Keeping quotes covers
/// non-identifier keys (`'kebab-case'`) and escape-bearing keys (`'b'`) whose
/// escapes must be preserved (see [`Self::string_key_unquotes`]). Shared by
/// object property keys, import-attribute keys and enum member names.
pub(in crate::printer) fn build_string_literal_key_doc(
&self,
lit: &Literal<'_>,
content: &str,
) -> DocId {
let d = self.d();
if self.string_key_unquotes(lit, content) {
// Unquoted: the key is a bare identifier equal to the literal's inner
// source slice (`string_key_unquotes` requires a valid identifier, so
// there are no escapes) — emit that inner span verbatim, no allocation.
let inner = Span::new(lit.span.start + 1, lit.span.end - 1);
debug_assert_eq!(inner.extract(self.source), content);
d.source_span(inner, self.source)
} else {
self.build_string_literal_doc(lit)
}
}
/// Build a Doc for a property key
///
/// String literal keys that are valid identifiers are output without quotes.
/// Example: `{"key": 1}` → `{key: 1}`, but `{"kebab-case": 1}` keeps quotes.
pub(in crate::printer) fn build_property_key_doc(&self, key: &Expression<'_>) -> DocId {
match &key.kind {
ExpressionKind::Literal(
lit @ Literal {
value: LiteralValue::String(cooked),
..
},
) => {
let content = cooked.resolve(lit.span, self.source);
self.build_string_literal_key_doc(lit, content)
}
_ => self.build_expression_doc(key),
}
}
/// Emit a type-member key (`PropertySignature`/`MethodSignature`), returning
/// `(doc, key_region_end)` where `key_region_end` is the source offset just
/// past the key — after the `]` for computed keys — used to anchor the search
/// for following comments/modifiers.
///
/// Drops quotes from an identifier-valid string-literal key for property
/// signatures (`'plain': T` → `plain: T`) and method signatures (`'foo'(): void`
/// → `foo(): void`, as prettier does). A method signature keyed by the value `new`
/// never reaches here: `Printer::build_method_signature_member_doc` keeps its quotes,
/// since a bare `new` there would read as a construct signature. Computed keys are
/// always emitted verbatim inside their brackets.
pub(in crate::printer) fn build_type_member_key_doc(
&self,
search_start: u32,
key: &Expression<'_>,
computed: bool,
) -> (DocId, u32) {
if computed {
// Deliberately NOT `build_computed_key_expr_doc`: a TYPE member's computed key
// takes no clarity parens — prettier emits `{ [a = 0]: A }` bare where the value
// spellings print `{ [(a = 0)]: 1 }` (pinned by `types/computed_key_grammar`).
// Hence the `None` shell below: the frozen arm must reproduce what THIS position's
// ordinary builder emits, not what its neighbours do.
self.build_computed_key_bracket_doc(search_start, key, None, || {
self.build_expression_doc(key)
})
} else {
(self.build_property_key_doc(key), key.span().end)
}
}
/// Find the position of `:` after a position (for finding colon in property)
/// Skips over comments to avoid matching colons inside them.
pub(in crate::printer) fn find_colon_after(&self, start: u32) -> u32 {
find_char_skipping_comments(
self.source.as_bytes(),
start as usize,
self.source.len(),
b':',
)
.map_or(start, |pos| pos as u32)
}
/// Parenthesize a computed `[expr]` key when the expression needs it for
/// clarity — an assignment (`[(x = 0)]`) or, inside a for-header init, an `in`
/// binary (`for (…[(a in b)]…)`, via `needs_parens`' ambient for-init rule).
/// Shared by object and class computed property/method keys. (The computed
/// member-*access* index applies the same rule inline in the chain printer,
/// which threads `in_for_init` explicitly.)
pub(in crate::printer) fn build_computed_key_expr_doc(&self, key: &Expression<'_>) -> DocId {
// The `[`→key gap cannot hang a leading cast's break — no operator line to end —
// so the cast reflows onto the `[`'s line (`Printer::with_jsdoc_cast_cannot_hang_gap`).
self.with_jsdoc_cast_cannot_hang_gap(key, || {
let doc = self.build_expression_doc_claiming_outermost(key);
if self.needs_parens(key, super::ParenContext::ComputedPropertyKey) {
self.d().parens(doc)
} else {
doc
}
})
}
/// Build a `[key]` doc with comments preserved inside brackets.
/// Returns `(doc, key_region_end)` where key_region_end is the position after `]`.
/// Used by object properties/methods, class methods/properties, destructuring
/// patterns, and interface/type-literal members (via `build_type_member_key_doc`).
///
/// `[`→key comment placement: a block comment the author GLUED to the key hugs `[`
/// inline (`[/* c */ foo]`) and the bracket stays flat; a **line** comment can't sit
/// inline before the key (a `//` runs to EOL and would swallow it), and a block the
/// author gave its OWN LINE keeps that line — both force the bracket to break,
/// preserved where the author wrote it (on the `[` line via
/// `delimiter_line_comment_prefix`, or on its own line) with the key dropped to
/// an indented continuation. Prettier relocates such a comment (out to the
/// member's leading line, or glued flush to the key) — a divergence
/// (conformance_prettier_ts_comments.md §Comment relocation, "Object/array/block
/// open-delimiter trailing"). A computed key never breaks on WIDTH alone
/// (prettier keeps a long key inline), so a comment is the only thing that opens
/// the brackets.
///
/// `ordinary` builds the key when nothing freezes it, taken lazily so a directive-free
/// document never pays for a doc the freeze would discard. `key_paren_shell` is the
/// clarity-paren context that same builder applies — `None` where it applies none — so
/// the frozen slice re-synthesizes exactly the shell the caller's own position would
/// have emitted. It is a parameter rather than a constant because the five hosts do NOT
/// agree: an object property, class field, class method and destructuring pattern
/// parenthesize an assignment key, and a **type-literal member** does not.
pub(in crate::printer) fn build_computed_key_bracket_doc(
&self,
search_start: u32,
key: &Expression<'_>,
key_paren_shell: Option<super::ParenContext>,
ordinary: impl FnOnce() -> DocId,
) -> (DocId, u32) {
let d = self.d();
let key_start = key.span().start;
let key_end = key.span().end;
let bracket_start = self.find_opening_bracket_after(search_start, key_start);
let bracket_end = self.find_closing_bracket_after(key_end);
// The `[`→key value head ([`Printer::value_head_frozen_span`]): an own-line directive
// in the gap freezes the whole KEY. The brackets are the property's own and stay
// outside the slice, as does any pair the key requires — which is why the frozen arm
// names `ComputedPropertyKey` even where the caller's ordinary doc did not: every
// host here IS a computed key, and the paren rule is the position's, not the
// caller's. `ordinary` is taken lazily so a directive-free document never builds a
// doc the freeze would discard.
//
// Resolved BEFORE the layout choice below, not inside it: the flat arm hugs the run
// onto the key's line, which is the placement the floor calls inert, so a BLOCK
// directive would lose its freeze on the next pass. (A line directive already forces
// the breaking arm through `bracket_line`.)
let frozen = self.value_head_frozen_span(bracket_start + 1, key.span());
let key_doc = match frozen {
Some(frozen) => {
let slice = self.build_frozen_expression_doc(key, frozen);
// `key_paren_shell` is the clarity shell the CALLER's ordinary builder
// supplies, so the frozen and unfrozen forms cannot disagree about it — the
// rule `Printer::build_frozen_value_doc` states, threaded here because this
// one emitter serves five hosts and they do not all answer it alike (a type
// member takes no shell at all).
match key_paren_shell {
Some(ctx) if self.needs_parens(key, ctx) => d.parens(slice),
_ => slice,
}
}
None => ordinary(),
};
let bracket_line = self.has_line_comments_between(bracket_start + 1, key_start);
let after_key_line = self.has_line_comments_between(key_end, bracket_end);
// A comment the author gave its OWN LINE in the `[`→key gap keeps that line, which
// means taking the breaking layout below. Own-line-ness is a SOURCE question about
// the comment's own neighbours (`docs/comments.md`), asked per comment because a run
// may mix glued and own-line members.
//
// Without this the flat arm collapsed such a comment onto the key's line
// (`[⏎/* c */⏎key]` → `[/* c */ key]`), reflowing a break the author wrote — the same
// hand-rolled kind-keyed split the template interpolation carried. The width stance
// is untouched: a computed key still never breaks on WIDTH, and a glued block still
// hugs inline. This is also what makes a BLOCK-spelled honored directive reachable
// here — the floor reads only a directive alone on its line, so the collapse used to
// make the block spelling inert while the `//` spelling froze.
let bracket_own_line = self
.comments_to_emit_between(bracket_start + 1, key_start)
.any(|c| {
self.has_newline_between(bracket_start + 1, c.span.start)
&& self.has_newline_between(c.span.end, key_start)
});
// A resolved freeze reaches the breaking arm and no other, and needs no term of its
// own to do it: an honored directive is alone on its line, which is `bracket_own_line`
// by construction (and, for the `//` spelling, `bracket_line` as well).
debug_assert!(
frozen.is_none() || bracket_own_line,
"a `[`→key freeze must reach the breaking bracket layout"
);
// Flat path (no line comment in either in-bracket gap): block comments hug
// inline (`[/* d */ foo]`, `[foo /* c */]`), the key never breaks on width.
// Byte-identical to the pre-divergence behavior.
if !bracket_line && !after_key_line && !bracket_own_line {
let mut parts: DocBuf = smallvec![d.text("[")];
for comment in self.comments_to_emit_between(bracket_start + 1, key_start) {
parts.push(self.build_comment_doc(comment));
parts.push(d.text(" "));
}
parts.push(key_doc);
for comment in self.comments_to_emit_between(key_end, bracket_end) {
parts.push(d.text(" "));
parts.push(self.build_comment_doc(comment));
}
parts.push(d.text("]"));
return (d.concat(&parts), bracket_end + 1);
}
// Breaking path: a line comment in either in-bracket gap forces the bracket
// to break so the `//` can't swallow the key or `]`, preserving each comment
// in place. `[`→key: a `[`-line comment is pulled onto the `[` line, an
// own-line one stays on its own line (`build_leading_comments_multiline*`,
// the shared open-delimiter leading-comment builder, hugging a same-line
// block to the key). key→`]`: a same-line comment trails the key with a
// space, an own-line comment keeps its own line. Prettier relocates instead
// (conformance_prettier_ts_comments.md §Comment relocation).
// Build the body (key + any key→`]` trailing comments) into a buffer; the shared
// bracket-break helper owns the `[`→key line-comment prefix and the break shell.
let mut body_parts: DocBuf = smallvec![key_doc];
if self.has_comments_to_emit_between(key_end, bracket_end) {
self.push_deferred_run_end(&mut body_parts, key_doc);
}
let mut prev = key_end;
for comment in self.comments_to_emit_between(key_end, bracket_end) {
if self.is_same_line(prev, comment.span.start) {
body_parts.push(d.text(" "));
} else {
body_parts.push(d.hardline());
}
body_parts.push(self.build_comment_doc(comment));
prev = comment.span.end;
}
let bracket = self.build_bracket_line_comment_break(
"[",
bracket_start,
key_start,
after_key_line,
d.concat(&body_parts),
);
(bracket, bracket_end + 1)
}
/// Find the opening `[` bracket between two positions (for computed properties).
/// Returns the first `[` found outside comments in the range [start, end).
pub(in crate::printer) fn find_opening_bracket_after(&self, start: u32, end: u32) -> u32 {
find_char_skipping_comments(self.source.as_bytes(), start as usize, end as usize, b'[')
.map_or(start, |pos| pos as u32)
}
/// Find the closing `]` bracket after a position (for computed properties)
/// Skips over comments to avoid matching brackets inside them.
fn find_closing_bracket_after(&self, pos: u32) -> u32 {
find_char_skipping_comments(
self.source.as_bytes(),
pos as usize,
self.source.len(),
b']',
)
.map_or(pos + 1, |p| p as u32)
}
}