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
// Variable declaration printing for TypeScript
use super::Printer;
use crate::ast::{self, Expression, ExpressionKind};
use crate::printer::expressions::functions::HeadForcedChainLead;
use crate::printer::statements::TerminatorGap;
use crate::printer::{
CommentFilter, CommentSpacing, CommentVec, ContinuationValue, LeadingGlue, ParenContext,
analysis, class_expr_has_decorators, conditional_should_break_after_op, is_curried_arrow_chain,
is_curried_arrow_chain_that_breaks, is_module_path_fluid_call, is_multiline_string_literal,
is_simple_value, is_type_assertion_call, needs_parens, should_break_after_operator,
should_inline_logical_expression,
};
use smallvec::smallvec;
use std::cell::LazyCell;
use tsv_lang::Span;
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::after_operator::{fluid_after_operator, hang_after_operator};
use tsv_lang::doc::arena::{DocArena, DocId};
/// Build the fluid assignment layout: break after `=` only when the full line
/// exceeds print_width. Uses indentIfBreak so the RHS is evaluated independently.
/// Matches Prettier's assignment.js lines 59-67.
///
/// Wrapped in its own group so the marker's fits() evaluation doesn't see
/// trailing elements like ";" that would cause incorrect breaking.
fn build_fluid_assignment_doc(d: &DocArena, id_doc: DocId, init_doc: DocId) -> DocId {
d.group(d.concat(&[id_doc, d.text(" ="), fluid_after_operator(d, init_doc)]))
}
impl Printer<'_> {
/// [`build_fluid_assignment_doc`] for a value-keyed fluid arm, which also owns the
/// one value whose break point is a last resort: a call or `new` whose sole type
/// argument is a nullable reference union breaks after `=` while the line up to the
/// value's first break (a call's `(`) then fits, and otherwise keeps the `=` line and
/// breaks inside its `<…>` — after the `=` too where even the line up to the `<`
/// overflows ([`Printer::after_operator_value_nullable_union_doc`]).
fn build_value_fluid_assignment_doc(
&self,
id_doc: DocId,
init_doc: DocId,
init: &Expression<'_>,
) -> DocId {
let d = self.d();
match self.after_operator_value_nullable_union_doc(init_doc, init) {
Some(tail) => d.group(d.concat(&[id_doc, d.text(" ="), tail])),
None => build_fluid_assignment_doc(d, id_doc, init_doc),
}
}
}
/// One declarator's `=` and what sits around it — the spans
/// [`Printer::build_declarator_init_doc`] bounds its comment reads with, plus the two
/// answers its caller already resolved. Grouped because they are one fact about one gap,
/// and because the layout arms read them in pairs.
pub(in crate::printer) struct DeclaratorEqGap {
/// End of the binding, past a definite `!` — the near edge of the `=` gap.
pub id_end: u32,
/// Position of the `=`.
pub equals_pos: u32,
/// Start of the initializer — the far edge of the `=` gap.
pub init_start: u32,
/// Whether the binding→`=` gap holds a comment to emit. Only BLOCK comments reach
/// here; a line comment there took its caller's continuation path.
pub has_comments_before_eq: bool,
/// Whether the `=`→initializer gap holds a comment to emit.
pub has_comments_after_eq: bool,
/// Whether an INDENTABLE block comment leads the initializer
/// ([`Printer::indentable_block_leads_value`]) — prettier's `chooseLayout` fourth
/// disjunct, which hangs the value under the `=`. **on page**, so a comment the value
/// owns counts: the gap emits nothing for it, but it still decides the layout.
pub indentable_leads_value: bool,
}
/// What [`Printer::build_declarator_init_doc`] needs from the position a declarator sits
/// in. Every field is a fact the caller already has in hand: the binding's printed doc, the
/// spans bounding its `=`, and what the gaps around that `=` hold.
pub(in crate::printer) struct DeclaratorInitInputs<'e, 'a> {
/// The declarator itself — read for its binding (the break-lhs arms rebuild the id doc
/// with a wrapping / non-wrapping type annotation) and its definite `!`.
pub declarator: &'e ast::VariableDeclarator<'a>,
/// Its initializer. Passed rather than read back off `declarator.init`, since the caller
/// has already matched on it to get here.
pub init: &'e Expression<'a>,
/// The printed binding.
pub id_doc: DocId,
/// The `=` and what the gaps on either side of it hold.
pub gap: DeclaratorEqGap,
}
impl<'a> Printer<'a> {
/// The `<id> = <value>` half of ONE variable declarator — prettier's `printAssignment`
/// for a `VariableDeclarator`, stated once for the two positions a declarator occurs
/// in: a declaration statement ([`Printer::build_variable_declaration_doc`]) and a
/// `for` header's init clause (`build_for_init_doc`). Prettier prints both through
/// `printVariableDeclaration` and differs only in the separator BETWEEN declarators
/// (`hardline` in a statement, `line` under a for header), so the layout inside one
/// declarator cannot be allowed to differ either — the header spelling its own flat
/// `" = " + value` is how that position came to have no break-after-operator arm at
/// all, and no over-width initializer written there could be a fixture input.
///
/// The caller supplies the id doc, the comment answers it resolved around its own `=`,
/// and `value` — the position's own value builder, which is the one thing that really
/// does differ (a header declarator's initializer carries the `[~In]` paren shell its
/// clause needs, and each position resolves its own value-head freeze).
///
/// `value` is `&dyn` rather than a generic: the body is long and its two callers would
/// otherwise monomorphize the whole cascade twice for no gain — every layout arm calls
/// it at most once.
///
/// ⚠️ The layout cascade below is a hand-rolled twin of `assignment.rs::choose_layout`
/// — one prettier function answered twice, once for a declarator and once for every
/// other assignment. It interleaves prettier's arms with arms only a declarator has
/// (the multiline string, the type-assertion binding's non-wrapping rebuild, the
/// break-lhs rebuilds), so the two cannot simply be merged — but they DRIFT, and a
/// `chooseLayout` fact added to one belongs in both. A value-SHAPE arm that
/// `chooseLayout` does not have belongs in neither: a shape prettier answers `fluid`
/// by default reaches the default fluid arm here on its own, and a flag for it placed
/// ahead of the hang arm shadows the owned-comment rules (`Hangs` / `Pins`) for exactly
/// that shape.
pub(in crate::printer) fn build_declarator_init_doc(
&self,
inputs: &DeclaratorInitInputs<'_, '_>,
value: &dyn Fn() -> DocId,
) -> DocId {
let d = self.d();
let &DeclaratorInitInputs {
declarator,
init,
id_doc,
gap:
DeclaratorEqGap {
id_end,
equals_pos,
init_start,
has_comments_before_eq,
has_comments_after_eq,
indentable_leads_value,
},
} = inputs;
// `can_break(id_doc)` — prettier's `canBreak(leftDoc)`, which decides the fluid arm.
// Asked at most once and only where an arm reads it (each read below keeps it LAST
// in its conjunction): prettier computes it eagerly, but on a real corpus two fifths
// of declarators never reach a reader, and the walk is the binding's whole doc when
// the binding is a pattern.
let can_break_left = LazyCell::new(|| d.can_break(id_doc));
let mut parts: DocBuf = DocBuf::new();
// Comments after `=` all stay after `=`, matching prettier — a JSDoc
// cast (`= /** @type {T} */ (expr)`) keeps its parens via the
// `CommentBoundPair` node, so its comment lives inside the init expression and
// never reaches this gap.
let rhs_comments_start = equals_pos + 1;
// Helpers for LHS doc handling. Most branches use id_doc as-is;
// some rebuild it (break-lhs wrapping type, fluid non-wrapping type).
// Comments before `=` are always appended after the LHS. (Only block
// comments reach here — a before-`=` *line* comment took the
// continuation `continue` path above.)
// The LHS every arm emits: the binding, plus the before-`=` comments appended to it.
// ONE doc rather than a push-pair, because the fluid arms need it as a single doc
// (it goes inside their group) and no other arm can tell the difference — two
// spellings of one append is how they drift. Only block comments reach here; a
// before-`=` *line* comment took the caller's continuation path.
let lhs_doc_with_comments = |lhs_doc: DocId| -> DocId {
if has_comments_before_eq {
d.concat(&[
lhs_doc,
self.build_inline_comments_between_doc(id_end, equals_pos),
])
} else {
lhs_doc
}
};
// Build optional inline block comment doc between `=` and init.
// These are comments like `const x = /* comment */ expr` that should be
// part of the RHS doc in assignment layout decisions. Line comments are
// handled separately (mandatory break path).
let rhs_block_comment_doc = if has_comments_after_eq {
self.build_comments_between_filtered_opt(
rhs_comments_start,
init_start,
CommentSpacing::Trailing,
CommentFilter::BlockOnly,
)
} else {
None
};
// A declarator `=` is a value gap (`mark_jsdoc_cast_value_gap`). 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);
// A MULTI-LINE block leading the value hoists its run OUT of the value's doc when
// the value OWNS it ([`Printer::hoist_owned_value_gap_run`] carries the why — an
// owned comment travels inside its node's doc, and its reprinted body force-breaks
// every group around it). This is the run-only form, because the cascade below picks
// among many arms rather than handing over one build, so the paired suppression is
// applied to `value` here instead: the two must move together or the comment is
// printed twice / not at all — and "together" binds EVERY arm, not just the ones
// that read `gap_comments` (`prepend_hoisted` below is the multiline-string arm's
// share; every other arm takes the whole of `gap_comments`).
//
// Unguarded, unlike the binding default's twin: when the name→value gap holds no
// comment at all, `equals_pos` is the sentinel `init_start` and this range is
// inverted, which the comment lookups read as empty — the same invariant every
// other gated call site here rides.
// The position's own pair (`const x = (a = b)`) holds the run
// ([`Printer::hoisted_owned_value_gap_run_opt`]); the same verdict
// `build_init_value_doc` wraps by.
let position_parens = self.needs_parens(init, ParenContext::VariableInit);
let hoisted_run =
self.hoisted_owned_value_gap_run_opt(rhs_comments_start, init, position_parens);
// Under the hoist the value's claim is suppressed; where the hoist declines the
// value claims its owned multi-line comment ITSELF, beneath the pair this position
// adds (`build_init_value_doc`) — `build_gap_value_doc` would prepend it outside
// the pair, and a `@type` block outside a `(` is a cast.
//
// A `shouldBreakChain` curried chain's context is set HERE, for every arm below,
// rather than at the arm that names the chain: the `AssignmentRhs` context is what
// makes the arrow printer DECLINE its own chain layout
// (`should_use_arrow_chain_layout`) so this `=` can own the break and the indent,
// and an arm that reached the chain first — a `//` on the `=` line forces its own
// break — would otherwise hand it over with no context and indent the heads a
// second time. Which context is the gap's question
// ([`Printer::head_forced_chain_lead`], shared with `build_assignment_layout`): the
// heads stack under the `=` as with no comment, except below a run the author gave
// lines of its own and behind a preserved multi-line block, where the chain takes
// its default shape.
let chain_breaks = is_curried_arrow_chain_that_breaks(init);
let chain_lead =
chain_breaks.then(|| self.head_forced_chain_lead(init, rhs_comments_start));
let build_value = &|| {
let build = || self.build_value_under_hoist(hoisted_run, init, value);
match chain_lead {
Some(lead) => self.build_with_arrow_chain_context(lead.chain_context(), build),
None => build(),
}
};
// The value under an arm that has ALREADY broken after the `=` and indented — every
// comment arm below ([`Printer::build_hung_value_doc`]). `build_value` rides inside
// it: a chain whose heads force the break sets its own context there, and declines
// the chain layout under either.
let build_hung_value = &|| self.build_hung_value_doc(init, rhs_comments_start, build_value);
let value: &dyn Fn() -> DocId = build_value;
let hung_value: &dyn Fn() -> DocId = build_hung_value;
// Helper: build init doc with optional inline block comments prepended.
// Comments use Trailing spacing (`/* comment */ `) so no extra space needed.
// `or`, never a concat — see [`Printer::hoisted_owned_value_gap_run_opt`].
let gap_comments = hoisted_run.or(rhs_block_comment_doc);
let make_init_doc = |init_doc: DocId| -> DocId {
if let Some(comment_doc) = gap_comments {
d.concat(&[comment_doc, init_doc])
} else {
init_doc
}
};
// ⚠️ The hoisted run alone, for the MULTILINE-STRING arm below, which owns its own
// comment emission and must NOT take the whole of `gap_comments`: it puts an
// emit-axis block on the `=` line, and moving it down onto the value's line is a
// relocation neither prettier nor tsv makes. The hoisted run has no such choice — it
// is the value's OWN comment, glued to the value's first token, so it goes wherever
// the value goes. Omitting it is a DROP (`docs/comments.md` hazard 1): the arm builds
// the value under the hoist's suppression, so nothing else prints it — which is
// exactly what `gaps:audit` caught the moment the licence widened to reach a
// multiline string and a curried head.
//
// ⚠️ **The curried-arrow arm does NOT share that restriction, and reading it as a
// two-arm rule cost a dropped comment.** The restriction is about a value that stays
// on the `=` line: a multiline string opens there, so its gap run and its value share
// a line either way. A curried chain is pushed BELOW the `=` by a hardline, so there
// is no `=` line left for the run to stay on and nothing to relocate — and the bare
// authoring already prints the run on the value's line, from the arrow's own doc,
// because the comment is glued to the head's `(` and the arrow OWNS it. The two only
// part when a redundant paren shell stands between: the comment is then owned by the
// node the strip discards, `hoisted_run` declines, and an arm carrying only
// `prepend_hoisted` printed nothing at all (`const a = /* x */ (({}) => () => test);`
// lost its comment outright). Taking the whole of `gap_comments` there is what makes
// the shell authoring converge on the bare one's fixed point, which is the rule every
// other value kind in this builder already keeps.
let prepend_hoisted = |init_doc: DocId| -> DocId {
match hoisted_run {
Some(run) => d.concat(&[run, init_doc]),
None => init_doc,
}
};
// A block run the author broke AFTER (`const y = /* c */⏎<value>`):
// the shared `=` broke-after arm ([`Printer::broke_after_operator_rhs_doc`]
// — the two-half rule, its declines, and what falls through live there).
if rhs_block_comment_doc.is_some()
&& let Some(rhs_doc) =
self.broke_after_operator_rhs_doc(rhs_comments_start, init_start, hung_value)
{
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" ="));
parts.push(rhs_doc);
return d.concat(&parts);
}
// Check if RHS is a multiline string (line continuations)
let is_multiline_string = is_multiline_string_literal(init, self.source);
// Check if LHS triggers break-lhs layout:
// 1. Complex type annotation - nested generics that should break internally
// 2. Complex destructuring - >2 properties with defaults/non-shorthand
// 3. Arrow function with breakable LHS (long type annotation)
//
// Example type annotation: `const x: Map<string, Array<number>> = getLongValue()`
// Should break as:
// const x: Map<
// string,
// Array<number>
// > = getLongValue();
//
// Example destructuring: `const { a, b = 1, c } = obj`
// Should break as:
// const {
// a,
// b = 1,
// c,
// } = obj;
//
// Example arrow with long type: `const fn: (x: number) => void = (x) => {}`
// When type is long enough to wrap:
// const fn: (
// x: number,
// ) => void = (x) => {};
let has_complex_type_annotation = self.id_has_complex_type_annotation(declarator.id);
let has_complex_destructuring = self.is_complex_destructuring_target(declarator.id);
let is_arrow_with_breakable_left =
matches!(init.kind, ExpressionKind::ArrowFunctionExpression(_)) && *can_break_left;
// Calls and imports with trailing comments expand internally and should not use fluid layout
let is_call_with_trailing_comments =
if let ExpressionKind::CallExpression(call) = &init.kind {
call.arguments.last().is_some_and(|last_arg| {
self.has_line_comments_between(last_arg.span().end, init.span.end)
})
} else {
false
};
// Import expressions with trailing comments also expand internally
// (handles `await import('./x' // comment)`)
let is_import_with_trailing_comments = self.has_import_with_trailing_comments(init);
// Call chains AND member-only chains with line comments should NOT be
// treated as fluid / break-after-operator. The chain formatter breaks
// internally at the comment location, so keep the chain with `=`
// (otherwise it breaks after `=` too → double indent). E.g.
// `const a = items // comment\n .foo()` and `const b = foo.bar // c\n .baz`.
//
// Not where the initializer's printer hoists an own-line run out of its leftmost
// shell (`= (// c⏎x.a() // c⏎)[x]`): the doc then opens with that run, the shape
// the `=`→init gap's own `//` produces, and takes the gap's hang below
// (`left_spine_shell_has_own_line_comment`) — kept with `=` it printed FLUSH under
// the operator and the reparse, reading the comment as the gap's, indented it.
let has_line_comments_in_chain = (self.has_line_comments_in_call_chain(init)
|| self.has_line_comments_in_member_chain(init))
&& !self.left_spine_shell_has_own_line_comment(init);
// Combined flag for expressions with trailing comments that expand internally
let has_trailing_comment_expansion =
is_call_with_trailing_comments || is_import_with_trailing_comments;
// Common exclusion: layout strategies don't apply when the init has trailing
// comment expansion or line comments in a chain — those need special handling.
//
// An object, array, function or class initializer is as eligible as any other
// value: prettier's `chooseLayout` has no notion of a value that "expands on its
// own", so those fall through to `fluid`, whose marker measures only the value's
// OPENING (` {`, ` [`, ` function () {`) and drops the value after the `=` when
// that opening is what passes the print width. That is what keeps a long pattern
// or typed binding flat while the value takes the break
// (`destructuring_fluid_value_long`, `typed_fluid_value_long`), and what gives an
// over-width `= {}` / `= () => {}` its one break point (`empty_value_long`).
// Withholding the layout from them left the binding as the only thing that could
// shed width.
//
// The third exclusion is the shared **retained VALUE shell** rule
// ([`Printer::value_shell_forced_open`], the one statement of it — the
// `build_assignment_layout` twin overrides its `BreakAfterOperator` with the same
// predicate): the author's grouping parens survive because a `//` (or an own-line
// comment) in their trailing gap needs them, and the break they then take is the
// COMMENT's, not a break point in the value. Excluding the value here withholds
// the hang and the fluid marker alike, so the cascade falls through to its last
// arm — `" = "` plus the value — which IS the hug this rule asks for:
// `const v = (⏎\ta?.b! // c⏎);`. The boundary is the declarator's own end, the
// same one both value builders are handed (`build_init_value_doc` at a statement,
// `build_for_init_value_doc` under a `for` header), so a header declarator answers
// identically. Note the gate's existing wording above already claimed this shape —
// "a chain whose own pair RETAINS the run hugging the `=`" — for the narrower
// chain spelling alone; the predicate is what makes it true of every value kind.
let is_layout_eligible = !has_trailing_comment_expansion
&& !has_line_comments_in_chain
&& !self.value_shell_forced_open(init, declarator.span.end);
// RHS expressions that should use break-after-operator layout.
// Matches Prettier's shouldBreakAfterOperator: poorly breakable chains,
// string literals, etc. These don't break well internally, so the
// assignment breaks at `=` with group(indent([line, rightDoc])).
//
// ⚠️ **This chain is a hand-rolled twin of `assignment.rs::choose_layout`** —
// one prettier function answered twice, once for `const x = …` and once for
// every other assignment. It interleaves prettier's arms with the declarator's
// own (see the fn doc), so the two cannot simply be merged — but they DRIFT, and
// the sequence arm is the proof: `choose_layout` has had it from the start while
// this list did not, so `const a = (a, b)` hung its operands off the `=` column.
// A `chooseLayout` fact added to one belongs in both — and a fact added to THIS
// list alone drifts the same way: a call-free chain's member-gap comment is
// `is_poorly_breakable_chain`'s own question (its gate is scoped to a chain that
// holds a CALL, where prettier's `memberChain` label lives), so it takes no
// cancelling term here that `choose_layout` would lack. The string / poorly-
// breakable pair is the twin's own `should_break_after_operator`, which asks it
// of the value UNDER its wrappers (`!!chain`, `await chain`) as prettier does.
let should_break_after_op_rhs = is_module_path_fluid_call(init, self.source)
|| should_break_after_operator(init, self)
// A SEQUENCE init breaks after the `=` and lays its operands out under
// one indent, prettier's own `shouldBreakAfterOperator` switch arm —
// the same fact `choose_layout` states for the assignment-RHS twin.
// Without it the sequence's internal break satisfies the fluid layout's
// fits() and the operands hang off the `=` column instead.
|| matches!(init.kind, ExpressionKind::SequenceExpression(_))
|| matches!(init.kind, ExpressionKind::RegexLiteral(_));
// Decorated class expression → break after operator, each decorator
// on its own line (`const C =\n\t@dec\n\tclass {}`).
let is_decorated_class_expr = matches!(&init.kind, ExpressionKind::ClassExpression(c) if class_expr_has_decorators(c));
// Expressions that need break-after-operator layout:
// group([left, " =", indent([line, right])])
// For binary/logical expressions, breaking happens at operators within the RHS,
// and the entire RHS is indented together after `=`.
//
// Excludes logical expressions with inline-able RHS (non-empty object/array).
// Those use default layout so the RHS self-expands:
// `const x = foo || { a: 1 }` not `const x =\n foo || {a: 1}`
// Prettier ref: `shouldBreakAfterOperator` (`print/assignment.js`) +
// `shouldInlineLogicalExpression` (`print/binaryish.js`)
let is_non_inline_binary = if let ExpressionKind::BinaryExpression(binary) = &init.kind {
!should_inline_logical_expression(binary)
} else {
false
};
let needs_break_after_op_layout =
is_non_inline_binary || conditional_should_break_after_op(init);
// The operator→value hang — prettier's `chooseLayout` fourth disjunct plus the
// own-line JSDoc cast beside it, both in [`Printer::value_hangs_under_operator`],
// stated once so this cascade and its twin cannot answer it differently. This
// declarator builds its own layout rather than routing through
// `build_assignment_layout`, so it applies the rule itself; the twin takes the
// indentable half through `RhsCommentInfo::indentable_leads_value` as this one
// takes it through `DeclaratorEqGap`.
let comment_hangs_value = self.value_hangs_under_operator(indentable_leads_value, init);
// Every value-keyed hang, gated ONCE on layout eligibility: a value whose own line
// comments expand it takes the never-break arm instead.
let is_break_after_op_rhs = is_layout_eligible
&& (should_break_after_op_rhs
|| needs_break_after_op_layout
|| is_decorated_class_expr
// An own-line run inside the grouping parens of the initializer's LEFTMOST
// node (`= (⏎// c⏎a as any) ? b : c`, `= (⏎// c⏎a).b`): the initializer's
// printer hoists it to the head of its doc, so the doc opens with the run
// and a hardline — the shape the `=`→init gap's own line comment produces,
// and it wants the same hang, so the run and the value sit under `=` at the
// value's indent (a binary initializer already lands there through its own
// arm). Left to the fluid / chain arms the run rendered FLUSH on the `=`
// line and the reparse — reading the comment as the gap's — indented it, a
// second fixed point one pass away. The `build_assignment_layout` twin
// states the same term (its left-spine override); the eligibility gate
// above keeps a chain whose own pair RETAINS the run hugging the `=`, as
// there.
|| self.left_spine_shell_has_own_line_comment(init));
// An indentable owned comment hangs the value, and its arm sits AHEAD of every arm
// the binding or the value's own shape would choose — the break-lhs rebuilds, the
// type-assertion and breakable-binding fluid arms, the curried chain's fluid arm.
// Prettier hangs such a comment under a short key, a never-break value, a complex
// pattern and a curried chain alike, and the twin (`build_assignment_layout`)
// overrides `BreakLhs` and `Fluid` for it; an arm placed after any of those
// shadows the rule for exactly that shape (`chain_value_glued_multiline_block_comment`,
// `binding_layout_glued_multiline_block_comment`). A *preserved* multi-line owned
// comment takes no arm: the fluid layout below places it by width, its first line
// charged to the `=` line (`preserved_multiline_block_comment_long`).
// Breakable LHS (a destructuring pattern, a typed binding whose type arguments can
// break): use fluid layout so the printer breaks at `=` before expanding the
// binding. Matches Prettier's `canBreak(leftDoc) → "fluid"`.
// E.g., `const {a, b, c} = resolve(x, y, z)` breaks after `=`, not inside `{}`,
// and so does `const {a, b, c} = { … }` once `= {` no longer fits.
//
// Excludes break-after-operator RHS (binary, conditional, strings, chains) —
// those go through needs_break_after_operator with their own layout.
// In Prettier, shouldBreakAfterOperator() handles those before the canBreak fallback.
let needs_fluid_for_breakable_lhs =
is_layout_eligible && !is_break_after_op_rhs && *can_break_left;
// Type assertion calls with LHS type annotation need special fluid handling
// (handled separately below because they need non-wrapping LHS type)
let is_type_assertion_with_lhs_type = is_type_assertion_call(init, self.source)
&& matches!(&declarator.id.kind, ExpressionKind::Identifier(id) if id.type_annotation().is_some());
// Answered per declarator, exactly as prettier's `printAssignment` is: a
// multi-declarator list does NOT withhold the width-decided break at `=` from its
// declarators. It used to, because the list carried its continuation indent as
// literal text and a hang inside a declarator therefore landed at the statement's
// column — the list is a doc-tree `indent` now
// (`build_variable_declaration_doc`), so the hang sits one level past the
// declarator, where prettier puts it (`multiple/init_long`). The leading-comment
// hang has its own arm above this one (`comment_hangs_value`).
let needs_break_after_operator = is_break_after_op_rhs && !d.will_break(id_doc);
// A curried chain whose heads trigger `arrow_chain_should_break` (`chain_breaks`)
// breaks after `=` unconditionally; every other curried chain goes fluid below.
// ⚠️ This pair is the declarator's hand-rolled twin of `choose_layout`'s
// `Fluid` / `BreakAfterOperator` arms — see the ⚠️ on `build_assignment_layout`.
if has_comments_after_eq
&& let Some(rhs) =
self.build_eq_comment_break_rhs(equals_pos, init_start, " =", hung_value)
{
// A comment after `=` forces a break (line comment → partition;
// own-line / multiline block → break-after-operator hang). Shared
// with the for-loop init clause.
parts.push(lhs_doc_with_comments(id_doc));
parts.push(rhs);
} else if is_multiline_string {
// Multiline string with no comment forcing a break: mandatory break
// after `=`. An inline block glued to `=` trails it on that line.
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" ="));
// The emit-axis run trails the `=`; a hoisted one instead leads the value below,
// where the author glued it. Exactly one of the two — the hoisted run is the
// on-page reading of this same gap, so emitting both double-prints.
if hoisted_run.is_none()
&& has_comments_after_eq
&& let Some(inline) =
self.build_inline_comments_between_doc_opt(equals_pos + 1, init_start)
{
parts.push(inline);
}
parts.push(d.indent_hardline(prepend_hoisted(value())));
} else if chain_lead == Some(HeadForcedChainLead::PreservedBlock) {
// A PRESERVED multi-line block leads the chain from the `=` line, and the chain
// takes no break after the `=`: the comment's own lines are the break, so the
// first head rides its closing line and the rest indent under it
// ([`HeadForcedChainLead::PreservedBlock`]; `build_value` lays the chain out
// with no chain context).
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" = "));
parts.push(make_init_doc(value()));
} else if chain_breaks {
// Mandatory break after `=`; the arrow printer stacks the heads under it.
// The chain is built under the `AssignmentRhs` context (`build_value` above), so
// the arrow printer declines its own chain layout and this `=` owns the break.
//
// `make_init_doc`, not `prepend_hoisted`: the hardline has already moved the
// value off the `=` line, so the gap's whole run travels with it (see the ⚠️ on
// `prepend_hoisted`). A shell-stripped value owns no run for the hoist to find,
// and the emit-axis half is then the only thing printing the comment.
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" ="));
parts.push(d.indent_hardline(make_init_doc(value())));
} else if comment_hangs_value {
// The leading comment's hang (see `comment_hangs_value`). The binding prints as
// built — a pattern or a type annotation stays flat while it fits, prettier's
// `group(leftDoc)` — and a curried chain takes the assignment-RHS chain layout,
// as it does under every hang the twin builds.
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" ="));
parts.push(hang_after_operator(d, make_init_doc(hung_value())));
} else if is_curried_arrow_chain(init) {
// Every other curried chain: fluid break after `=`. The chain's
// signature heads break only when they don't fit on the operator
// line; a hugging body otherwise expands in place. The context tells
// the arrow printer to use the assignment-RHS chain layout.
// The gap's run is the chain's to place ([`Printer::build_led_curried_chain_doc`]).
let init_doc = self.build_led_curried_chain_doc(
gap_comments,
(rhs_comments_start, init_start),
value,
);
parts.push(build_fluid_assignment_doc(
d,
lhs_doc_with_comments(id_doc),
init_doc,
));
} else if has_complex_type_annotation
|| has_complex_destructuring
|| is_arrow_with_breakable_left
{
// Break-lhs layout: LHS breaks internally, `=` stays on same line with RHS
//
// For complex type annotations, rebuild with wrapping type.
// Complex destructuring and arrow with breakable left already have correct id_doc.
if has_complex_type_annotation
&& let ExpressionKind::Identifier(ident) = &declarator.id.kind
{
parts.push(lhs_doc_with_comments(self.build_typed_identifier_doc(
ident,
declarator.definite,
true, // wrap_type
)));
} else if has_complex_destructuring {
// Strip the outer group from the destructuring id_doc so it
// participates in the outer group's fit check. Without this,
// the destructuring group evaluates independently via fits()
// and stays flat even when the full line exceeds print_width.
// Prettier's break-lhs does not wrap leftDoc in an extra group.
parts.push(lhs_doc_with_comments(d.unwrap_group(id_doc)));
} else {
parts.push(lhs_doc_with_comments(id_doc));
}
// Add ` = rightDoc` (right side grouped)
parts.push(d.text(" = "));
let init_doc = make_init_doc(value());
parts.push(d.group(init_doc));
} else if is_type_assertion_with_lhs_type || needs_fluid_for_breakable_lhs {
// Fluid layout ahead of the hang arm for the two LEFT-keyed cases: a breakable
// binding (prettier's `canBreak(leftDoc) → "fluid"`), and a type assertion
// call under a typed binding, which rebuilds the LHS with a non-wrapping type
// annotation. Every value-keyed fluid case is the default arm below.
let fluid_id_doc = if is_type_assertion_with_lhs_type
&& let ExpressionKind::Identifier(ident) = &declarator.id.kind
{
self.build_typed_identifier_doc(
ident,
declarator.definite,
false, // non-wrapping
)
} else {
id_doc
};
let init_doc = make_init_doc(value());
parts.push(self.build_value_fluid_assignment_doc(
lhs_doc_with_comments(fluid_id_doc),
init_doc,
init,
));
} else if needs_break_after_operator {
// Break-after-operator layout for binary/conditional expressions:
// Structure: [" =", group(indent([line, init]))]
//
// The init IS inside the group with the line. This allows the binary/conditional
// expression to control its own breaking at operators. The entire RHS is
// indented together after the `=` break.
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" ="));
let init_doc = make_init_doc(value());
// A short call whose sole type argument is a flat mapped type takes the mapped
// type's width break as authored where prettier's second pass does
// (`MappedTypeArgHug`, shared with `build_assignment_layout`). Its gate refuses
// any comment in the value, and the gap's are refused here, so the rebuilt value
// carries nothing `make_init_doc` would add.
let hug =
self.mapped_type_arg_hug(init, || !has_comments_after_eq && gap_comments.is_none());
parts.push(match hug {
Some(hug) => {
self.build_mapped_type_arg_hug_tail(&hug, init_doc, || make_init_doc(value()))
}
None => hang_after_operator(d, init_doc),
});
} else if is_layout_eligible && !is_simple_value(init) {
// Fluid layout (default for layout-eligible values)
//
// Matches prettier's chooseLayout default: when no special layout
// applies, use fluid so the marker can break at `=` only if needed,
// while allowing the RHS to break internally first.
let init_doc = make_init_doc(value());
parts.push(self.build_value_fluid_assignment_doc(
lhs_doc_with_comments(id_doc),
init_doc,
init,
));
} else {
// Prettier's `never-break-after-operator`: a simple value (`is_simple_value`)
// under a binding that cannot break — a breakable one took the fluid arm above
// — plus a value pinned to the `=` by the multi-line comment it owns, and the
// comment-expanding calls and chains `is_layout_eligible` excludes. The value
// rides the operator's line and breaks inside itself or not at all.
parts.push(lhs_doc_with_comments(id_doc));
parts.push(d.text(" = "));
let init_doc = make_init_doc(value());
parts.push(init_doc);
}
d.concat(&parts)
}
/// Build a variable initializer value, wrapping it in parens for the value
/// position when needed (`const x = (a = b)`) — but NOT double-wrapping when
/// `build_expression_doc_with_paren_comments` already added its own pair around a
/// trailing comment (`const y = (a = b // c)` stays single, not `((a = b // c))`).
/// The single paren then matches the assignment-RHS rendering.
///
/// `position_parens` is asked ONCE here and answers two questions that must agree — the
/// wrap below, and whether the shell builder holds the comment inside the pair
/// ([`Printer::shell_value_keeps_own_parens`]). Asking it separately on each side is
/// how the pair gets doubled or dropped. (The value-gap hoist asks the same pure
/// question of the same inputs ahead of this call, to decline at the pair it wraps —
/// one verdict, read twice, not two verdicts.)
///
/// The paren decision carries the for-header rule via `self.in_for_init`: a
/// statement-level `const x = b in c` lexically under a for-header init (e.g. in a
/// nested function body) parenthesizes the `in` like every other position there —
/// this path's shell builder is the `StatementTerminator` tail, whose `wrap_in` is a
/// no-op, so the caller is the only one who can supply that pair.
///
/// ⚠️ A for-header's *own* declarator is built in `build_for_init_doc` and passes
/// `false` for the same argument, deliberately: its `ForClauseSeparator` tail DOES
/// apply `wrap_in`, so reading the flag there would spell one wrap twice. The
/// asymmetry is the point — don't "fix" it into agreement.
///
/// `frozen` is the value-head freeze this position resolved (`=`→initializer, per
/// [`Printer::value_head_frozen_span`]): the whole initializer prints verbatim, with
/// the same clarity parens the ordinary path would supply — the position's own
/// [`ParenContext`], so the two forms cannot disagree about the shell. Every layout
/// branch below routes its value through here, so the freeze is stated once.
fn build_init_value_doc(
&self,
init: &Expression<'_>,
boundary_end: u32,
frozen: Option<Span>,
) -> DocId {
// Declarator init — an `ancestorNameMap` value position. A frozen value takes the
// same shell (its slice replaces the expression doc, nothing else); only the
// ternary mark is unfrozen-only, since a verbatim slice takes no layout from it.
if frozen.is_none() {
self.mark_ternary_extra_indent(init);
}
// A declarator initializer is the second position prettier's call-object clause
// names ([`Printer::mark_member_call_tail_operand`]). ⚠️ A for-header's own
// declarator does NOT reach here — it is built in `build_for_init_doc` and marks
// itself; `VariableDeclarator` is `VariableDeclarator` to prettier either way, so
// unlike the `[~In]` asymmetry above, the two DO have to agree here.
self.mark_member_call_tail_operand(init);
// And an assignment's value (`mark_assignment_value`) — the for-header declarator
// marks this one itself too, for the same reason.
self.mark_assignment_value(init);
let position_parens =
needs_parens(init, ParenContext::VariableInit, self.in_for_init.get());
// A multi-line comment the value OWNS is claimed HERE, beneath the position's pair,
// so it prints outside the operand's own group but inside the `(`…`)` the author
// wrote it in (`const x = (/* c⏎d */ a = b)`); claimed by the gap seam above the
// wrap, it would land in front of the pair. The claim declines on its own under a
// hoist, and for a sequence, which claims inside its own envelope.
// A pair the position adds holds the value's trailing region, so no shell below it
// hands that region to the declaration's terminator ([`Printer::without_statement_tail`]).
let build = || match frozen {
Some(frozen) => {
self.build_frozen_value_shell_doc(init, frozen, boundary_end, position_parens)
}
None => {
self.build_expression_doc_with_paren_comments(init, boundary_end, position_parens)
}
};
let inner = self.build_value_with_outermost_owned_comment(init, || {
if position_parens {
self.without_statement_tail(build)
} else {
build()
}
});
self.wrap_value_position_parens(init, boundary_end, position_parens, inner)
}
/// The start of the type-argument list prettier's `isArrowFunctionVariable` opts out of
/// the inline and nullable-union layouts (`print/type-parameters.js`): the `<…>` of the
/// type an identifier binding is annotated with, when the initializer is an arrow
/// function — unless its sole argument is an object type (`isObjectType`), which hugs
/// as anywhere. That list takes the ordinary group, so its `<…>` can break ahead of the
/// `=` (`const a: Foo<⏎\tB | null⏎> = () => …`).
fn arrow_variable_type_args_start(
&self,
declarator: &ast::VariableDeclarator<'_>,
) -> Option<u32> {
if !matches!(
declarator.init.map(|init| &init.kind),
Some(ExpressionKind::ArrowFunctionExpression(_))
) {
return None;
}
let ExpressionKind::Identifier(ident) = &declarator.id.kind else {
return None;
};
let args = match self.unwrap_redundant_parens(ident.type_annotation()?.type_annotation) {
ast::TSType::TypeReference(reference) => reference.type_arguments.as_ref(),
ast::TSType::TypeQuery(query) => query.type_arguments.as_ref(),
ast::TSType::Import(import) => import.type_arguments.as_ref(),
_ => None,
}?;
let sole_object_type = matches!(
args.params,
[param] if matches!(
self.unwrap_redundant_parens(param),
ast::TSType::TypeLiteral(_) | ast::TSType::Mapped(_)
)
);
(!sole_object_type).then_some(args.span.start)
}
/// Build a doc for a variable binding pattern with optional definite assignment assertion.
///
/// For identifiers with `definite: true`, builds doc for `name!: type` instead of `name: type`.
/// Uses wrapping type annotations so TypeReference type arguments break internally when needed.
fn build_variable_binding_doc(&self, id: &Expression<'_>, definite: bool) -> DocId {
if definite {
if let ExpressionKind::Identifier(ident) = &id.kind {
self.build_typed_identifier_doc(ident, true, true)
} else {
// Destructuring patterns don't support definite assignment
self.build_expression_doc(id)
}
} else if let ExpressionKind::Identifier(ident) = &id.kind {
self.build_identifier_doc_with_wrapping_type(ident)
} else {
self.build_expression_doc(id)
}
}
/// Build doc for an identifier with type annotation, configurable wrapping.
///
/// - `definite`: include `!` after name
/// - `wrap_type`: use wrapping type annotation (breaks internally) vs non-wrapping (stays on one line)
fn build_typed_identifier_doc(
&self,
ident: &ast::Identifier<'_>,
definite: bool,
wrap_type: bool,
) -> DocId {
let d = self.d();
let mut parts = smallvec![self.identifier_name_doc(ident)];
// Compute name_end for comment extraction
let search_end = ident
.type_annotation()
.map_or(ident.span.end, |ta| ta.span.start);
let raw_name_end = analysis::skip_identifier_at(
self.source.as_bytes(),
ident.span.start as usize,
search_end as usize,
) as u32;
let mut after_modifier = raw_name_end;
if definite {
after_modifier = self.push_modifier_marker_doc(&mut parts, after_modifier, b'!');
}
if ident.optional {
after_modifier = self.push_modifier_marker_doc(&mut parts, after_modifier, b'?');
}
if let Some(type_ann) = ident.type_annotation() {
// `: type` annotation, handling a before-`:` comment between the binding
// name (and any `!`/`?`) and `:` — line → indented continuation, block →
// inline before `:`.
parts.push(self.build_binding_type_annotation_doc(after_modifier, type_ann, wrap_type));
}
d.concat(&parts)
}
/// Build a Doc for a variable declaration statement
///
/// Handles declare, definite assignment (!), type annotations, and multiple declarators.
/// Follows prettier's rule: if any declarator has an initializer, break to multiple lines.
///
/// `terminator` is `None` for an embedder that supplies its own — Svelte's
/// `{const …}` / `{let …}` tags, which close with `}` and own both the `;` and the
/// gap before it (`tsv_ts::__private::build_variable_declaration_doc`). It is one argument
/// rather than a `bool` beside a [`TerminatorGap`] because the two were never independent: with
/// no `;` emitted the gap has no claimant here, and pairing them let the gap's comments be
/// dropped outright (`{let a /* c */;}`). [`Self::build_variable_declaration_doc`] for an
/// EMBEDDED declaration — a Svelte `{const …}` / `{let …}` tag, reached through
/// `tsv_ts::__private::build_variable_declaration_doc` rather than from a statement list.
///
/// It exists so the public entry names the answer instead of passing one, which also
/// keeps [`TerminatorGap`] inside the printer: the host closes with `}` and owns both
/// the `;` and the gap before it, so there is no terminator here to hand a policy to.
pub(crate) fn build_embedded_variable_declaration_doc(
&self,
decl: &ast::VariableDeclaration<'_>,
) -> DocId {
self.build_variable_declaration_doc(decl, None)
}
pub(in crate::printer) fn build_variable_declaration_doc(
&self,
decl: &ast::VariableDeclaration<'_>,
terminator: Option<TerminatorGap>,
) -> DocId {
let d = self.d();
let first_decl_start = decl.declarations[0].span.start;
// The header keyword, word by word: an optional `declare` modifier plus the
// kind (`await using` is two words). Every gap *between* those words is a
// position an author can comment in, so the words are located rather than
// measured — measuring skips the interior gaps and drops what's in them.
// The kind's words are a static slice the head emitter takes as is; a `declare`
// prefix is the only reason to assemble one, and the shared head builder owns that.
//
// The keyword→first-declarator gap. A *line* comment here indents the whole
// continuation one level (uniform declaration-header rule); block/no-comment
// cases stay inline. The leading space is supplied by the gap helper below.
let (keyword_doc, keyword_end) = self.build_declaration_head_doc(
decl.declare,
decl.kind.words(),
decl.span.start,
first_decl_start,
);
// Everything after the gap is collected into `parts` (the continuation).
let mut parts = DocBuf::new();
let is_multi_declarator = decl.declarations.len() > 1;
let has_any_init = decl.declarations.iter().any(|d| d.init.is_some());
let should_break = is_multi_declarator && has_any_init;
// Prettier's `printVariableDeclaration` shape: `[kind, " ", indent(first),
// indent([",", <break>, rest…])]`. BOTH wrappers are doc-tree `indent`s, so a
// declarator that breaks INSIDE — a hung binary, a call's arguments, a ternary's
// branches — keeps its continuation one level past the declarator's own line, and
// the first declarator's content sits at the same depth as the others'. A literal
// indent TEXT after each hardline put every declarator on the right column and
// every break inside one at the STATEMENT's column, below the declarator it
// belonged to; only objects and arrays escaped, through a per-printer compensation
// that has since been retired with it.
//
// The one exception: a keyword→first-declarator gap that breaks already wraps the
// whole continuation in the one indent the list wants
// (`build_keyword_to_name_continuation`), so neither wrapper is added there —
// stacked on it, the declarators after the first would sit two levels deep.
//
// The wrapper is not the *list's* alone: prettier's gate on it is
// `printed.length === 1 && !hasComment(node.declarations[0])` → bare, else
// `indent(printed[0])`, so a LONE declarator that carries a comment of its own takes
// it too and hangs its value two levels. "Of its own" is the keyword→declarator gap
// and nothing else — the declarator's span opens at its binding, so a comment written
// before that binding is what prettier attaches to the declarator, while one between
// the name and `=`, one after the `=`, one inside the value and one trailing it all
// belong to a child node. Probed against prettier at each of those five positions;
// only this one moves. The **on page** axis, because the question is a layout one and
// the comment is glued to the binding, hence owned — `const /* c */ a` prints it from
// the declarator's own doc, and an emit-keyed ask would answer `false` for the very
// comment prettier keys on.
let first_declarator_owns_comment = !is_multi_declarator
&& self.has_comments_on_page_between(keyword_end, first_decl_start);
let list_indents = (is_multi_declarator || first_declarator_owns_comment)
&& !self.keyword_gap_breaks(keyword_end, first_decl_start);
// The Rule A gap anchors, in the shared closure form `list_item_frozen` takes. The
// first declarator's gap opens past the keyword, so a directive written between
// `const`/`let`/`var` and it freezes it like any other member; the header emitter
// keeps that directive on its own line ([`Printer::build_header_comment_run`]) —
// flush against the keyword it would be inert and the freeze would be lost on the
// second pass.
let item_span = |j: usize| decl.declarations[j].span;
// Every declarator after the first, each behind its own separator — a hardline
// when the list has an initializer, a soft `line` when it has none — wrapped in
// the list's `indent()` after the loop. `parts` holds the first declarator alone
// until then.
let mut rest_parts = DocBuf::new();
// Declarators
// The LAST declarator's value ends the statement, so a terminator this declaration
// prints may take over its trailing region ([`Printer::with_statement_tail`]).
let tail_end = terminator
.is_some()
.then(|| decl.declarations.last().map(|last| last.span.end))
.flatten();
let outer_tail = self.arm_statement_tail(tail_end);
for (i, declarator) in decl.declarations.iter().enumerate() {
if i > 0 {
let prev_end = decl.declarations[i - 1].span.end;
let curr_start = declarator.span.start;
// Check for comments between declarators
let has_line_comment = self.has_line_comments_between(prev_end, curr_start);
let has_gap_comment = self.has_comments_to_emit_between(prev_end, curr_start);
// The declarator-separating comma. A block comment keeps the author's
// side of it: before → trails the previous init; after → leads the next
// declarator. (Only consulted when `has_gap_comment`.)
let comma_pos = self.comma_between(prev_end, curr_start);
// The whole gap lands in `rest_parts`, wrapped in the list's `indent()`
// below — so every break here takes its continuation indent from the doc
// tree and carries none of its own. The comma goes there too: nothing
// breaks before it, so the enclosing indent is inert on it.
if has_line_comment {
// Line comment(s) between declarators: the comma must go before the
// first line comment, block comments go before the comma — a `//`
// runs to EOL, so a comma after it would be commented out and a soft
// `line` would let it absorb the next declarator.
// e.g. `a = 1 /* c1 */,\n// c2\nb = 2` or `a = 1, // c1\n// c2\nb = 2`.
self.push_inter_item_line_comment_gap(
&mut rest_parts,
prev_end,
comma_pos,
curr_start,
);
} else {
// Block comment(s) before the comma trail the previous declarator
// (`a = 1 /* c */,`); after-comma comments lead the next one.
// Prettier preserves the side.
if has_gap_comment {
self.push_before_comma_blocks(&mut rest_parts, prev_end, comma_pos);
}
rest_parts.push(d.text(","));
if should_break {
// A stranded after-comma block (on the comma's line, but a
// newline before the next declarator) trails the comma —
// preserving the author's placement (prettier relocates it
// before the comma). Emitted before the break below. Only the
// hardline-separated list takes this rule: a width-separated one
// collapses when it fits, where the block hugs the next declarator
// and both formatters agree.
self.push_stranded_after_comma_blocks(
&mut rest_parts,
comma_pos,
curr_start,
);
rest_parts.push(d.hardline());
if has_gap_comment {
// After-comma block comment(s) lead the next declarator. A
// stranded block already trailed the comma above.
let comments: 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(
&mut rest_parts,
comments.iter().copied(),
curr_start,
LeadingGlue::Adjacent,
);
}
} else {
// Soft break for declarations without initializers.
rest_parts.push(d.line());
if has_gap_comment {
self.push_leading_comment_run(
&mut rest_parts,
self.comments_to_emit_between(comma_pos, curr_start),
curr_start,
LeadingGlue::Adjacent,
);
}
}
}
}
// The first declarator is `parts`; every later one is `rest_parts`, behind the
// separator emitted above. Named once, then reused by the freeze arm and the
// value arms.
let target: &mut DocBuf = if i == 0 { &mut parts } else { &mut rest_parts };
// Rule A: an own-line directive in an inter-declarator gap freezes the FOLLOWING
// declarator over its own node span — the annotation, `=`, and initializer all
// ride inside it; the separating `,` is parent-owned and was emitted above.
if self.list_item_frozen(keyword_end, &item_span, i) {
target.push(self.build_frozen_node_doc(declarator.span));
continue;
}
// Build id doc once for reuse and analysis
let arrow_variable_args = self
.arrow_variable_type_args
.replace(self.arrow_variable_type_args_start(declarator));
let id_doc = self.build_variable_binding_doc(declarator.id, declarator.definite);
self.arrow_variable_type_args.set(arrow_variable_args);
// Initializer with comment handling around =
if let Some(init) = &declarator.init {
let mut id_end = declarator.id.span().end;
let init_start = init.span().start;
// With definite assignment but no type annotation (`let a! = x`), the id
// span excludes the `!`; advance past it so comments between the name and
// `!` (already emitted inside the id doc) aren't re-emitted before `=`.
if declarator.definite
&& let ExpressionKind::Identifier(ident) = &declarator.id.kind
&& ident.type_annotation().is_none()
&& let Some(bang_pos) =
self.find_char_outside_comments(id_end, init_start, b'!')
{
id_end = bang_pos + 1;
}
// Zero-comment fast gate: one binary search over the whole name→value
// gap. The overwhelming common case (no comment around `=`) then skips
// locating `=` — a byte-by-byte source scan — and both the before-`=`
// and after-`=` comment probes, falling through to the plain `id = init`
// layout below. Sound because comments are start-sorted + disjoint and
// both gap sub-ranges lie within `[id_end, init_start]`, so an empty
// whole-gap window makes every sub-query provably empty. Canonical
// reference: `build_params_doc_with_comments`.
let gap_has_comments = self.has_comments_on_page_between(id_end, init_start);
let (equals_pos, has_comments_before_eq, has_comments_after_eq) =
if gap_has_comments {
let eq = self.find_equals_position(id_end, init_start);
(
eq,
self.has_comments_to_emit_between(id_end, eq),
self.has_comments_to_emit_between(eq + 1, init_start),
)
} else {
// No gap comment ⇒ the `=` position is never consulted (its only
// uses bound comment ranges, all empty here); the value below is
// a never-read sentinel that keeps the gated call sites' ranges
// trivially empty.
(init_start, false, false)
};
// prettier's `chooseLayout` fourth disjunct
// ([`Printer::indentable_block_leads_value`]), resolved here rather than in
// the layout builder because it rides the same zero-comment fast gate as
// its two siblings: with no comment anywhere in the name→value gap,
// `equals_pos` is a never-read sentinel and the scan would be over a
// degenerate range. **on page**, unlike `has_comments_after_eq` — a JSDoc
// cast's comment is OWNED and so emits nothing here, and it still hangs.
let indentable_leads_value = gap_has_comments
&& self.indentable_block_leads_value(equals_pos + 1, init_start);
// The `=`→initializer value head: an own-line directive there freezes the
// whole initializer. Rides the gap probe above — a directive is a comment,
// so a comment-free gap provably holds none.
let init_frozen = if has_comments_after_eq {
self.value_head_frozen_span(equals_pos + 1, init.span())
} else {
None
};
// A line comment between the binding and `=` keeps the comment in place
// and drops `= value` to a continuation line indented one level (preserve
// — lossless when a second comment also trails the statement; prettier
// relocates it to end-of-statement and merges the two onto one line —
// conformance_prettier_ts_comments.md §Comment relocation). Bypasses the
// assignment-layout selection below; value built lazily so the common
// no-comment path is unaffected. Init declarators always feed `parts`
// (the comma/separator is handled above, the `;` after the loop), so a
// plain push + `continue` is safe.
if has_comments_before_eq
&& let Some(cont) = self.build_initializer_line_continuation(
id_end,
equals_pos,
ContinuationValue::Expression(init),
|| {
// The declarator's own value builder, exactly as every other
// layout branch below spells it: this arm changes where the `=`
// and its value SIT, not what the value is. Building the bare
// expression here instead dropped the position's clarity parens
// (`const a // c⏎= b = c`) and skipped the freeze outright, so a
// `prettier-ignore` in the gap silently normalized its value.
let value_doc =
self.build_init_value_doc(init, declarator.span.end, init_frozen);
self.prepend_rhs_comments(value_doc, equals_pos + 1, init_start)
},
)
{
target.push(id_doc);
target.push(cont);
continue;
}
target.push(self.build_declarator_init_doc(
&DeclaratorInitInputs {
declarator,
init,
id_doc,
gap: DeclaratorEqGap {
id_end,
equals_pos,
init_start,
has_comments_before_eq,
has_comments_after_eq,
indentable_leads_value,
},
},
&|| self.build_init_value_doc(init, declarator.span.end, init_frozen),
));
} else {
// No initializer: push id_doc directly
target.push(id_doc);
}
}
let tail_gap_start = self.disarm_statement_tail(outer_tail);
// The list's two indents — prettier's `indent(first)` and `indent(rest)` — or
// neither under a broken keyword gap (see `list_indents`). A single declarator takes
// no wrapper unless it carries a comment of its own.
let first_doc = d.concat(&parts);
parts.clear();
parts.push(if list_indents {
d.indent(first_doc)
} else {
first_doc
});
if !rest_parts.is_empty() {
let rest_doc = d.concat(&rest_parts);
parts.push(if list_indents {
d.indent(rest_doc)
} else {
rest_doc
});
}
// Comments between the last declarator and the `;`, with the `;` bound to the
// declaration: a same-line block trails *after* it (`const x = 1 /* c */;` →
// `const x = 1; /* c */`, prettier 3.9), a same-line line trails after it via
// `line_suffix` (`const x = 1; // c`), an own-line comment drops to its own line
// after it (`const x = 1;⏎// c`). See `push_semicolon_with_gap_comments`.
//
// `None` emits neither, for a host that closes with a delimiter of its own — the
// three placements above all put the comment where such a host's closer cannot
// follow it (`crate::__private::build_variable_declaration_doc`).
if let Some(gap) = terminator {
let terminator_gap = crate::__private::declaration_terminator_gap(decl);
self.push_statement_semicolon(
&mut parts,
tail_gap_start.unwrap_or(terminator_gap.start),
terminator_gap.end,
gap,
);
}
let continuation = if should_break {
// Multi-declarator with initializers: hardline breaks already inserted
d.concat(&parts)
} else if is_multi_declarator || has_any_init {
// Group for width-based breaking (multi-declarator soft breaks or single with init)
d.group(d.concat(&parts))
} else {
d.concat(&parts)
};
// A line comment in the keyword→declarator gap indents the continuation.
d.concat(&[
keyword_doc,
self.build_keyword_to_name_continuation(keyword_end, first_decl_start, continuation),
])
}
}