Skip to content

Commit 10b10c5

Browse files
committed
fix(formatter): keep comments around = on their side and line (#27041)
Follow up on #26997, apply our consistent policy.
1 parent 9aad365 commit 10b10c5

9 files changed

Lines changed: 235 additions & 204 deletions

File tree

‎crates/oxc_formatter/AGENTS.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,15 @@ The `as`/`satisfies` operator gap follows the same policy (`as_or_satisfies_expr
145145
so once the expression's source parens are dropped, only same-line single-line block comments stay on the expression side;
146146
everything else normalizes to the type side so the output re-parses
147147
- paragraph-like promotion: a line-ending multiline block goes own-line above the type.
148-
`=`/`:` reach the same outputs through `AssignmentLike` (DIVERGENCES.md#eol-comment-after-assign-colon);
148+
Declarators, assignments and type aliases reach the same outputs at `=` through `AssignmentLike` (DIVERGENCES.md#eol-comment-after-assign-colon);
149+
property keys and class fields keep it on the left;
149150
the head-body `write_*` helpers split on `preceded_by_newline` alone and do not promote
150151
- a union type claims the after-operator comments itself, the same placement as after a type alias's `=` (`union_type.rs`);
151152
the operator side breaks only for a riding line comment before the operator.
152153
A suppressed union never runs that printer, so the cast site and `AssignmentLike` lay it out like any other type
153154
- an assignment-like's `=` / `:` (`AssignmentLike`): the left side's trailing run stops at the operator (comments past it are hidden while it prints);
154155
a glued run ending in a line comment prints right after the operator (`operator_line_run`), a block-ending one leads the right-hand side;
156+
a line-ending single-line block before the operator trails the left side;
155157
with comments the left side deferred still pending, nothing glues (same as the cast site)
156158

157159
Implemented by the `write_*` helpers in `utils/statement_body.rs` and `FormatParenHeadExpression` (`print/mod.rs`);

‎crates/oxc_formatter/DIVERGENCES.md‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -205,15 +205,14 @@ Prettier moves the comment inside for `keyof`/type-operator operands while keepi
205205

206206
- Why: invariant (prettier/prettier#14617)
207207
- Pin: `tests/fixtures/js/comments/assignment-eol-line-comment.js`, `tests/fixtures/ts/comments/operator-eol-line-comment.ts`
208+
- Conformance: `js/comments/array-and-object.js`, `js/comments/assignment/variable-declarator.js`, `js/comments/variable-declarator.js`, `typescript/comments/type-literals.ts`
208209

209-
Prettier's output crosses user content (the value the comment precedes, then the `;`) or changes line (own-lined in TS).
210+
Prettier's output crosses user content (the value the comment precedes, then the `;`) or changes line (own-lined).
210211
An end-of-line line comment right after `=`/`:` keeps its position (`= // c` + mandatory break).
211-
Block comments glued after the operator before it stay there, in order;
212-
Prettier prints the line comment first and the block on the value's line, crossing the block.
213-
A line comment before the operator rides its `line_suffix` past the operator and gets the same break;
214-
Prettier flushes it past the value.
215-
Comments the left side defers (own-line, or a block ending its line) lead the value, the line comment follows them in source order, as Prettier prints type aliases;
216-
for JS values, Prettier flushes the line comment past the value after a block (`const v = /* c */ 1; // d`) and before an own-line one.
212+
Block comments glued after the operator before it stay there, in order; Prettier prints the line comment first and the block on the value's line, crossing the block.
213+
A line comment before the operator rides its `line_suffix` past the operator and gets the same break; Prettier flushes it past the value.
214+
A single-line block comment ending the left side's line trails the left side; Prettier moves it across the operator.
215+
Comments the left side defers (own-line, or a multiline block ending its line) lead the value, the line comment follows them in source order, as Prettier prints type aliases; for JS values, Prettier prints the line comment before them.
217216

218217
```ts
219218
// input
@@ -223,6 +222,10 @@ const v2 = /* c */ // d
223222
1;
224223
const v3 // c
225224
= 1;
225+
const v4 /* c */
226+
= 1;
227+
const v5 = // c
228+
{ a: 1 };
226229
type Alias = // c
227230
"VALUE";
228231

@@ -233,6 +236,9 @@ const v2 = /* c */ // d
233236
1;
234237
const v3 = // c
235238
1;
239+
const v4 /* c */ = 1;
240+
const v5 = // c
241+
{ a: 1 };
236242
type Alias = // c
237243
"VALUE";
238244

@@ -241,14 +247,19 @@ const v1 = 1; // c
241247
const v2 = // d
242248
/* c */ 1;
243249
const v3 = 1; // c
250+
const v4 = /* c */ 1;
251+
const v5 =
252+
// c
253+
{ a: 1 };
244254
type Alias =
245255
// c
246256
"VALUE";
247257
```
248258

249-
Prettier treats the same shape three ways:
259+
Prettier treats the same shape differently:
250260

251-
- JS keeps it only when the right-hand side breaks and flushes it past a fitting one (the prettier/prettier#14617-family attachment artifact)
261+
- JS keeps it only when the right-hand side breaks and flushes it past a fitting one (the prettier/prettier#14617-family attachment artifact),
262+
except an object, array or template value, which gets it own-lined (`handleAssignmentLikeComments`)
252263
- TS type aliases and union-valued property signatures get it own-lined (the 3.9 union rewrite)
253264
- simple-typed property signatures get it flushed past the member and its `;` separator
254265

‎crates/oxc_formatter/src/utils/assignment_like.rs‎

Lines changed: 10 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -138,20 +138,15 @@ pub enum AssignmentLikeLayout {
138138
SuppressedInitializer,
139139
}
140140

141-
/// Based on Prettier's behavior:
142-
/// <https://github.com/prettier/prettier/blob/7584432401a47a26943dd7a9ca9a8e032ead7285/src/language-js/comments/handle-comments.js#L853-L883>
143-
fn format_left_trailing_comments(
144-
start: u32,
145-
should_print_as_leading: bool,
146-
f: &mut JsFormatter<'_, '_>,
147-
) {
141+
/// The left side's trailing comments up to the operator (see DIVERGENCES.md#eol-comment-after-assign-colon).
142+
fn format_left_trailing_comments(start: u32, f: &mut JsFormatter<'_, '_>) {
148143
let end_of_line_comments = f.context().comments().end_of_line_comments_after(start);
149144

150145
let comments = if end_of_line_comments.is_empty() {
151146
let comments = f.context().comments().comments_before_character(start, b'=');
152147
if comments.iter().any(|c| c.preceded_by_newline()) { &[] } else { comments }
153-
} else if should_print_as_leading || end_of_line_comments.last().is_some_and(|c| c.is_block()) {
154-
// No trailing comments for these expressions or if the trailing comment is a block comment
148+
} else if end_of_line_comments.last().is_some_and(|c| c.is_multiline_block()) {
149+
// A line-ending multiline block is promoted own-line above the right-hand side
155150
&[]
156151
} else {
157152
end_of_line_comments
@@ -160,16 +155,6 @@ fn format_left_trailing_comments(
160155
FormatTrailingComments::Comments(comments).fmt(f);
161156
}
162157

163-
fn should_print_as_leading(expr: &Expression) -> bool {
164-
matches!(
165-
expr,
166-
Expression::ObjectExpression(_)
167-
| Expression::ArrayExpression(_)
168-
| Expression::TemplateLiteral(_)
169-
| Expression::TaggedTemplateExpression(_)
170-
)
171-
}
172-
173158
/// The minimum number of overlapping characters between left and right hand side
174159
const MIN_OVERLAP_FOR_BREAK: u8 = 3;
175160

@@ -185,11 +170,7 @@ impl<'a> AssignmentLike<'a, '_> {
185170
declarator.type_annotation()
186171
]
187172
);
188-
format_left_trailing_comments(
189-
declarator.id.span().end,
190-
self.right_hugs_leading_comments(),
191-
f,
192-
);
173+
format_left_trailing_comments(declarator.id.span().end, f);
193174
} else {
194175
write!(
195176
f,
@@ -204,11 +185,7 @@ impl<'a> AssignmentLike<'a, '_> {
204185
}
205186
AssignmentLike::AssignmentExpression(assignment) => {
206187
write!(f, [FormatNodeWithoutTrailingComments(&assignment.left()),]);
207-
format_left_trailing_comments(
208-
assignment.left.span().end,
209-
self.right_hugs_leading_comments(),
210-
f,
211-
);
188+
format_left_trailing_comments(assignment.left.span().end, f);
212189
false
213190
}
214191
AssignmentLike::ObjectProperty(property) => {
@@ -328,7 +305,7 @@ impl<'a> AssignmentLike<'a, '_> {
328305
}
329306
let start = type_alias_left_end(declaration);
330307

331-
format_left_trailing_comments(start, self.right_hugs_leading_comments(), f);
308+
format_left_trailing_comments(start, f);
332309

333310
false
334311
}
@@ -541,39 +518,15 @@ impl<'a> AssignmentLike<'a, '_> {
541518

542519
/// The comments glued after the operator up to a line comment ending its line (`= /* c */ // d`),
543520
/// printed right after the operator (see `Comments::mark_suppressed_after_operator` for their suppression target).
544-
/// A right-hand side that hugs its leading comments (object, array, template) takes them instead.
545521
/// Comments the left side deferred are still pending: nothing glues, all lead the right-hand side in order.
546-
fn operator_line_run(&self, operator_end: u32, f: &JsFormatter<'_, 'a>) -> &'a [Comment] {
547-
if self.right_hugs_leading_comments()
548-
|| f.context().comments().has_comment_before(operator_end)
549-
{
522+
fn operator_line_run(operator_end: u32, f: &JsFormatter<'_, 'a>) -> &'a [Comment] {
523+
if f.context().comments().has_comment_before(operator_end) {
550524
return &[];
551525
}
552526
let run = f.context().comments().end_of_line_comments_after(operator_end);
553527
if run.last().is_some_and(|c| c.is_line()) { run } else { &[] }
554528
}
555529

556-
/// Prettier attaches the comments around the operator to these right-hand sides as leading (`handleAssignmentLikeComments`),
557-
/// so nothing trails the left side or glues to the operator.
558-
fn right_hugs_leading_comments(&self) -> bool {
559-
match self {
560-
Self::VariableDeclarator(declarator) => {
561-
declarator.init.as_ref().is_some_and(should_print_as_leading)
562-
}
563-
Self::AssignmentExpression(assignment) => should_print_as_leading(&assignment.right),
564-
Self::PropertyDefinition(property) => {
565-
property.value.as_ref().is_some_and(should_print_as_leading)
566-
}
567-
Self::AccessorProperty(property) => {
568-
property.value.as_ref().is_some_and(should_print_as_leading)
569-
}
570-
Self::TSTypeAliasDeclaration(decl) => {
571-
matches!(decl.type_annotation, TSType::TSTypeLiteral(_))
572-
}
573-
Self::ObjectProperty(_) | Self::BindingProperty(_) => false,
574-
}
575-
}
576-
577530
/// End of the left-hand side (type annotation included), before the operator and any comments around it.
578531
/// Distinct from the comment-scan start in `write_left`, which begins at the id.
579532
fn left_end(&self) -> u32 {
@@ -944,7 +897,7 @@ impl<'a> Format<'a, JsFormatContext<'a>> for AssignmentLike<'a, '_> {
944897
f.context_mut().comments_mut().restore_view_limit(view_limit);
945898
}
946899
let operator_line_run =
947-
operator_end.map_or(&[][..], |end| self.operator_line_run(end, f));
900+
operator_end.map_or(&[][..], |end| Self::operator_line_run(end, f));
948901
// A line comment on the operator's line, before it (printed by the left side) or after it (the run):
949902
// the pending `line_suffix` must be followed by the break, or it flushes past the right-hand side
950903
let has_line_comment_on_operator_line = !operator_line_run.is_empty()

‎crates/oxc_formatter/tests/fixtures/js/comments/assignment-eol-line-comment.js‎

Lines changed: 40 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,20 @@ class C {
2020
1;
2121
}
2222

23+
// Object, array and template values too (Prettier own-lines it above them)
24+
const h1 = // c
25+
{ a: 1 };
26+
const h2 = // c
27+
[1];
28+
const h3 = // c
29+
`x`;
30+
h4 = // c
31+
{ a: 1 };
32+
const h5 // c
33+
= { a: 1 };
34+
const h6 = // prettier-ignore
35+
{ a: 1 };
36+
2337
// Breaking right-hand side: Prettier keeps the order here too (no divergence)
2438
const v3 = // c
2539
someLongFunctionCall(argumentOne, argumentTwo, argumentThree, argumentFours);
@@ -39,9 +53,31 @@ class C2 {
3953
f = /* c */ // d
4054
1;
4155
}
42-
// Before the operator they trail the left side
56+
// Before the operator they trail the left side, also when ending its line
57+
// (Prettier moves a line-ending one across the operator: `const b6 = /* c */ 1; // d`)
4358
const b3 /* c */ = // d
4459
1;
60+
const b6 /* c */
61+
= // d
62+
1;
63+
b7 /* c */
64+
= // d
65+
1;
66+
const b8 /* c */
67+
= 1;
68+
class C4 {
69+
f /* c */
70+
= // d
71+
1;
72+
}
73+
const o4 = {
74+
p /* c */
75+
: // d
76+
1,
77+
};
78+
const b10 /* c */
79+
= // oxfmt-ignore
80+
[1, 2];
4581
// A line comment before the operator trails the left side and breaks after the operator the same way
4682
// (Prettier flushes it past a fitting value)
4783
const b4 // c
@@ -56,32 +92,13 @@ class C3 {
5692
f // c
5793
= 1;
5894
}
59-
// Comments the left side defers lead the right-hand side, the line comment follows them in source order
60-
// (Prettier flushes the line comment past the value: `const b6 = /* c */ 1; // d`)
61-
const b6 /* c */
62-
= // d
63-
1;
64-
b7 /* c */
65-
= // d
66-
1;
67-
const b8
95+
// Own-line comments the left side defers lead the right-hand side, the line comment follows them in source order
96+
// (Prettier prints the line comment first: `const b9 = // d`)
97+
const b9
6898
// c
6999
= // d
70100
1;
71101
a.b
72102
// c
73103
= // d
74104
1;
75-
const b9 /* c */
76-
= // oxfmt-ignore
77-
[1, 2];
78-
class C4 {
79-
f /* c */
80-
= // d
81-
1;
82-
}
83-
const o4 = {
84-
p /* c */
85-
: // d
86-
1,
87-
};

0 commit comments

Comments
 (0)