Skip to content

fix(prettier): keep comments where they are written and print them like Prettier (#274, #279, #282, #294, #296, #299, #301, #306, #307, #319, #320, #353, #355, #358, #364, #365, #390) - #391

Merged
leonidaz merged 4 commits into
mainfrom
fix/prettier-comments-299
Sep 25, 2026

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #274
Closes #279
Closes #282
Closes #294
Closes #296
Closes #299
Closes #301
Closes #306
Closes #307
Closes #319
Closes #320
Closes #353
Closes #355
Closes #358
Closes #364
Closes #365
Closes #390

Summary

Comments now stay where they were written and print the way Prettier prints them. Most of the fixes are in the parser's comment attachment (@tsrx/core), the rest in the plugin's comment printing.

Input Before Now
if (/** @type {Node} */ (node).end > limit) { /** @type {Node} */ above if ((node).end > limit) {, then the cast is dropped unchanged
@if (/* note */ props.open) { @/* note */ + if (props.open) {, not idempotent unchanged
if (ready) /** @type {Api} */ (api).insert(value); if (ready /** @type {Api} */) api.insert(value); unchanged
if (a) foo(() => { x(); }); if (a) foo(() => { + x(); + }); if (a) + foo(() => { + … (Prettier's clause layout)
if (a) + // note + b(); if (a) // note + b();, then the comment moves into the condition unchanged
} // c + else { } else { // c, then the comment moves into the block unchanged
function named() { + check(value /* c */); check(value);, comment deleted unchanged
function f /* c */ () {}, class C /* c */ {}, type T /* c */ = … comment deleted kept after the name
function f(/* c */) {}, (a) /* c */ => {}, function f(a) /* c */ {} comment deleted unchanged
foo(/* c */); foo /* c */();, then foo(); /* c */ unchanged
<div title={/* a */ title}>{/* b */ label}</div> {label} and /* b */ as JSX text before </div> unchanged
<div a="1" + // c + > comment deleted unchanged
class A { + a = 1; ; // c // c moves above the next member a = 1; // c
/* a */ /* b */ run(); /* a */ + /* b */ run(); unchanged
a(); /* c */ /* d */ + b(); /* d */ moves to the next line unchanged
a multi-line /** … */ inside indented code continuation lines at column 1 lined up under /**
const x = 1 /* c */; unchanged const x = 1; /* c */
switch (x) { + // a + } the comment moves into switch (…) unchanged
yield ( + // c + 42 + ); yield // c + 42;, which yields undefined unchanged

Changes

Output differences from Prettier that remain

  • yield ([Bug]: Formatter changes yielded values when the argument starts with a line comment #274): Prettier 3.9.6 prints yield // c + 42;, which yields undefined. This PR keeps yield ( + // c + 42 + );, as Prettier does for return.
  • Prettier isn't idempotent: it prints return (a /* c */); as return a /* c */; and moves the comment after the ; on the next pass. The formatter prints return a; /* c */ at once. For a binary or logical argument the parser can't tell whether the parentheses stay, so it does what Prettier does: a broken return ( + a && + b /* c */ + ); keeps the comment inside, and a short return (a && b /* c */); prints return a && b /* c */; and moves the comment on the next pass, as Prettier does (main deletes that comment). The same goes for parentheses inside the value, as in x = y + (a /* c */); and x = () => (a /* c */);.
  • Comments before =>: Prettier 3.9.6 prints two of them ((a) /* b */ /* c */ => a) on separate lines, which puts a line break before =>, and that doesn't parse. They stay on one line here.
  • JSX wrapping: a multi-line JSX value isn't wrapped in ( … ) and a long child's cast parentheses break inside it ([Bug]: prettier-plugin lays out JSX children and multi-line elements differently from Prettier #369). The JSX tests avoid that.

Verification

  • pnpm vitest run --project prettier-plugin: 1277 pass (1079 on main). Of the 198 new cases, 150 fail with main's printer and parser; the other 48 pin layouts that already matched, or inputs that must stay syntax errors. One existing test changed: import a from /* c */ "mod" /* d */; now prints the comment after the ;, as Prettier does ([Bug]: prettier-plugin prints a comment before a statement's semicolon instead of after it #390). The format helper checks that a second pass changes nothing.
  • The core parser changed, so I also ran tsrx-utils, tsrx-react, tsrx-preact, tsrx-solid, tsrx-vue, tsrx-hono, tsrx-analyze, eslint-parser, eslint-plugin, typescript-plugin, language-server, and tsrx-mcp: 4241 pass. One tsrx-utils parser test now expects the comment before an import's ; on the declaration ([Bug]: prettier-plugin prints a comment before a statement's semicolon instead of after it #390).
  • tsgo --noEmit passes for packages/prettier-plugin/tsconfig.typecheck.json and packages/tsrx/tsconfig.json. Prettier checks pass for the changed files and all 69 tracked .tsrx files (none reformatted), and so does pnpm changeset:check.
  • A probe formatted 8000 top-level and function-body statements that contain comments, from .ts/.js files in node_modules, with main's plugin, this branch's, and Prettier (typescript or babel). 7997 parse with Prettier. 6762 matched Prettier on main (f0db679) and 7639 here (877 fixed, none regressed). 13 outputs aren't idempotent here against 53 on main, with none new; the TypeScript AST (ignoring parentheses) changed for 17 on both, the same statements; comments were lost or merged in none here against 4 on main; and no JSDoc cast lost its parentheses (1 on main).

Related findings

Filed and fixed here, because they share the printers or the parser code above: #353, #355, #365, #390. Also fixed here, with the same cause as an issue above, so described there instead of filed: comments in empty call parentheses (#320), a comment after a function's name before its parameters (#319), comments after the last JSX attribute or the tag name (#301), and a leading comment of an empty body (#306).

Filed for later (scope freeze):

Taken from Group B's routing: #358 and #364.

Integration with the other Prettier PRs

Review

  • Cursor Bugbot, "Unparenthesized arrows steal body comments": fixed in c31789e (7c78662 before the rebase), with tests for both arrowParens settings.
  • Cursor Bugbot, "Line comments swallow arrow tokens": a line comment before => can't parse (no line break may come before =>; Babel and Node reject it too), so tests pin it as a syntax error. The check turned up a real problem next to it. Several comments before => were joined with line breaks, as Prettier does, and that output doesn't parse. They now stay on one line (f99e0a6), and the tests parse the output again.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Unparenthesized arrows steal body comments
    • When an arrow has no parameter parentheses, the last parameter's trailing-comment boundary is now the parameter itself instead of the function's end, so comments after => stay in the body and a second pass with arrowParens avoid no longer moves them.

Create PR

Or push these changes by commenting:

@cursor push 918c043cc3
Preview (918c043cc3)
diff --git a/packages/prettier-plugin/src/index.test.js b/packages/prettier-plugin/src/index.test.js
--- a/packages/prettier-plugin/src/index.test.js
+++ b/packages/prettier-plugin/src/index.test.js
@@ -9295,7 +9295,29 @@
 			expect(await format(source)).toBeWithNewline(source);
 		});
 
+		// An unparenthesized arrow has no `)`. The last parameter used to take
+		// every later comment that sits before a `)`, including one in the body,
+		// and print it before `=>`. Dropping the parentheses (`arrowParens:
+		// 'avoid'`) then moved the comment on the next pass.
 		it.each([
+			['const g = a => {\n  foo(x /* c */);\n};', 'const g = (a) => {\n  foo(x /* c */);\n};'],
+			['const g = a => foo(x /* c */);', 'const g = (a) => foo(x /* c */);'],
+			['const g = async a => foo(x /* c */);', 'const g = async (a) => foo(x /* c */);'],
+		])('keeps a body comment of an unparenthesized arrow in %j', async (source, expected) => {
+			expect(await format(source)).toBeWithNewline(expected);
+		});
+
+		it.each([
+			['const g = (a) => {\n  foo(x /* c */);\n};', 'const g = a => {\n  foo(x /* c */);\n};'],
+			['const g = (a) => foo(x /* c */);', 'const g = a => foo(x /* c */);'],
+		])(
+			'keeps a body comment when arrowParens drops the parentheses of %j',
+			async (source, expected) => {
+				expect(await format(source, { arrowParens: 'avoid' })).toBeWithNewline(expected);
+			},
+		);
+
+		it.each([
 			'foo(/* none */);',
 			'new Foo(/* none */);',
 			'foo(\n  // none\n);',

diff --git a/packages/tsrx/src/parse/index.js b/packages/tsrx/src/parse/index.js
--- a/packages/tsrx/src/parse/index.js
+++ b/packages/tsrx/src/parse/index.js
@@ -1175,6 +1175,10 @@
 
 							const slice = source.slice(end_node.end, comments[0].start);
 
+							// A parameter takes comments only up to the parameter list's `)`.
+							// An unparenthesized arrow (`a => …`) has none, so the boundary is
+							// the parameter itself. The function's end would run through the
+							// body, and a later `)` would claim the body's comments.
 							const trailingCommentBoundary =
 								parent &&
 								parent.type === 'ObjectPattern' &&
@@ -1193,7 +1197,7 @@
 										: isParam
 											? (getParameterParens(
 													/** @type {AST.FunctionDeclaration} */ (/** @type {unknown} */ (parent)),
-												)?.close ?? parent.end)
+												)?.close ?? end_node.end)
 											: parent?.end;
 
 							if (is_last_in_array) {

You can send follow-ups to the cloud agent here.

Comment thread packages/tsrx/src/parse/index.js Resolved
@leonidaz
leonidaz force-pushed the fix/prettier-comments-299 branch from 24c29f3 to 7c78662 Compare September 25, 2026 00:57
leonidaz and others added 3 commits September 24, 2026 21:21
…ke Prettier (#274, #279, #282, #294, #296, #299, #301, #306, #307, #319, #320, #353, #355, #358, #364, #365, #390)

Parser comment attachment (@tsrx/core):
- A comment after the `)` of an if, loop, or catch header leads the body.
- A function's name, type parameters, and return type aren't parameters and a
  callee isn't an argument; the last parameter only takes comments before the
  parameter list's `)`. Comments in empty parameter or argument parentheses
  dangle on the function or call, one before `=>` stays on the arrow, and one
  before a function body leads it or moves into it.
- A stray `;` in a class body ends the member before it.
- Elements visit their opening tag before their children, and tags their name
  before their attributes; a comment after the last attribute trails it.
- A comment before `else` trails an unbraced body or dangles on the if.
- A node takes every comment after it on its line.
- A switch with no cases keeps its comments.
- Comments before a statement's `;` trail the statement, as in Prettier.

Printer (@tsrx/prettier-plugin):
- Test comments stay inside the parentheses of if, while, do-while, switch,
  @if, and @switch.
- printClause ports Prettier's clause layout, and empty bodies print their
  `;` with their comments around it.
- Declaration names print through print(), empty parameter and argument lists
  print dangling comments, arrows print comments before `=>`, and comments
  before else print before it.
- JSX attributes and tag names print their comments.
- printLeadingComments ports printLeadingComment, hasOwnLineLeadingComment
  follows hasLeadingOwnLineComment, and one printComment helper prints
  indentable block comments like printIndentableBlockComment.
- yield keeps the parentheses of an argument that starts with a comment
  ending its line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eter

When an arrow's lone parameter has no parentheses, the last parameter's
comment boundary fell back to the arrow's end, so a comment before a `)`
in the body, as in `x => check(value /* c */)`, trailed the parameter and
printed before `=>`. The parameter now ends the list. Like Prettier's
canPrintParamsWithoutParens, arrowParens: "avoid" keeps the parentheses
of a parameter with a comment, or of an arrow with a comment before `=>`,
and those comments print one per line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With #387, a broken binary or logical return argument keeps its
parentheses, so a comment before the closing one stays inside, as in
Prettier. Only a value that prints without its parentheses, like
`return (a /* c */);`, gives the comment to the statement. The same goes
for any other pair, like the one in `x = !(a || b /* c */);`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@leonidaz
leonidaz force-pushed the fix/prettier-comments-299 branch from 7c78662 to 8b558f5 Compare September 25, 2026 01:27

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is ON. A cloud agent has been kicked off to fix the reported issue. You can view the agent here.

Reviewed by Cursor Bugbot for commit 8b558f5. Configure here.

Comment thread packages/prettier-plugin/src/index.js Resolved
No line break may come between an arrow's parameters and `=>`. Joining two
comments there with a hardline, as Prettier 3.9.6 does, printed
`(a) /* b */` + newline + `/* c */ => a`, which doesn't parse. They now stay
on one line. A line comment there can't occur: that source doesn't parse,
as in Babel and Node, and tests pin that, along with the output of the
valid cases parsing again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@leonidaz
leonidaz merged commit b932928 into main Sep 25, 2026
8 checks passed
@leonidaz
leonidaz deleted the fix/prettier-comments-299 branch September 25, 2026 01:41
leonidaz added a commit that referenced this pull request Sep 25, 2026
Brings in #391 (comment attachment and printing).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leonidaz added a commit that referenced this pull request Sep 25, 2026
…e union printer

#391 dropped printLeadingComments' isInlineContext parameter, so the
union printer's fourth argument became semicolonBeforeLast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leonidaz added a commit that referenced this pull request Sep 25, 2026
… and called or accessed await and casts like Prettier (#368, #381, #378, #375, #399) (#411)

* fix(prettier): break union types like Prettier (#368)

Port Prettier's printUnionType: the members join with `line, "| "` in a
group, and a broken union moves to its own indented line unless its
context already indents it (an assignment that breaks after the operator)
or keeps it in place (type arguments, tuples, conditional type branches).
A union inside parentheses breaks inside them, and its leading comments
print inside the indentation (shouldUnionTypePrintOwnComments).

`as` and `satisfies` now print like Prettier's printBinaryCastExpression,
so a cast union moves below the operator by itself; the
preferInlineSimpleUnionType argument is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prettier): break intersection types after & like Prettier (#381)

Port Prettier's printIntersectionType: two types that aren't object types
join with `indent([" &", line, type])` in a group, so a long intersection
breaks after each `&` instead of inside a member's type arguments. An
object type next to another type stays on the `&` line and indents once
the chain has broken before it, and a type after an own-line comment
moves to the next line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prettier): lay out a JSDoc-cast value like a parenthesized one (#378)

Prettier keeps a JSDoc cast's parentheses as a ParenthesizedExpression,
so chooseLayout's checks on the value's type (binaryish, string literal,
poorly breakable chain, arrow function, require call, and the rest) never
match a cast value, and the value doesn't get the assignment layout as a
print argument. chooseAssignmentLayout now does the same for a value in
cast parentheses, so `const x = /** @type {T} */ (a && b)` stays on the
`=` line and breaks inside the parentheses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prettier): break a called or accessed await or cast inside its parentheses (#375, #399)

Port the callee/object branch of Prettier's printAwaitExpression and
printBinaryCastExpression: an `await`, `as`, or `satisfies` expression that
is the callee of a call (or, for a cast, of a `new`) or the object of a
member access prints `group([indent([softline, …]), softline])` inside its
parentheses. An await that starts the argument of an enclosing await
leaves the lines to the enclosing group, so `await (await` stays together.
`yield` keeps hugging its parentheses, as in Prettier.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(prettier): call printLeadingComments with its new signature in the union printer

#391 dropped printLeadingComments' isInlineContext parameter, so the
union printer's fourth argument became semicolonBeforeLast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment