Repository navigation
fix(core): attach comments around empty statements like Prettier (#288, #303) - #309
Merged
Merged
Conversation
#303) An empty statement in a statement list prints as nothing, so a comment attached to it printed with a stray leading space and moved on the next pass. In a switch case the comment was deleted. Like Prettier's canAttachComment, the parser now skips these empty statements: the statement before takes a comment on its line, the statement after takes an own-line comment, and a list of only empty statements leaves its comments to its block or program. A `;` body such as `if (x) ;` keeps its comments. The formatter prints a program's inner comments, so a file that has only comments keeps them (#303), and statement lists drop every empty statement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Comments escape static and module blocks
- Static and module blocks now rehome comments past empty statements like other statement lists, and a comment-only static body is printed from innerComments, so those comments stay inside the block.
Or push these changes by commenting:
@cursor push a662cb8231
Preview (a662cb8231)
diff --git a/packages/prettier-plugin/src/index.js b/packages/prettier-plugin/src/index.js
--- a/packages/prettier-plugin/src/index.js
+++ b/packages/prettier-plugin/src/index.js
@@ -3491,21 +3491,26 @@
case 'StaticBlock': {
const printedIndexes = getPrintedStatementIndexes(node.body ?? []);
- nodeContent =
- printedIndexes.length > 0
- ? group([
- 'static {',
- indent([
- hardline,
- join(
- hardline,
- printedIndexes.map((i) => path.call(print, 'body', i)),
- ),
- ]),
- hardline,
- '}',
- ])
- : 'static {}';
+ if (printedIndexes.length === 0) {
+ // Same as an empty block: a comment-only body lives on `innerComments`.
+ nodeContent =
+ innerComments && innerComments.length > 0
+ ? group(['static {', indent(printElementBodyComments(innerComments)), hardline, '}'])
+ : 'static {}';
+ break;
+ }
+ nodeContent = group([
+ 'static {',
+ indent([
+ hardline,
+ join(
+ hardline,
+ printedIndexes.map((i) => path.call(print, 'body', i)),
+ ),
+ ]),
+ hardline,
+ '}',
+ ]);
break;
}
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
@@ -7758,6 +7758,39 @@
'switch (x) {\n case 1:\n a; ; // c\n b;\n}',
'switch (x) {\n case 1:\n a; // c\n b;\n}',
],
+ [
+ 'class A {\n static {\n a; ; // c\n }\n b() {}\n}',
+ 'class A {\n static {\n a; // c\n }\n b() {}\n}',
+ ],
+ [
+ 'class A {\n static {\n a; ; // c\n }\n}',
+ 'class A {\n static {\n a; // c\n }\n}',
+ ],
+ [
+ 'class A {\n static {\n a;\n\n // c\n }\n}',
+ 'class A {\n static {\n a;\n\n // c\n }\n}',
+ ],
+ [
+ 'class A {\n static {\n ; // c\n }\n b() {}\n}',
+ 'class A {\n static {\n // c\n }\n b() {}\n}',
+ ],
+ ['class A {\n static {\n // c\n }\n}', 'class A {\n static {\n // c\n }\n}'],
+ [
+ 'class A {\n static {\n ; // c\n } // d\n b() {}\n}',
+ 'class A {\n static {\n // c\n } // d\n b() {}\n}',
+ ],
+ ['namespace N {\n a; ; // c\n}\nb;', 'namespace N {\n a; // c\n}\nb;'],
+ ['namespace N {\n a; ; // c\n}', 'namespace N {\n a; // c\n}'],
+ ['namespace N {\n ; // c\n}\nb;', 'namespace N {\n // c\n}\nb;'],
+ ['namespace N {\n ; // c\n}', 'namespace N {\n // c\n}'],
+ ['namespace N {\n // c\n}', 'namespace N {\n // c\n}'],
+ ['namespace N {\n ; // c\n} // d\nb;', 'namespace N {\n // c\n} // d\nb;'],
+ [
+ 'namespace N {\n export const a = 1; ; // c\n export const b = 2;\n}',
+ 'namespace N {\n export const a = 1; // c\n export const b = 2;\n}',
+ ],
+ ['declare namespace N {\n ; // c\n}', 'declare namespace N {\n // c\n}'],
+ ['module M {\n a; ; // c\n}', 'module M {\n a; // c\n}'],
])('formats %j like Prettier', async (source, expected) => {
expect(await format(source)).toBeWithNewline(expected);
});
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
@@ -650,8 +650,16 @@
return;
}
}
- if (node.type === 'BlockStatement' && hasOnlyEmptyStatements(node.body)) {
- // Collect all comments that fall within this empty block
+ if (
+ (node.type === 'BlockStatement' ||
+ node.type === 'StaticBlock' ||
+ node.type === 'TSModuleBlock') &&
+ hasOnlyEmptyStatements(node.body)
+ ) {
+ // Collect all comments that fall within this empty block. A
+ // `static` block and a module block are statement lists too, so a
+ // comment after their only `;` (or their only comment) belongs
+ // inside them.
while (
comments[0] &&
comments[0].start < /** @type {AST.NodeWithLocation} */ (node).end &&
@@ -660,7 +668,15 @@
const comment = /** @type {AST.CommentWithLocation} */ (comments.shift());
(node.innerComments ||= []).push(comment);
}
- if (node.innerComments && node.innerComments.length > 0) {
+ // A BlockStatement's parent owns a comment after `}`. A static
+ // block or module block is the list entry, so that comment still
+ // attaches below — but only when one remains. Falling through
+ // with nothing left reads `comments[0]`.
+ if (
+ node.innerComments &&
+ node.innerComments.length > 0 &&
+ (node.type === 'BlockStatement' || !comments[0])
+ ) {
return;
}
}
@@ -727,7 +743,9 @@
if (
parent.type === 'BlockStatement' ||
parent.type === 'Program' ||
- parent.type === 'ClassBody'
+ parent.type === 'ClassBody' ||
+ parent.type === 'StaticBlock' ||
+ parent.type === 'TSModuleBlock'
) {
node_array = parent.body;
} else if (parent.type === 'SwitchStatement') {
diff --git a/packages/tsrx/tests/utils/parser.test.js b/packages/tsrx/tests/utils/parser.test.js
--- a/packages/tsrx/tests/utils/parser.test.js
+++ b/packages/tsrx/tests/utils/parser.test.js
@@ -5961,4 +5961,44 @@
expect(values(statement.consequent.trailingComments)).toEqual([' c']);
});
+
+ it('keeps a comment after the last statement inside a static block', () => {
+ const ast = parseModule('class A {\n\tstatic {\n\t\ta; ; // c\n\t}\n\tb() {}\n}', 'App.tsrx');
+ const members = firstStatement(ast, 'ClassDeclaration').body.body;
+ const staticBlock = as_type(members[0], 'StaticBlock');
+ const [statement] = staticBlock.body;
+
+ expect(values(statement.trailingComments)).toEqual([' c']);
+ expect(staticBlock.trailingComments).toBeUndefined();
+ expect(members[1].leadingComments).toBeUndefined();
+ });
+
+ it('keeps the comments of a static block that has only empty statements', () => {
+ const ast = parseModule('class A {\n\tstatic {\n\t\t; // c\n\t} // d\n\tb() {}\n}', 'App.tsrx');
+ const members = firstStatement(ast, 'ClassDeclaration').body.body;
+ const staticBlock = as_type(members[0], 'StaticBlock');
+
+ expect(values(staticBlock.innerComments)).toEqual([' c']);
+ expect(values(staticBlock.trailingComments)).toEqual([' d']);
+ expect(members[1].leadingComments).toBeUndefined();
+ });
+
+ it('keeps a comment after the last statement inside a namespace', () => {
+ const ast = parseModule('namespace N {\n\ta; ; // c\n}\nb;', 'App.tsrx');
+ const block = as_type(firstStatement(ast, 'TSModuleDeclaration').body, 'TSModuleBlock');
+ const [statement, next] = [block.body[0], ast.body[1]];
+
+ expect(values(statement.trailingComments)).toEqual([' c']);
+ expect(next.leadingComments).toBeUndefined();
+ });
+
+ it('keeps the comments of a namespace that has only empty statements', () => {
+ const ast = parseModule('namespace N {\n\t; // c\n} // d\nb;', 'App.tsrx');
+ const declaration = firstStatement(ast, 'TSModuleDeclaration');
+ const block = as_type(declaration.body, 'TSModuleBlock');
+
+ expect(values(block.innerComments)).toEqual([' c']);
+ expect(values(declaration.trailingComments)).toEqual([' d']);
+ expect(ast.body[1].leadingComments).toBeUndefined();
+ });
});You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit dc015d0. Configure here.
Static blocks and namespace bodies are not statement lists for comment attachment yet (#286), so after the last statement a comment left the block once its empty statement stopped taking it. Their empty statements keep their comments again, and statement lists keep an empty statement that has one, which formats them as main does until #302 lands. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ty-statement-comment-288 # Conflicts: # packages/tsrx/tests/utils/parser.test.js
Merged
leonidaz
added a commit
that referenced
this pull request
Sep 24, 2026
…mespaces (#286) #309 left the empty statements of static blocks and namespace bodies owning their comments, because a comment after their last statement used to leave the block. These bodies are statement lists now, so their empty statements take no comments, like a function body's. getPrintedStatementIndexes kept an empty statement that had a comment; the parser leaves none on a list entry, so it drops every empty statement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
leonidaz
added a commit
that referenced
this pull request
Sep 24, 2026
… interfaces, and enums like their siblings (#286, #293) (#302) * fix(core): attach comments in static blocks, namespaces, and code blocks like a function body (#286) The parser's comment attachment only treated BlockStatement, Program, and ClassBody bodies as statement lists. In a StaticBlock, TSModuleBlock, or JSXCodeBlock, a block comment on the next statement's line became a trailing comment of the previous statement, so the formatter separated a JSDoc cast from its parentheses and dropped the cast. A comment after the last statement of a static block or namespace, or in an empty one, moved out of the block. StaticBlock and TSModuleBlock bodies now attach comments as BlockStatement bodies do, including empty-block inner comments. A code block's siblings are its setup statements then its render node, so a block comment on the render node's line leads it. Comments after the last node still go to the code block's innerComments, where printJSXCodeBlock prints them. The formatter prints StaticBlock through the BlockStatement case, so a static block also prints its inner comments and keeps blank lines between statements. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(prettier): keep JSDoc casts in statement lists with semi: false (#286) #290 guards the statement with a leading semicolon before the cast. The next pass must read the cast as the start of that statement in static blocks, namespaces, and code blocks too. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(core): attach comments in interfaces, enums, and type literals like members (#293) The parser's comment attachment treated TSTypeLiteral members as a sibling list, but not TSInterfaceBody bodies or TSEnumDeclaration members. A block comment on the next member's line became a trailing comment of the member before it, so `a: 1; /** @deprecated */ b: 2;` deprecated `a`. A comment after the last member moved after the closing `}`. Both are sibling lists now. An enum's name is kept out of its member list: with no members, it would count as the last one and take the body's comments. A comment in an empty interface, enum, or type literal moved out of the body too. The parser now keeps it as an inner comment, and printEmptyMemberList prints it between the braces. Like Prettier, an enum or type literal keeps a lone block comment on the braces' line when it fits. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(core): skip empty statements for comments in static blocks and namespaces (#286) #309 left the empty statements of static blocks and namespace bodies owning their comments, because a comment after their last statement used to leave the block. These bodies are statement lists now, so their empty statements take no comments, like a function body's. getPrintedStatementIndexes kept an empty statement that had a comment; the parser leaves none on a list entry, so it drops every empty statement. 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.


Fixes #288, #303.
Cause
The parser attached a comment after
;to theEmptyStatement. Statement lists print an empty statement as nothing, so only the comment and its separator were left:a; ; // cprinteda;, then// cwith a stray space, and the next pass removed the space. In a function body the comment was indented one column too far.; // calone printed// c, and the next pass deleted it. In aswitchcase,printSwitchCaseskips empty statements, soa; ; // clost the comment on the first pass.Fix
Prettier never attaches a comment to an
EmptyStatement(itscanAttachCommentleaves them out). The parser now does the same for empty statements in a statement list (get_comment_handlersinpackages/tsrx/src/parse/index.js):;of those before the comment ends the statement, soa; ; // cgives// ctoa;. The next sibling is the next real statement, and a statement followed only by empty statements counts as the last in the list. That way the comments before the block's}stay with it and don't leak out of the block.if (x) ;,do ; while (x)) keeps its comments.printClauseprints that;in place, andif (x); // calready matches Prettier.Printer changes:
Programcase prints its inner comments when it has no statements. Before, a file that had only comments formatted to an empty file ([Bug]: Formatter deletes the comments of a file that has only comments #303).; // calso relies on this now.getPrintedStatementIndexes(fix(prettier): guard statements without semicolons, keep directives and tagged-template type arguments (#263, #266, #268) #290) still keeps an empty statement that has a comment. Only those in static blocks and namespace bodies have one now.Why the parser and not the printer: the parser now attaches these comments the way Prettier does, and one change covers every statement list:
Program, blocks,switchcases, template bodies and code blocks. A printer fix would have to handle each list printer separately. The compiler doesn't emit ordinary comments, so compiled output doesn't change.a; ; // c/b;a;/// c/b;, then// ca; // c/b;function f() { a; ; // c…// c(one column too far)a; // c; // c// c, then an empty file// ccase 1:/a; ; // c/b;// cdeleteda; // cfunction f() {/; // c/}// c// ca; ; /* c *//b;/* c */on its own line, then moveda; /* c */semi: false:; // c/[1].forEach(f)// c, then a blank line before;[1]// c/;[1].forEach(f)// only(a file with only comments)// onlyStatic blocks and namespace bodies format as they do on main, including #288's stray space, until #302 makes them statement lists (see below). Code blocks print
a;then// con its own line, which is stable.Overlap with #302
#302 (#286) changes the same code in
get_comment_handlers, so whichever merges second needs a rebase. The two changes combine:(BlockStatement || StaticBlock || TSModuleBlock) && hasOnlyEmptyStatements(node.body).is_last_in_arrayforJSXCodeBlockchildren with!isCodeBlockChild. Run this PR's look-past loop for everynode_array, so code-block children still getend_nodeandnextSibling(theirnode_arrayincludes the render node), and setis_last_in_arrayonly when!isCodeBlockChild.StaticBlock/TSModuleBlockexception from the empty-statement skip inget_comment_handlers, and the comment exception ingetPrintedStatementIndexes. With both PRs in, static blocks and namespaces formata; ; // casa; // c, and no empty statement keeps a comment. (Bugbot's review found that without fix(core): attach comments in static blocks, namespaces, code blocks, interfaces, and enums like their siblings (#286, #293) #302, those comments left the block.) I checked this resolution on a local merge with fix(core): attach comments in static blocks, namespaces, code blocks, interfaces, and enums like their siblings (#286, #293) #302's headfe729ace: the formatter and parser tests pass (799 and 352), and the static block and namespace cases match Prettier and are stable.Verification
pnpm test: 5632 passed.pnpm typecheck,pnpm changeset:checkand Prettier--checkon the changed files all pass..tsrxfile and the repository's JS/TS sources that parse, 368 files, plus 72 targeted cases, with this branch and with main. No repository file formats differently. No output changes its AST or loses a comment, and every unstable output is also unstable without this change. All 31 of the [Bug]: Formatter prints a comment after an empty statement with a stray space and is not idempotent #288 cases are stable, and thesemi: falsecases match Prettier.Related bugs found and filed
switchcases move to their own line. After a case's last statement the comment moves out to thecaseindent.;becomes a blank line. The;is dropped, but blank lines are counted from line numbers.ifordobody prints before the;, and the next pass moves it again (forif, into the parentheses via [Bug]: A comment that starts an unbraced if or loop body moves into the condition and drops JSDoc casts #296).;in a class body moves to the next member.🤖 Generated with Claude Code
Note
Medium Risk
Touches core parser comment placement used by every format pass; behavior is broad but scoped to empty-statement edge cases with heavy test coverage.
Overview
Aligns comment attachment and printing with Prettier for stray
;in statement lists and comment-only files.The parser no longer hangs comments on
EmptyStatementnodes that sit in a list (Program, blocks,switchcases, etc.). Comments move to the previous or next real statement, or to the block/file asinnerCommentswhen the list is only empty statements. Clause bodies likeif (x) ; // cstill keep comments on the empty statement. Trailing-comment logic skips past consecutive empty siblings so patterns likea; ; // cattach toa.The formatter prints a
Program’sinnerCommentswhen there are no statements, so comment-only sources are preserved instead of becoming an empty file.Parser and formatter tests cover list neighbors,
semi: false, switch cases, and static block/namespace exceptions (#286).Reviewed by Cursor Bugbot for commit 591764f. Bugbot is set up for automated code reviews on this repo. Configure here.