Skip to content

fix(core): attach comments around empty statements like Prettier (#288, #303) - #309

Merged
leonidaz merged 3 commits into
mainfrom
fix/prettier-empty-statement-comment-288
Sep 24, 2026
Merged

leonidaz merged 3 commits into
mainfrom
fix/prettier-empty-statement-comment-288

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #288, #303.

Cause

The parser attached a comment after ; to the EmptyStatement. Statement lists print an empty statement as nothing, so only the comment and its separator were left: a; ; // c printed a;, then // c with a stray space, and the next pass removed the space. In a function body the comment was indented one column too far. ; // c alone printed // c, and the next pass deleted it. In a switch case, printSwitchCase skips empty statements, so a; ; // c lost the comment on the first pass.

Fix

Prettier never attaches a comment to an EmptyStatement (its canAttachComment leaves them out). The parser now does the same for empty statements in a statement list (get_comment_handlers in packages/tsrx/src/parse/index.js):

  • The walk skips an empty statement that is an entry in its parent's list, so it takes no leading or trailing comments.
  • The statement before it looks past the empty statements that follow it. The ; of those before the comment ends the statement, so a; ; // c gives // c to a;. 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.
  • A program or block that has only empty statements keeps its comments as inner comments, the same as an empty one.
  • An empty statement that is a clause's body (if (x) ;, do ; while (x)) keeps its comments. printClause prints that ; in place, and if (x); // c already matches Prettier.
  • Empty statements in static blocks and namespace bodies also keep their comments for now. The parser doesn't treat those bodies as statement lists yet ([Bug]: Comments in static blocks, namespaces, and code blocks attach to the previous statement and drop JSDoc casts #286), so a comment after their last statement would leave the block.

Printer changes:

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, switch cases, 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.

Input Before After (matches Prettier)
a; ; // c / b; a; / // c / b;, then // c a; // c / b;
function f() { a; ; // c … // c (one column too far) a; // c
; // c // c, then an empty file // c
case 1: / a; ; // c / b; // c deleted a; // c
function f() { / ; // c / } // c // c
a; ; /* c */ / b; /* c */ on its own line, then moved a; /* c */
semi: false: ; // c / [1].forEach(f) // c, then a blank line before ;[1] // c / ;[1].forEach(f)
// only (a file with only comments) empty file // only

Static 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 // c on 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:

Verification

  • pnpm test: 5632 passed. pnpm typecheck, pnpm changeset:check and Prettier --check on the changed files all pass.
  • New tests: 6 parser tests and 18 formatter tests. The formatter tests also check that a second pass changes nothing. Without the fix, 15 of the formatter tests and 4 of the parser tests fail. The rest check that nothing regresses: the clause-body comment, static blocks and namespaces, and inputs that were already correct.
  • Probe: formatted every tracked .tsrx file 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 the semi: false cases match Prettier.

Related bugs found and filed

🤖 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 EmptyStatement nodes that sit in a list (Program, blocks, switch cases, etc.). Comments move to the previous or next real statement, or to the block/file as innerComments when the list is only empty statements. Clause bodies like if (x) ; // c still keep comments on the empty statement. Trailing-comment logic skips past consecutive empty siblings so patterns like a; ; // c attach to a.

The formatter prints a Program’s innerComments when 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.

#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]>
@vercel

vercel Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
tsrx-website Ready Ready Preview Sep 24, 2026 8:55pm UTC
tsrx-website-mcp Ready Ready Preview Sep 24, 2026 8:55pm UTC

Request Review

@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 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.

Create PR

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.

Comment thread packages/tsrx/src/parse/index.js Resolved
leonidaz and others added 2 commits September 24, 2026 17:13
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
@leonidaz
leonidaz merged commit ce6bd8d into main Sep 24, 2026
8 checks passed
@leonidaz
leonidaz deleted the fix/prettier-empty-statement-comment-288 branch September 24, 2026 21:28
@github-actions github-actions Bot mentioned this pull request Sep 24, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Formatter prints a comment after an empty statement with a stray space and is not idempotent

1 participant