Repository navigation
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
Conversation
Contributor
There was a problem hiding this comment.
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.
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.
leonidaz
force-pushed
the
fix/prettier-comments-299
branch
from
September 25, 2026 00:57
24c29f3 to
7c78662
Compare
…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
force-pushed
the
fix/prettier-comments-299
branch
from
September 25, 2026 01:27
7c78662 to
8b558f5
Compare
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
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.
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


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.if (/** @type {Node} */ (node).end > limit) {/** @type {Node} */aboveif ((node).end > limit) {, then the cast is dropped@if (/* note */ props.open) {@/* note */+if (props.open) {, not idempotentif (ready) /** @type {Api} */ (api).insert(value);if (ready /** @type {Api} */) api.insert(value);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} // c+else {} else { // c, then the comment moves into the blockfunction named() {+check(value /* c */);check(value);, comment deletedfunction f /* c */ () {},class C /* c */ {},type T /* c */ = …function f(/* c */) {},(a) /* c */ => {},function f(a) /* c */ {}foo(/* c */);foo /* c */();, thenfoo(); /* c */<div title={/* a */ title}>{/* b */ label}</div>{label}and/* b */as JSX text before</div><div a="1"+// c+>class A {+a = 1; ; // c// cmoves above the next membera = 1; // c/* a */ /* b */ run();/* a */+/* b */ run();a(); /* c */ /* d */+b();/* d */moves to the next line/** … */inside indented code/**const x = 1 /* c */;const x = 1; /* c */switch (x) {+// a+}switch (…)yield (+// c+42+);yield // c+42;, which yieldsundefinedChanges
printIfStatement,printWhileStatement,printDoWhileStatement,printSwitchStatement, andprintJSXSwitchExpressionno longer hoist the test's leading comments above the keyword (suppressLeadingComments+extractAndPrintLeadingComments). The test prints its own comments inside the parentheses, as in Prettier, so casts keep their parentheses and@if/@switchstay idempotent. A comment between the keyword and(moves inside the parentheses, like Prettier.onlySimpleWhitespaceaccepted a)between a node and a comment, so a comment after the)ofif (…),while (…),for (…), orcatch (…)trailed the condition.endsStatementHeadernow spots the last node of a header, and a comment after its)leads the body instead, unless another)follows it, like Prettier'shandleIfStatementCommentsandhandleWhileLikeComments. A switch's discriminant is excluded, since Prettier keepsswitch (a /* c */) {.printClauseports Prettier'sprintClause: a block or anelse iffollows after a space, any other body isindent([line, body]), andindent([hardline, body])when its first comment starts its line or spans lines. Eachif, loop, anddogroups its header with its body, so a body that doesn't fit, or that contains a function body, moves to its own line, andif (a) if (b) c();stays on one line.EmptyStatementnow prints the;itself, so its comments print around it (if (x); /* c */,if (x) /* c */ ;), as in Prettier.printLabeledStatementprintslabel:;itself.else([Bug]: prettier-plugin moves a comment before else after the else keyword and is not idempotent #365, found here; core). LikehandleIfStatementComments, a comment between anifbody andelsetrails an unbraced body when it's a one-line comment on its line, and otherwise dangles on theif(innerComments).printIfStatementprints them beforeelsethe way Prettier's does, keeping a blank line before them.-1 === -1). The last parameter also took every comment up to the end of the function, body included. Now only parameters and arguments are list members, and the last parameter only takes comments before the parameter list's)(getParameterParens). Comments that used to reach the function'scomments, which nothing printed, go where Prettier puts them: in empty parameter parentheses they dangle on the function, before an arrow's=>they stay on the arrow, a line comment before the body's{moves into the body, and a block comment there leads the body. Comments in empty call parentheses dangle on the call. An arrow's lone parameter without parentheses ends the parameter list, so it never takes the body's comments, and like Prettier'scanPrintParamsWithoutParens,arrowParens: "avoid"keeps the parentheses when the parameter or the=>has a comment. The printers print the name of a function, class, enum, enum member, interface, and type alias throughprint, so a comment on it prints, andprintDanglingCommentsInList(Prettier's function of the same name) prints the comments of empty parameter and argument lists.;in a class body ([Bug]: Formatter moves a comment after a stray semicolon in a class body to the next member #307, core). The last;between a member and a comment now ends the member, as an empty statement does in a statement list ([Bug]: Formatter prints a comment after an empty statement with a stray space and is not idempotent #288).printJSXElementprints attributes throughprintand a comment after the tag name, andcollectOpeningTagComments, which pulled opening-tag comments off the first child and dropped the ones after the last attribute, is gone.printLeadingCommentsports Prettier'sprintLeadingComment: a block comment keeps what follows it on its line, and one that only ends its line breaks it withline, so the value can still join it. The leading-comment checks ofreturn,throw,yield, arrays, assignments, and logical operands now share onehasLeadingOwnLineComment(Prettier's: any leading comment that ends its line); the branch'shasOwnLineLeadingCommentand fix(prettier): lay out binary, logical, conditional, sequence and template expressions and member chains like Prettier (#352, #347, #334, #348, #349, #346, #280, #297, #350) #387'shasLeadingCommentEndingLineare gone.printValueAfterLeadingCommentgroups the value soconst x = /* c */+5;joins like Prettier. TheisInlineContextprint argument no longer changes how comments print;printCallArgumentsstill passes it.innerComments, printed inside the braces.;([Bug]: prettier-plugin prints a comment before a statement's semicolon instead of after it #390, found here; core). Prettier ends expression, return, throw, import, export,do…while, and variable statements before their;(__contentEnd), so a comment between the content and the;trails the statement and prints after the;.takeCommentsBeforeFinalSemicolondoes the same. Besides matching Prettier (const x = 1 /* c */;becomesconst x = 1; /* c */), this keepsif (a) return -1 // c+;from breaking the new clause group on the first pass only. A comment before the closing parenthesis around a statement's value that prints without it (return (a /* c */);) moves too, which is the form Prettier reaches on its second pass. A comment inside parentheses the printer keeps, like a broken binary return argument's or the ones in!(a || b /* c */), stays inside.printCommenthelper prints every comment, including the ones fix(prettier): lay out blank lines, switch cases, member lists, empty bodies, and for headers like Prettier (#344, #328, #330, #304, #318, #317, #329, #331, #281, #321) #370, fix(prettier): lay out assignments, arrow functions, and call arguments like Prettier (#340, #332, #316, #337, #335, #336, #325, #326, #298) #383, fix(prettier): lay out binary, logical, conditional, sequence and template expressions and member chains like Prettier (#352, #347, #334, #348, #349, #346, #280, #297, #350) #387, and fix(prettier): break parameter lists, type arguments, patterns, tuples, objects, and import attributes like Prettier (#324, #351, #315, #314, #311, #341, #276) #367 print:printCommentTextand fix(prettier): break parameter lists, type arguments, patterns, tuples, objects, and import attributes like Prettier (#324, #351, #315, #314, #311, #341, #276) #367's copy ofprintDanglingCommentsInListare folded into the shared helpers, and fix(prettier): lay out binary, logical, conditional, sequence and template expressions and member chains like Prettier (#352, #347, #334, #348, #349, #346, #280, #297, #350) #387'sisIndentableBlockCommentis the oneprintCommentuses. Like Prettier'sprintIndentableBlockComment, a block comment whose lines all start with*prints its lines withhardline, so they take the indentation where the comment prints, and a JSDoc line ending in two spaces keeps them. Any other multi-line block comment prints its source as written (replaceEndOfLine), because the parser strips the comment's indentation fromvalue.yieldarguments ([Bug]: Formatter changes yielded values when the argument starts with a line comment #274). Likereturnandthrow,yieldkeeps an argument that starts with a comment ending its line in parentheses.yield*doesn't need them and prints like Prettier.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 printsyield // c+42;, which yieldsundefined. This PR keepsyield (+// c+42+);, as Prettier does forreturn.return (a /* c */);asreturn a /* c */;and moves the comment after the;on the next pass. The formatter printsreturn 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 brokenreturn (+a &&+b /* c */+);keeps the comment inside, and a shortreturn (a && b /* c */);printsreturn a && b /* c */;and moves the comment on the next pass, as Prettier does (maindeletes that comment). The same goes for parentheses inside the value, as inx = y + (a /* c */);andx = () => (a /* c */);.=>: 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.(…)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 onmain). Of the 198 new cases, 150 fail withmain'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). Theformathelper checks that a second pass changes nothing.tsrx-utils,tsrx-react,tsrx-preact,tsrx-solid,tsrx-vue,tsrx-hono,tsrx-analyze,eslint-parser,eslint-plugin,typescript-plugin,language-server, andtsrx-mcp: 4241 pass. Onetsrx-utilsparser 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 --noEmitpasses forpackages/prettier-plugin/tsconfig.typecheck.jsonandpackages/tsrx/tsconfig.json. Prettier checks pass for the changed files and all 69 tracked.tsrxfiles (none reformatted), and so doespnpm changeset:check..ts/.jsfiles innode_modules, withmain's plugin, this branch's, and Prettier (typescriptorbabel). 7997 parse with Prettier. 6762 matched Prettier onmain(f0db679) and 7639 here (877 fixed, none regressed). 13 outputs aren't idempotent here against 53 onmain, 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 onmain; and no JSDoc cast lost its parentheses (1 onmain).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
printCommentTextis folded intoprintComment, and its switch-case and class-body comments use it too.main24df857). Two hunks conflicted.printTSTypeAliasDeclarationnow keeps C'sdeclareand prints the name throughprint. The comments before=>moved into C'sprintArrowFunctionSignature(printCommentsBeforeArrow, for both the parenthesized and the bare-parameter signature). The dangling comments of empty parameter and argument lists merged into C'sprintFunctionParametersandprintCallArgumentswithout conflicts.mainf0db679).printStatementConditionlays out theif,while, anddo…whiletests, now with the test's comments inside it, and the loops call the path-basedprintClause. The line comment in awhiletest, which this PR used to list as a remaining difference, now prints like Prettier (while (+// c+ready+) {), with tests forwhileanddo…while.printFunctionParameters(path, options, print, shouldExpandParameters, shouldPrintTypeParameters)prints an empty list's dangling comments after the type parameters.printMethodValuegoes through it, so this PR's class-method special case is gone. E's empty array and objectinnerCommentssit next to the empty call's in the parser, and E'sprintObject,printArray, and mapped types use the sharedprintDanglingCommentsInListandprintComment.!(…)tests showed that the comment-before-;rule ([Bug]: prettier-plugin prints a comment before a statement's semicolon instead of after it #390) must not cross parentheses the printer keeps; commit 8b558f5 limits it to values that print without them.Review
arrowParenssettings.=>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.