Skip to content

fix(prettier): keep empty bodies and lay out assigned values like Prettier (#254, #255, #256) - #283

Merged
leonidaz merged 2 commits into
mainfrom
fix/prettier-empty-body-254
Sep 24, 2026
Merged

leonidaz merged 2 commits into
mainfrom
fix/prettier-empty-body-254

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #254
Closes #255
Closes #256

Summary

Three formatter fixes found while working on #258. One changes behavior and two are layout gaps against Prettier:

Input Before Now
if (a); + count++; (#254) if (a) + count++; (the next statement becomes the body) unchanged
for (;;);, while (next());, do; + while (x); (#254) for (;;), while (next()), do while (x); unchanged
const g = a || b ? c : d; (#255) const g = + a || b ? c : d; unchanged
const x = ( + // note + cache.entry + ); (#256) const x = // note + cache.entry; at column zero const x = + indented // note + indented cache.entry;

Changes

  • Empty bodies ([Bug]: Formatter drops an empty loop or if body and makes the next statement the body #254). if, else, for, for…in, for…of, while and do print their body through printClause. Like Prettier's adjustClause, it prints an empty statement body as ; against the header. A do body that is not a block now puts while on its own line, as Prettier does (do x++; / while (y);). The old do x++; while (y); was valid, but the empty case needs a separator rule, so this uses Prettier's.
  • Conditional initializers ([Bug]: Formatter breaks a short conditional initializer onto its own line #255). The declarator used a line outside any group, so it broke after = whenever the statement broke. It now uses Prettier's chooseLayout choices: break-after-operator when the test is binary or logical, and the existing fluid layout otherwise. That also fixes const w = cond ? call(a, b) : other; breaking, and const v = cond + ? … getting an extra break after = when the branches break.
  • Comments that start an assigned value ([Bug]: Formatter prints an own-line initializer comment right after the = #256). printValueAfterLeadingComment handles variable initializers, assignments (every operator), class fields and object properties, which all had the same bug. An own-line comment prints below the operator with the value indented. A comment already on the operator's line (const x = // note) stays there, and the value is indented on the next line, matching Prettier's output.
  • Which comments count. getOwnLineCommentAhead mirrors printTsrxNode's own rule: a line comment, a block comment that isn't last, or a last block comment that isn't on the node's line and doesn't hug a type cast's (. It follows the leftmost operand (getLeftmostChildKey), because in ( + // note + a || b + )() the comment belongs to the callee. It stops at printed parentheses and prettier-ignore source. This replaces argumentHasOwnLineLeadingComment, so return and throw use it too.
  • Type casts inside parentheses a parent adds. return, throw, and a superclass that needs parentheses print the node with suppressOwnParens, which also skipped a JSDoc cast's parentheses: return ( + // note + /** @type {Entry} */ (node) + ); lost the cast. Routing stacked casts after return into that path made it more common (Bugbot's review item), so cast parentheses now print regardless of suppressOwnParens.

Parser or printer

I looked at changing the parser's comment attachment instead, so a comment inside leading parentheses would attach to the outer node. I kept the fix in the printer for three reasons:

  • The parser attaches the comment to the first node that starts after it, which is also what Prettier's attachment does.
  • Moving it to the outer call would widen what // prettier-ignore covers, and the call's verbatim slice would print the comment a second time.
  • The compiler's source mapping and JSX helpers also read leadingComments.

Prettier handles the same problem in the printer too: returnArgumentHasLeadingComment walks the left side.

Output changes for existing code

  • return and throw now wrap their argument in parentheses in two cases where they used to print a line break right after the keyword, which returned undefined: the leftmost operand has an own-line comment (return ( + // note + a || b + )();), or two block comments share a line before the argument (return /* a */ /* b */ x;). Two files in this repo hit the second case with a double JSDoc cast (packages/tsrx/src/parse/style.js:205 and a plugin.js return). The line break between the comments is [Bug]: Formatter breaks the line between block comments that share a line #279.
  • return /** @type {X} */ ( + foo() + ); keeps the cast on the return line. A superclass that needs parentheses keeps its cast inside them: class A extends (/** @type {Base} */ (new Base())) {}. It used to be wrapped in return (…) with the cast's parentheses dropped.
  • A nested conditional initializer without parentheses now stays on one line when it fits (const y = a ? b : c ? d : e;), like an assignment already did. return still breaks it; that is [Bug]: Formatter breaks a short nested conditional after return, throw, and export default #280.
  • Across the repo's 69 .tsrx files, only vite-plugin-react/tests/fixtures/react-aria/App.tsrx formats differently. It has a short conditional initializer, and this PR reformats it so pnpm format:check passes.

Verification

  • Rebased on main after fix(prettier): keep trailing array holes, JSX attribute entities, and string escapes (#269, #270, #271) #277. pnpm test: 118 files, 5572 tests pass (60 skipped). pnpm test --project prettier-plugin: 739 pass, including 25 new cases. 23 of them fail on main.
  • pnpm typecheck, pnpm format:check and pnpm changeset:check pass.
  • A 30-case probe of comment and empty-body edge cases checks four things for each output: formatting is idempotent, TypeScript's parser reports no errors, Prettier's typescript parser gives the same tree as the input, and every comment survives. All 30 pass. The cases include JSDoc casts, prettier-ignore, semi: false, typed declarators, compound assignment operators, and multiple declarators.
  • The repo's 186 JS/TS source files were formatted with the old and new plugin and compared after re-parsing with Prettier's typescript parser. Only the two return double-cast files differ, both in the fix described above. No file became invalid or non-idempotent, and packages/tsrx/src/utils/builders.js became idempotent.

Related findings

Filed separately because they have different causes:

#274 (yield with a leading line comment) is the same ASI problem as return and throw. getOwnLineCommentAhead could decide it, but it is a separate printer and this PR doesn't touch it.

🤖 Generated with Claude Code


Note

Medium Risk
Printer changes fix semantics-changing formatting (empty ;, return/throw ASI) and will reformat some existing sources, though scope is limited to the prettier plugin.

Overview
Fixes semantic and layout bugs in @tsrx/prettier-plugin so output matches Prettier and no longer alters program meaning.

Empty control-flow bodies now print via printClause, preserving ; on EmptyStatement for if/else, loops, and do…while, and putting while on its own line when the do body is not a block.

Initializer and assignment layout is tightened: short ternaries stay on the = line; binary/logical tests break after =; fluid layout covers other conditionals and calls. printValueAfterLeadingComment indents values when a leading comment would otherwise start at column zero (declarators, assignments, class fields, object properties).

return / throw use getOwnLineCommentAhead (replacing the narrower argumentHasOwnLineLeadingComment) to wrap arguments in parens when an own-line comment would trigger ASI, including comments on leftmost operands inside wrapping parens. JSDoc type-cast parentheses still print when a parent uses suppressOwnParens.

Adds a patch changeset and 24+ formatter tests; one vite react-aria fixture is reformatted for a short ternary.

Reviewed by Cursor Bugbot for commit 3dcd84a. Bugbot is set up for automated code reviews on this repo. Configure here.

@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:10pm UTC
tsrx-website-mcp Ready Ready Preview Sep 24, 2026 8:10pm UTC

Request Review

…ttier (#254, #255, #256)

An empty statement body printed as nothing, so `if (a);` followed by
`count++;` became `if (a)` + `count++;` and the next statement became the
body. Loop and `if` bodies now go through `printClause`, which prints an
empty body as `;` against the header, as Prettier's `adjustClause` does.
A `do` body that is not a block puts `while` on its own line.

A conditional initializer used a `line` outside any group, so it broke after
the `=` whenever the statement broke, even when it fit. It now uses Prettier's
layouts: break-after-operator for a binary or logical test, fluid otherwise.

A comment that starts an assigned value printed right after the operator and
pushed the value to column zero. `printValueAfterLeadingComment` now puts an
own-line comment below the operator, keeps a comment already on the
operator's line there, and indents the value under it. It covers variable
initializers, assignments, class fields and object properties. The check
(`getOwnLineCommentAhead`) mirrors printTsrxNode's comment rule and walks the
leftmost operand, since a comment inside `(a || b)()` belongs to the callee.
`return` and `throw` share it, so they no longer print `return // note` for
such an argument, which returned `undefined`.

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

@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: Wrap drops JSDoc type-cast parens
    • Return and throw now keep each JSDoc cast's parentheses, including stacked casts, so the comments still hug (expr) and TypeScript treats them as casts.

Create PR

Or push these changes by commenting:

@cursor push bd19d79915
Preview (bd19d79915)
diff --git a/.changeset/prettier-empty-body-and-assigned-values.md b/.changeset/prettier-empty-body-and-assigned-values.md
new file mode 100644
--- /dev/null
+++ b/.changeset/prettier-empty-body-and-assigned-values.md
@@ -1,0 +1,26 @@
+---
+'@tsrx/prettier-plugin': patch
+---
+
+The formatter no longer changes what code does when a loop or `if` has an empty
+body, or when a comment starts a returned value, and it lays out assigned values
+the way Prettier does:
+
+- An empty statement body keeps its `;`. `if (a);` followed by `count++;` used
+  to print as `if (a)` followed by `count++;`, which made `count++` the body. The
+  same applied to `while`, `for`, `for…in`, `for…of`, `do`, and `else`. A `do`
+  loop whose body is not a block now prints `while` on its own line, as
+  Prettier does.
+- A short conditional initializer stays on the `=` line: `const g = a || b ? c : d;`
+  and `const x = a ? (b ? c : d) : e;` no longer break after the `=`. Longer
+  ones follow Prettier: a binary or logical test breaks after the `=`, and any
+  other test stays on the `=` line while the branches break.
+- A comment that starts a variable initializer, assignment, class field, or
+  object property value no longer pushes the value to column zero. An own-line
+  comment prints below the operator with the value indented under it, and a
+  comment right after the operator stays on that line.
+- `return` and `throw` keep their argument when a comment inside the argument's
+  leading parentheses ends its line, as in `return (` + `// note` + `a || b` +
+  `)();` on separate lines, or when two block comments lead the argument, as in
+  `return /* a */ /* b */ x;`. Both used to print a line break right after
+  `return`, which returned `undefined`.

diff --git a/.changeset/prettier-jsdoc-cast-parens.md b/.changeset/prettier-jsdoc-cast-parens.md
new file mode 100644
--- /dev/null
+++ b/.changeset/prettier-jsdoc-cast-parens.md
@@ -1,0 +1,9 @@
+---
+'@tsrx/prettier-plugin': patch
+---
+
+`return` and `throw` keep JSDoc type casts when the argument starts with more
+than one comment. `return /** @type {A} */ (/** @type {B} */ (x))` used to print
+both comments without the parentheses that make them casts, so TypeScript no
+longer treated them as casts. The same happened to `throw`, and to a cast that
+followed an own-line comment.

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
@@ -507,6 +507,27 @@
 }
 
 /**
+ * Whether `comment` is a JSDoc cast whose `(` opens before `nextStart`
+ * (the next leading comment). One pair of parentheses around the whole value
+ * only keeps the last cast; each earlier one has to be printed after its
+ * comment.
+ * @param {AST.Comment} comment
+ * @param {number} nextStart
+ * @param {TsrxFormatOptions} options
+ * @returns {boolean}
+ */
+function commentOpensTypeCast(comment, nextStart, options) {
+	if (!isTypeCastComment(comment) || typeof options.originalText !== 'string') {
+		return false;
+	}
+	const end = /** @type {AST.NodeWithLocation} */ (comment).end;
+	if (typeof end !== 'number' || nextStart < end) {
+		return false;
+	}
+	return /^\s*\(\s*$/.test(options.originalText.slice(end, nextStart));
+}
+
+/**
  * Whether a parenthesized node's parentheses complete a JSDoc type cast:
  * `/** @type {T} *\/ (value)` only casts `value` with them. The cast comment
  * sits right before the opening paren, so the parser attaches it either to
@@ -1659,6 +1680,11 @@
 
 	/** @type {Doc[]} */
 	const parts = [];
+	// Leading comments fill this list. A stacked JSDoc cast reassigns it to the
+	// inside of the parentheses that comment opens, so later comments hug that
+	// `(`.
+	/** @type {Doc[]} */
+	let commentParts = parts;
 
 	const isInlineContext = args && args.isInlineContext;
 	const suppressLeadingComments = args && args.suppressLeadingComments;
@@ -1671,25 +1697,44 @@
 			const isLastComment = i === node.leadingComments.length - 1;
 
 			if (comment.type === 'Line') {
-				parts.push('//' + comment.value);
-				parts.push(hardline);
+				commentParts.push('//' + comment.value);
+				commentParts.push(hardline);
 
 				// Check if there should be blank lines between this comment and the next
 				if (nextComment) {
 					const blankLinesBetween = getBlankLinesBetweenNodes(comment, nextComment);
 					if (blankLinesBetween > 0) {
-						parts.push(hardline);
+						commentParts.push(hardline);
 					}
 				} else if (isLastComment && node.type !== 'JSXText') {
 					// Preserve a blank line between the last comment and the node if it existed
 					const blankLinesBetween = getBlankLinesBetweenNodes(comment, node);
 					if (blankLinesBetween > 0) {
-						parts.push(hardline);
+						commentParts.push(hardline);
 					}
 				}
 			} else if (comment.type === 'Block') {
-				parts.push('/*' + comment.value + '*/');
+				commentParts.push('/*' + comment.value + '*/');
 
+				const nextStart = /** @type {AST.NodeWithLocation} */ (nextComment ?? node).start;
+				if (
+					nextComment &&
+					typeof nextStart === 'number' &&
+					commentOpensTypeCast(comment, nextStart, options)
+				) {
+					// The `(` between this cast and the next comment is what makes
+					// the comment a cast. Keep it here; the innermost pair is
+					// printed around the value.
+					const inner = /** @type {Doc[]} */ ([]);
+					const blankLinesBetween = getBlankLinesBetweenNodes(comment, nextComment);
+					// A blank line belongs after the opening `(`, not before the close.
+					const openBreak = blankLinesBetween > 0 ? [hardline, hardline] : softline;
+					const closeBreak = blankLinesBetween > 0 ? hardline : softline;
+					commentParts.push(' ', group(['(', indent([openBreak, inner]), closeBreak, ')']));
+					commentParts = inner;
+					continue;
+				}
+
 				// Check if comment and node are on the same line (for inline JSDoc comments)
 				const isCommentInlineWithParen =
 					isLastComment && isCommentFollowedBySameLineParen(comment, options);
@@ -1698,23 +1743,23 @@
 				const shouldKeepOnSameLine = isCommentOnSameLine || isCommentInlineWithParen;
 
 				if (!isInlineContext && !shouldKeepOnSameLine) {
-					parts.push(hardline);
+					commentParts.push(hardline);
 
 					// Check if there should be blank lines between this comment and the next
 					if (nextComment) {
 						const blankLinesBetween = getBlankLinesBetweenNodes(comment, nextComment);
 						if (blankLinesBetween > 0) {
-							parts.push(hardline);
+							commentParts.push(hardline);
 						}
 					} else if (isLastComment) {
 						// Preserve a blank line between the last comment and the node if it existed
 						const blankLinesBetween = getBlankLinesBetweenNodes(comment, node);
 						if (blankLinesBetween > 0) {
-							parts.push(hardline);
+							commentParts.push(hardline);
 						}
 					}
 				} else {
-					parts.push(' ');
+					commentParts.push(' ');
 				}
 			}
 		}
@@ -2357,6 +2402,12 @@
 			// For CallExpression on the right with JSDoc comments, use fluid layout strategy
 			const rightSide = path.call(print, 'right');
 
+			const commentedRight = printValueAfterLeadingComment(path, 'right', rightSide, options);
+			if (commentedRight) {
+				nodeContent = [group(leftPart), ' ', node.operator, commentedRight];
+				break;
+			}
+
 			// Use fluid layout for assignments: allows breaking after operator first
 			const groupId = Symbol('assignment');
 			nodeContent = group([
@@ -2855,10 +2906,13 @@
 			/** @type {Doc[]} */
 			const parts = ['return'];
 			if (node.argument) {
-				if (argumentHasOwnLineLeadingComment(node.argument)) {
+				if (
+					path.call((argumentPath) => getOwnLineCommentAhead(argumentPath, options), 'argument')
+				) {
 					// The comment prints on its own line, which would separate `return`
 					// from its argument and trigger ASI — keep the argument in parens.
-					// These parens replace any the argument would print for itself.
+					// These parens replace precedence parentheses the argument would
+					// print for itself. A JSDoc type cast keeps its own parentheses.
 					parts.push(
 						' (',
 						indent([
@@ -3369,18 +3423,28 @@
 		nodeContent = [...printDecorators(decorated, path, options, print), nodeContent];
 	}
 
-	if (!args?.suppressOwnParens) {
-		if (hasTypeCastParens(path, options)) {
-			// Like Prettier, a cast breaks inside its parens unless it hugs a literal
-			nodeContent =
-				node.type === 'ObjectExpression' || node.type === 'ArrayExpression'
-					? ['(', nodeContent, ')']
-					: group(['(', indent([softline, nodeContent]), softline, ')']);
-		} else if (needsParens(path, options)) {
-			nodeContent = ['(', nodeContent, ')'];
+	// A parent that prints its own parens (`return` / `throw` with a leading
+	// comment, a superclass) passes `suppressOwnParens` so precedence
+	// parentheses are not doubled. JSDoc type-cast parentheses are not those:
+	// the comment is only a cast when it hugs `(expr)`.
+	if (hasTypeCastParens(path, options)) {
+		// Like Prettier, a cast breaks inside its parens unless it hugs a literal
+		nodeContent =
+			node.type === 'ObjectExpression' || node.type === 'ArrayExpression'
+				? ['(', nodeContent, ')']
+				: group(['(', indent([softline, nodeContent]), softline, ')']);
+	} else if (!args?.suppressOwnParens && needsParens(path, options)) {
+		nodeContent = ['(', nodeContent, ')'];
+	}
+
+	if (commentParts !== parts) {
+		// Trailing comments belong with the value, inside the cast parentheses.
+		const finished = finishTsrxNode(/** @type {AST.Node} */ (node), commentParts, nodeContent);
+		if (finished !== commentParts) {
+			commentParts.push(finished);
 		}
+		return parts;
 	}
-
 	return finishTsrxNode(/** @type {AST.Node} */ (node), parts, nodeContent);
 }
 
@@ -4555,6 +4619,18 @@
 }
 
 /**
+ * Print a loop or `if` body after its header. An empty statement body prints
+ * as `;` against the header, as Prettier does: printing nothing would make the
+ * next statement the body.
+ * @param {AST.Statement} body - The body statement
+ * @param {Doc} bodyDoc - The printed body
+ * @returns {Doc}
+ */
+function printClause(body, bodyDoc) {
+	return body.type === 'EmptyStatement' ? [bodyDoc, ';'] : [' ', bodyDoc];
+}
+
+/**
  * Print an if statement
  * @param {AST.IfStatement} node - The if statement node
  * @param {AstPath<AST.IfStatement>} path - The AST path
@@ -4587,15 +4663,11 @@
 	parts.push(testDoc);
 
 	// Handle the consequent
-	if (consequentIsBlock) {
-		// For block statements, add a space before the block
-		parts.push(' ', consequent);
-	} else if (consequentIsIf) {
+	if (consequentIsIf) {
 		// For nested if statements, add a line break and indent
 		parts.push(indent([hardline, consequent]));
 	} else {
-		// For other non-block statements, add a space
-		parts.push(' ', consequent);
+		parts.push(printClause(node.consequent, consequent));
 	}
 
 	// Handle the alternate
@@ -4607,9 +4679,10 @@
 			parts.push(' ');
 		}
 
-		parts.push(directive ? '@else ' : 'else ');
+		parts.push(directive ? '@else' : 'else');
 		if (directive && node.alternate.type === 'IfStatement') {
 			parts.push(
+				' ',
 				path.call(
 					(alternatePath) =>
 						printIfStatement(
@@ -4623,7 +4696,7 @@
 				),
 			);
 		} else {
-			parts.push(path.call(print, 'alternate'));
+			parts.push(printClause(node.alternate, path.call(print, 'alternate')));
 		}
 	}
 
@@ -4646,8 +4719,7 @@
 	parts.push(' in ');
 	parts.push(path.call(print, 'right'));
 
-	parts.push(') ');
-	parts.push(path.call(print, 'body'));
+	parts.push(')', printClause(node.body, path.call(print, 'body')));
 
 	return parts;
 }
@@ -4680,8 +4752,7 @@
 		parts.push(path.call(print, 'key'));
 	}
 
-	parts.push(') ');
-	parts.push(path.call(print, 'body'));
+	parts.push(')', printClause(node.body, path.call(print, 'body')));
 	if (node.empty) {
 		parts.push(directive ? ' @empty ' : ' empty ');
 		parts.push(path.call(print, 'empty'));
@@ -4722,8 +4793,7 @@
 		parts.push(path.call(print, 'update'));
 	}
 
-	parts.push(') ');
-	parts.push(path.call(print, 'body'));
+	parts.push(')', printClause(node.body, path.call(print, 'body')));
 
 	return parts;
 }
@@ -4751,8 +4821,7 @@
 
 	parts.push('while (');
 	parts.push(test);
-	parts.push(') ');
-	parts.push(path.call(print, 'body'));
+	parts.push(')', printClause(node.body, path.call(print, 'body')));
 
 	return parts;
 }
@@ -4774,17 +4843,12 @@
 
 	/** @type {Doc[]} */
 	const parts = [];
-	parts.push('do ');
-	parts.push(path.call(print, 'body'));
+	parts.push('do', printClause(node.body, path.call(print, 'body')));
+	// Like Prettier, only a block body keeps `while` on its closing line
+	parts.push(node.body.type === 'BlockStatement' ? ' ' : hardline);
 
 	// Print leading comments from test node before 'while' keyword
-	const commentParts = extractAndPrintLeadingComments(testNode);
-	if (commentParts.length > 0) {
-		parts.push(' ');
-		parts.push(...commentParts);
-	} else {
-		parts.push(' ');
-	}
+	parts.push(...extractAndPrintLeadingComments(testNode));
 
 	parts.push('while (');
 	parts.push(test);
@@ -5283,8 +5347,9 @@
 
 	// Initializer
 	if (node.value) {
-		parts.push(' = ');
-		parts.push(path.call(print, 'value'));
+		const value = path.call(print, 'value');
+		const commentedValue = printValueAfterLeadingComment(path, 'value', value, options);
+		parts.push(...(commentedValue ? [' =', commentedValue] : [' = ', value]));
 	}
 
 	parts.push(semi(options));
@@ -5567,9 +5632,10 @@
 function printThrowStatement(node, path, options, print) {
 	/** @type {Doc[]} */
 	const parts = [];
-	if (argumentHasOwnLineLeadingComment(node.argument)) {
+	if (path.call((argumentPath) => getOwnLineCommentAhead(argumentPath, options), 'argument')) {
 		// Same ASI hazard as `return`: keep the argument attached via parens.
-		// These parens replace any the argument would print for itself.
+		// These parens replace precedence parentheses the argument would
+		// print for itself. A JSDoc type cast keeps its own parentheses.
 		parts.push(
 			'throw (',
 			indent([
@@ -5588,30 +5654,88 @@
 }
 
 /**
- * Check whether a return/throw argument has a leading comment that prints on
- * its own line (line comments always do; block comments only when they did not
- * share a line with the argument in the source).
- * @param {AST.Node | null | undefined} argument - The statement argument
+ * Whether printTsrxNode ends a node's leading comments with a line break. It
+ * does after a line comment, and after a block comment unless that comment
+ * hugs a type cast's `(`, or it is the last comment and shares its line with
+ * the node or with a type cast's `(`.
+ * @param {AST.Node} node - The node
+ * @param {TsrxFormatOptions} options - Prettier options
  * @returns {boolean}
  */
-function argumentHasOwnLineLeadingComment(argument) {
-	if (!argument) {
-		return false;
-	}
-	const comments = /** @type {AST.NodeWithMaybeComments} */ (argument).leadingComments;
+function hasOwnLineLeadingComment(node, options) {
+	const comments = /** @type {AST.NodeWithMaybeComments} */ (node).leadingComments;
 	if (!comments) {
 		return false;
 	}
-	return comments.some(
-		(comment) =>
-			comment.type === 'Line' ||
-			!comment.loc ||
-			!argument.loc ||
-			comment.loc.end.line !== argument.loc.start.line,
-	);
+	return comments.some((comment, index) => {
+		if (comment.type === 'Line') {
+			return true;
+		}
+		if (index < comments.length - 1) {
+			const nextStart = /** @type {AST.NodeWithLocation} */ (comments[index + 1]).start;
+			// A stacked cast prints `(` after this comment, so the comment does
+			// not end the line between `return`/`throw` and the argument.
+			return !(typeof nextStart === 'number' && commentOpensTypeCast(comment, nextStart, options));
+		}
+		const isOnNodeLine = comment.loc && node.loc && comment.loc.end.line === node.loc.start.line;
+		return !isOnNodeLine && !isCommentFollowedBySameLineParen(comment, options);
+	});
 }
 
 /**
+ * The first comment printed ahead of the node at `path`, when the comments
+ * printed ahead of it end with a line break. The leftmost operand's comments
+ * print ahead of the node too (a comment inside the parentheses of
+ * `(a || b)()` belongs to the callee), unless the node prints its own
+ * parentheses or its source verbatim.
+ * @param {AstPath} path - The path to the node
+ * @param {TsrxFormatOptions} options - Prettier options
+ * @returns {AST.Comment | null}
+ */
+function getOwnLineCommentAhead(path, options) {
+	const node = /** @type {AST.Node & AST.NodeWithMaybeComments} */ (path.node);
+	const firstComment = node.leadingComments?.[0] ?? null;
+	if (hasOwnLineLeadingComment(node, options)) {
+		return firstComment;
+	}
+	const key = getLeftmostChildKey(node);
+	if (
+		!key ||
+		hasPrettierIgnore(node) ||
+		hasTypeCastParens(path, options) ||
+		needsParens(path, options)
+	) {
+		return null;
+	}
+	const comment = path.call((childPath) => getOwnLineCommentAhead(childPath, options), key);
+	return comment && (firstComment ?? comment);
+}
+
+/**
+ * Print the value after an assignment-like operator (`=`, `:`) when the value
+ * starts with a comment that ends its line, as Prettier does: a comment on the
+ * operator's line stays there, one on its own line moves below the operator,
+ * and the value indents under the operator instead of starting at column zero.
+ * @param {AstPath} path - The path to the assignment-like node
+ * @param {string} key - The property that holds the value
+ * @param {Doc} valueDoc - The printed value, including its leading comments
+ * @param {TsrxFormatOptions} options - Prettier options
+ * @returns {Doc | null} - The doc that follows the operator, or null when the
+ * value starts with no such comment
+ */
+function printValueAfterLeadingComment(path, key, valueDoc, options) {
+	const comment = path.call((valuePath) => getOwnLineCommentAhead(valuePath, options), key);
+	if (!comment) {
+		return null;
+	}
+	const commentStart = /** @type {AST.NodeWithLocation} */ (comment).start;
+	if (hasNewline(options.originalText ?? '', commentStart, { backwards: true })) {
+		return indent([hardline, valueDoc]);
+	}
+	return [' ', indent(valueDoc)];
+}
+
+/**
  * Print a TypeScript interface declaration
  * @param {AST.TSInterfaceDeclaration} node - The interface declaration node
  * @param {AstPath<AST.TSInterfaceDeclaration>} path - The AST path
@@ -6487,8 +6611,9 @@
 	const parts = [];
 	parts.push(...printKey(node, path, options, print));
 
-	parts.push(': ');
-	parts.push(path.call(print, 'value'));
+	const value = path.call(print, 'value');
+	const commentedValue = printValueAfterLeadingComment(path, 'value', value, options);
+	parts.push(...(commentedValue ? [':', commentedValue] : [': ', value]));
 	return parts;
 }
 
@@ -6505,35 +6630,25 @@
 		const id = path.call(print, 'id');
 		const init = path.call(print, 'init');
 
+		const commentedInit = printValueAfterLeadingComment(path, 'init', init, options);
+		if (commentedInit) {
+			return [group(id), ' =', commentedInit];
+		}
+
 		// A decorated class expression leads with its decorators on their own
 		// lines, so the whole thing moves below the `=` to stay indented.
 		if (node.init.type === 'ClassExpression' && getDecorators(node.init).length > 0) {
 			return [id, ' =', indent([hardline, init])];
 		}
 
-		// For conditional expressions that will break, put them on a new line
-		if (node.init.type === 'ConditionalExpression') {
-			// Check if the ternary will break by checking if it has complex branches
-			// or if the doc builder indicates it will break
-			const ternaryWillBreak = willBreak(init);
-
-			// Also check if either branch is a CallExpression (which typically breaks)
-			const hasComplexBranch =
-				node.init.consequent.type === 'CallExpression' ||
-				node.init.alternate.type === 'CallExpression';
-
-			// Check if test is a LogicalExpression or BinaryExpression with complex operators
-			const hasComplexTest =
-				node.init.test.type === 'LogicalExpression' || node.init.test.type === 'BinaryExpression';
-
-			// Check if there are nested ternaries
-			const hasNestedTernary =
-				node.init.consequent.type === 'ConditionalExpression' ||
-				node.init.alternate.type === 'ConditionalExpression';
-
-			if (ternaryWillBreak || hasComplexBranch || hasComplexTest || hasNestedTernary) {
-				return [id, ' =', indent([line, init])];
-			}
+		// Like Prettier, a conditional with a binary or logical test breaks after
+		// the `=` before it breaks itself. Any other conditional uses the fluid
+		// layout below, keeping its test on the `=` line while that fits.
+		if (
+			node.init.type === 'ConditionalExpression' &&
+			(node.init.test.type === 'BinaryExpression' || node.init.test.type === 'LogicalExpression')
+		) {
+			return group([group(id), ' =', group(indent([line, init]))]);
 		}
 
 		// For arrays/objects with blank lines, use conditionalGroup to try both layouts
@@ -6590,9 +6705,8 @@
 			const init = path.call(print, 'init');
 			return group([group(id), ' =', group(indent([line, init]))]);
 		}
-		// For CallExpression inits, use fluid layout strategy to break after = if needed
-		const isCallExpression = node.init.type === 'CallExpression';
-		if (isCallExpression) {
+		// For CallExpression and ConditionalExpression inits, use fluid layout strategy to break after = if needed
+		if (node.init.type === 'CallExpression' || node.init.type === 'ConditionalExpression') {
 			// Always use fluid layout for call expressions
 			// This allows breaking after = when the whole line doesn't fit
 			{

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
@@ -7791,6 +7791,217 @@
 		});
 	});
 
+	// Dropping the `;` of an empty body makes the next statement the body, so the
+	// formatted program runs different code and a trailing loop stops parsing.
+	describe('empty statement bodies keep their semicolon', () => {
+		it.each([
+			'if (a);\ncount++;',
+			'while (next());\ncount++;',
+			'for (const k of list);\ncount++;',
+			'for (const k in obj);\ncount++;',
+			'for (;;);',
+			'for (let i = 0; i < n; i++);\ncount++;',
+			'do;\nwhile (next());',
+			'if (a) b();\nelse;',
+			'if (a);\nelse if (b);\nelse c();',
+		])('keeps the empty body of %s', async (source) => {
+			const result = await format(source);
+			expect(result).toBeWithNewline(source);
+		});
+
+		it('keeps the empty body with semi: false', async () => {
+			const source = 'if (a);\ncount++\nwhile (next());\ndo;\nwhile (next())';
+			const result = await format(source, { semi: false });
+			expect(result).toBeWithNewline(source);
+		});
+
+		it('puts while on its own line after a non-block do body', async () => {
+			const result = await format('do count++; while (next());');
+			expect(result).toBeWithNewline('do count++;\nwhile (next());');
+		});
+	});
+
+	describe('variable initializer layouts follow Prettier', () => {
+		it.each([
+			'const g = a || b ? c : d;',
+			'const i = a > 1 ? b : c;',
+			'const x = a ? (b ? c : d) : e;',
+			'const y = a ? b : c ? d : e;',
+			'const w = cond ? call(argumentOne, argumentTwo) : other;',
+		])('keeps the short conditional initializer %s on one line', async (source) => {
+			const result = await format(source);
+			expect(result).toBeWithNewline(source);
+		});
+
+		it('breaks after = before a conditional with a binary test', async () => {
+			const source = `const z =
+  isSomethingVeryLong || otherCondition
+    ? someVeryLongValueNameHere
+    : anotherLongValue;`;
+			const result = await format(source);
+			expect(result).toBeWithNewline(source);
+		});
+
+		it('keeps any other conditional test on the = line', async () => {
+			const source = `const v = cond
+  ? call(argumentOne, argumentTwo, argumentThree, argumentFour)
+  : otherValueHere;
+const u = cond
+  ? () => {
+      run();
+    }
+  : null;`;
+			const result = await format(source);
+			expect(result).toBeWithNewline(source);
+		});
+	});
+
+	describe('comments that start an assigned value', () => {
+		it('prints an own-line comment below the = with the value indented', async () => {
+			const input = `const value = (
+  // pick the cached entry
+  cache.entry
+);
+const block = (
+  /* pick the cached entry */
+  cache.entry
+);`;
+			const expected = `const value =
+  // pick the cached entry
+  cache.entry;
+const block =
+  /* pick the cached entry */
+  cache.entry;`;
+			const result = await format(input);
+			expect(result).toBeWithNewline(expected);
+		});
+
+		it('keeps a comment on the = line and indents the value below it', async () => {
+			const source = `const value = // pick the cached entry
+  cache.entry;
+const call = // compute it
+  compute(a);`;
+			const result = await format(source);
+			expect(result).toBeWithNewline(source);
+		});
+
+		it('indents the value in assignments, class fields, and object properties', async () => {
+			const source = `value =
+  // pick the cached entry
+  cache.entry;
+total += // running sum
+  next;
+class Store {
+  value =
+    // pick the cached entry
+    cache.entry;
+}
+const options = {
+  value:
+    // pick the cached entry
+    cache.entry,
+};`;
+			const result = await format(source);
+			expect(result).toBeWithNewline(source);
+		});
+
+		it('sees a comment that belongs to the leftmost operand', async () => {
+			const input = `const called = (
+  // pick the handler
+  primary || fallback
+)();
+const member = (
+  // pick the cache
+  cache
+).entry;`;
+			const expected = `const called =
+  // pick the handler
+  (primary || fallback)();
+const member =
+  // pick the cache
+  cache.entry;`;
+			const result = await format(input);
+			expect(result).toBeWithNewline(expected);
+		});
+
+		it('keeps a type cast comment on the = line', async () => {
+			await expect(format('const value = /** @type {Entry} */ (cache.entry);')).resolves.toBe(
+				'const value = /** @type {Entry} */ (cache.entry);\n',
+			);
+		});
+
+		// A line break between `return` or `throw` and its argument ends the
+		// statement, so the argument would no longer be returned or thrown.
+		it('keeps a return or throw argument whose leftmost operand has an own-line comment', async () => {
+			const input = `function run() {
+  return (
+    // pick the handler
+    primary || fallback
+  )();
+}
+function fail() {
+  throw (
+    // pick the error
+    errors
+  ).first;
+}`;
+			const expected = `function run() {
+  return (
+    // pick the handler
+    (primary || fallback)()
+  );
+}
+function fail() {
+  throw (
+    // pick the error
+    errors.first
+  );
+}`;
+			const result = await format(input);
+			expect(result).toBeWithNewline(expected);
+		});
+
+		// A JSDoc cast is only a cast while its comment hugs `(expr)`. Wrapping
+		// the argument to avoid ASI used to drop those parentheses.
+		it('keeps JSDoc type casts on a return or throw argument with leading comments', async () => {
+			const input = `function run() {
+  return /** @type {A} */ (/** @type {B} */ (x));
+}
+function fail() {
+  throw /** @type {A} */ (/** @satisfies {B} */ (x));
+}
+function noted() {
+  return (
+    // note
+    /** @type {T} */ (value)
+  );
+}
+function blocked() {
+  return /* note */ /** @type {A} */ (/** @type {B} */ (x));
+}`;
+			const expected = `function run() {
+  return /** @type {A} */ (/** @type {B} */ (x));
+}
+function fail() {
+  throw /** @type {A} */ (/** @satisfies {B} */ (x));
+}
+function noted() {
+  return (
+    // note
+    /** @type {T} */ (value)
+  );
+}
+function blocked() {
+  return (
+    /* note */
+    /** @type {A} */ (/** @type {B} */ (x))
+  );
+}`;
+			const result = await format(input);
+			expect(result).toBeWithNewline(expected);
+		});
+	});
+
 	// Import aliases and export assignments are runtime bindings. Dropping one
 	// leaves every later reference dangling, and the file still compiles, so the
 	// break only surfaces when the module runs.

diff --git a/packages/vite-plugin-react/tests/fixtures/react-aria/App.tsrx b/packages/vite-plugin-react/tests/fixtures/react-aria/App.tsrx
--- a/packages/vite-plugin-react/tests/fixtures/react-aria/App.tsrx
+++ b/packages/vite-plugin-react/tests/fixtures/react-aria/App.tsrx
@@ -18,8 +18,7 @@
 	const [entries, setEntries] = useState<ActionLogEntry[]>([]);
 	const lastEntry = entries.at(-1);
 	function recordAction(id: ActionId, pointerType: ActionPointerType) {
-		const action =
-			id === saveAction.id ? saveAction : deleteAction;
+		const action = id === saveAction.id ? saveAction : deleteAction;
 		setEntries((prev) => [...prev, { id, label: action.label, pointerType }]);
 	}

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

Reviewed by Cursor Bugbot for commit 2af0e22. Configure here.

Comment thread packages/prettier-plugin/src/index.js Resolved
`return` and `throw` wrap an argument with an own-line comment in their own
parentheses and print it with `suppressOwnParens`, and so does a superclass
that needs parentheses. That flag also skipped a JSDoc cast's parentheses, so
`/** @type {Entry} */ (node)` printed as a plain comment before `node`. This
PR routes stacked casts after `return` into that path, which Bugbot flagged.
A cast's parentheses belong to the cast, so they now print regardless of
`suppressOwnParens`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@leonidaz
leonidaz force-pushed the fix/prettier-empty-body-254 branch from 2af0e22 to 3dcd84a Compare September 24, 2026 20:08
@leonidaz
leonidaz merged commit 4cb3595 into main Sep 24, 2026
11 checks passed
@leonidaz
leonidaz deleted the fix/prettier-empty-body-254 branch September 24, 2026 20:13
@github-actions github-actions Bot mentioned this pull request Sep 24, 2026
trueadm added a commit to octanejs/octane that referenced this pull request Sep 30, 2026
…ng .tsrx (#1452)

@tsrx/prettier-plugin 0.4.10 had no LabeledStatement printer. Its fallback
logged "Unknown node type" and wrote `/* Unknown: LabeledStatement */` in
place of the statement, and `pnpm format:files` still wrote the file. It also
printed an empty statement body as nothing, so `while (x);` followed by a
statement made that statement the loop body.

Patch the plugin (patches/@[email protected]) with a
backport of tsrx-org/tsrx#322 (labeled statements, including comments around
the colon and prettier-ignore) and the empty-body part of tsrx-org/tsrx#283
(`printClause` for if/else/for/for-in/for-of/while/do bodies). A node type
with no printer now throws instead of emitting a placeholder. Upstream fixed
all three in 0.4.12 and 0.5.x, but 0.5.2 would reformat 1,564 of 2,217
.tsrx files, so the upgrade stays a separate change.

The same fallback had already deleted `export * from './server'` from puck's
SlotRender module, so every `<Render>` of a slot field threw "Element type is
invalid". Restore it and cover slot rendering in the puck render contract.

scripts/tsrx-prettier-plugin.test.mjs (in ci:workflow:test) pins the output,
checks idempotence, compares the AST before and after formatting, and checks
the unknown-node throw; scripts/fixtures/tsrx-prettier-statements.tsrx makes
`pnpm format:check` fail if the patch is lost.

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

2 active deployments
Preview – tsrx-website — 3dcd84a2 Deployed Sep 24, 2026 by vercel[bot]
Preview – tsrx-website-mcp — 3dcd84a2 Deployed Sep 24, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant