Repository navigation
fix(prettier): guard statements without semicolons, keep directives and tagged-template type arguments (#263, #266, #268) - #290
Merged
Conversation
…nd tagged-template type arguments (#263, #266, #268) - With `semi: false`, an expression statement that starts with `(`, `[`, `` ` ``, `/`, `+`, `-` or `<` now starts with `;`, like Prettier's shouldPrintLeadingSemicolon, in every statement list (program, blocks, static blocks, namespaces, switch cases, and template code blocks). The `;` goes after the statement's comments but before a JSDoc cast comment, and a prettier-ignore'd statement is checked from its source text. - Statement lists drop empty statements like Prettier, and blank lines are counted from a statement's content when its `;` sits on the next line, so semicolon-free output stays stable. - Tagged templates print their type arguments. - Directives print from their source text with Prettier's printDirective quote rule, and the empty directive `"";` no longer gets parentheses that end the prologue. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
…ded statement With `semi: false`, `a\n\n// note\n;[b].c()` lost its blank line on the next pass: the check for a `;` on the next statement's line compared against the statement's first leading comment instead of the statement itself. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ective-tagged-263
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: Blank lines lost after unlisted statements
- Blank lines before a guarded statement are now measured from the real end of if, for, while, break, continue, debugger, return, and export { … }, so a leading semicolon on the next line no longer drops the gap.
Or push these changes by commenting:
@cursor push 8ea062b683
Preview (8ea062b683)
diff --git a/.changeset/prettier-blank-line-after-statements.md b/.changeset/prettier-blank-line-after-statements.md
new file mode 100644
--- /dev/null
+++ b/.changeset/prettier-blank-line-after-statements.md
@@ -1,0 +1,7 @@
+---
+'@tsrx/prettier-plugin': patch
+---
+
+With `semi: false`, a blank line before a statement that starts with `;` stays
+put after `if`, `for`, `while`, `break`, `continue`, `debugger`, `return`, and
+`export { … }`. Formatting that file again no longer deletes the blank line.
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
@@ -1956,7 +1956,7 @@
const nextStmt = node.body[printedIndexes[n + 1]];
// Only add spacing when explicitly needed
- if (shouldAddBlankLine(currentStmt, nextStmt)) {
+ if (shouldAddBlankLine(currentStmt, nextStmt, options.originalText)) {
statements.push([line, line]); // blank line
} else {
statements.push(line); // single line break
@@ -3007,7 +3007,7 @@
const currentStmt = node.body[i];
const nextStmt = node.body[printedIndexes[n + 1]];
- if (shouldAddBlankLine(currentStmt, nextStmt)) {
+ if (shouldAddBlankLine(currentStmt, nextStmt, options.originalText)) {
statements.push(hardline, hardline); // Blank line = two hardlines
} else {
statements.push(hardline); // Normal line break
@@ -5323,7 +5323,7 @@
// Check if we should add a blank line between members
const prevNode = node.body[i - 1];
const currNode = node.body[i];
- if (shouldAddBlankLine(prevNode, currNode)) {
+ if (shouldAddBlankLine(prevNode, currNode, options.originalText)) {
contentParts.push(line);
}
}
@@ -6538,9 +6538,12 @@
* statement's line, and that `;` still ends the previous statement, so its
* blank lines are counted from its content, like Prettier's `__contentEnd`.
* @param {AST.Node | AST.Comment} node - The statement
+ * @param {AST.Node | AST.Comment} [nextNode] - The following statement, whose
+ * leading comments may sit between this statement's text and that `;`
+ * @param {string} [text] - The source being formatted
* @returns {AST.Node | null}
*/
-function getStatementContentEnd(node) {
+function getStatementContentEnd(node, nextNode, text) {
switch (node.type) {
case 'ExpressionStatement':
return node.expression;
@@ -6548,9 +6551,26 @@
return node.declarations[node.declarations.length - 1] ?? null;
case 'ReturnStatement':
case 'ThrowStatement':
- return node.argument ?? null;
+ // `return` can omit its argument; the keyword is the content
+ return node.argument ?? contentEndOnLine(node.loc?.start.line);
case 'DoWhileStatement':
return node.test;
+ case 'BreakStatement':
+ case 'ContinueStatement':
+ return node.label ?? contentEndOnLine(node.loc?.start.line);
+ case 'DebuggerStatement':
+ return contentEndOnLine(node.loc?.start.line);
+ case 'IfStatement': {
+ const branch = node.alternate ?? node.consequent;
+ return getStatementContentEnd(branch) ?? branch;
+ }
+ case 'ForStatement':
+ case 'ForInStatement':
+ case 'ForOfStatement':
+ case 'WhileStatement':
+ case 'LabeledStatement':
+ case 'WithStatement':
+ return getStatementContentEnd(node.body) ?? node.body;
case 'TSTypeAliasDeclaration':
return node.typeAnnotation;
case 'ExportDefaultDeclaration': {
@@ -6558,9 +6578,14 @@
return getStatementContentEnd(declaration) ?? declaration;
}
case 'ExportNamedDeclaration':
- return node.declaration
- ? getStatementContentEnd(node.declaration)
- : /** @type {AST.Node | null} */ (node.source ?? null);
+ if (node.declaration) {
+ return getStatementContentEnd(/** @type {AST.Node} */ (node.declaration));
+ }
+ if (node.source) {
+ return /** @type {AST.Node} */ (node.source);
+ }
+ // `export { … }` has no child that ends at `}`
+ return exportClauseContentEnd(node, nextNode, text);
case 'ExportAllDeclaration':
return node.source;
default:
@@ -6569,12 +6594,86 @@
}
/**
+ * A position on `line`, standing in for statement text that has no child node
+ * (`break`, `debugger`, the `}` of `export { … }`).
+ * @param {number | undefined} line
+ * @returns {AST.Node | null}
+ */
+function contentEndOnLine(line) {
+ if (typeof line !== 'number') return null;
+ return /** @type {AST.Node} */ ({ loc: { end: { line } } });
+}
+
+/**
+ * The line of `}` in `export { … }`. Specifiers end before that brace, and the
+ * `;` that guards the next statement is still inside this node's span.
+ * @param {AST.ExportNamedDeclaration} node
+ * @param {AST.Node | AST.Comment | undefined} nextNode
+ * @param {string | undefined} text
+ * @returns {AST.Node | null}
+ */
+function exportClauseContentEnd(node, nextNode, text) {
+ if (
+ typeof text !== 'string' ||
+ typeof node.start !== 'number' ||
+ typeof node.end !== 'number' ||
+ !node.loc?.start ||
+ text[node.end - 1] !== ';'
+ ) {
+ return null;
+ }
+
+ /** @type {Array<{ start: number, end: number }>} */
+ const comments = [];
+ for (const current of [node, nextNode, ...(node.specifiers ?? [])]) {
+ if (!current) continue;
+ const commented = /** @type {AST.NodeWithMaybeComments} */ (current);
+ for (const list of [
+ commented.leadingComments,
+ commented.trailingComments,
+ commented.innerComments,
+ ]) {
+ if (!list) continue;
+ for (const comment of list) {
+ if (typeof comment.start === 'number' && typeof comment.end === 'number') {
+ comments.push({ start: comment.start, end: comment.end });
+ }
+ }
+ }
+ }
+
+ let pos = node.end - 2;
+ while (pos >= node.start) {
+ const code = text.charCodeAt(pos);
+ // space, tab, LF, CR, VT, FF
+ if (code === 32 || code === 9 || code === 10 || code === 13 || code === 11 || code === 12) {
+ pos--;
+ continue;
+ }
+ const comment = comments.find((entry) => pos >= entry.start && pos < entry.end);
+ if (comment) {
+ pos = comment.start - 1;
+ continue;
+ }
+ break;
+ }
+ if (pos < node.start) return null;
+
+ let line = node.loc.start.line;
+ for (let i = node.start; i < pos; i++) {
+ if (text.charCodeAt(i) === 10) line++;
+ }
+ return contentEndOnLine(line);
+}
+
+/**
* Determine if a blank line should be added between nodes
* @param {AST.Node | AST.Comment} currentNode - Current node
* @param {AST.Node | AST.Comment} nextNode - Next node
+ * @param {string} [text] - The source being formatted
* @returns {boolean}
*/
-function shouldAddBlankLine(currentNode, nextNode) {
+function shouldAddBlankLine(currentNode, nextNode, text) {
// Simplified blank line logic:
// 1. Check if there was originally 1+ blank lines between nodes
// 2. If yes, preserve exactly 1 blank line (collapse multiple to one)
@@ -6605,7 +6704,7 @@
sourceNode === currentNode &&
currentNode.loc?.end.line !== undefined &&
currentNode.loc.end.line === nextNode.loc?.start.line;
- const contentEnd = endsOnNextLine ? getStatementContentEnd(currentNode) : null;
+ const contentEnd = endsOnNextLine ? getStatementContentEnd(currentNode, nextNode, text) : null;
if (contentEnd) {
originalBlankLines = Math.max(
originalBlankLines,
@@ -8254,7 +8353,9 @@
parts.push(path.call(print, 'body', i));
if (i < node.body.length - 1) {
parts.push(
- shouldAddBlankLine(node.body[i], node.body[i + 1]) ? [hardline, hardline] : hardline,
+ shouldAddBlankLine(node.body[i], node.body[i + 1], options.originalText)
+ ? [hardline, hardline]
+ : hardline,
);
}
}
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
@@ -7711,6 +7711,111 @@
;(first || second)()`);
});
+ // The `;` before `[` is parsed as the end of the previous statement, so
+ // a blank line has to be measured from that statement's text.
+ it('keeps the blank line after a statement that ends on the next line', async () => {
+ await expectUnchanged(`function log() {}
+const ready = true
+const items = [1]
+const object = { key: 1 }
+if (ready) log(ready)
+
+;[1].forEach(log)
+for (const item of items) log(item)
+
+;[2].forEach(log)
+for (const key in object) log(key)
+
+;[3].forEach(log)
+for (let i = 0; i < 1; i++) log(i)
+
+;[4].forEach(log)
+while (ready) log(ready)
+
+;[5].forEach(log)
+for (;;) {
+ if (ready) break
+
+ ;[6].forEach(log)
+ continue
+
+ ;[7].forEach(log)
+}
+debugger
+
+;[8].forEach(log)
+export { log }
+
+;[9].forEach(log)
+export {}
+
+;[10].forEach(log)
+function run() {
+ if (ready) return
+
+ ;[11].forEach(log)
+ return
+
+ ;[12].forEach(log)
+}`);
+ });
+
+ it('keeps the blank line before a comment after those statements', async () => {
+ await expectUnchanged(`if (ready) log()
+
+// note
+;[1].forEach(log)
+for (;;) {
+ break
+
+ // note
+ ;[2].forEach(log)
+}
+function log() {}
+export { log }
+
+/* note */
+;[3].forEach(log)`);
+ });
+
+ it('keeps one blank line after a multiline export clause', async () => {
+ const input = `function log() {}
+export {
+ log
+}
+
+;[1].forEach(log)`;
+ const result = await format(input, { semi: false });
+ expect(result).toBeWithNewline(`function log() {}
+export { log }
+
+;[1].forEach(log)`);
+ });
+
+ it('does not add a blank line when an export clause is only wrapped', async () => {
+ const input = `function log() {}
+export {
+ log
+}
+;[1].forEach(log)`;
+ const result = await format(input, { semi: false });
+ expect(result).toBeWithNewline(`function log() {}
+export { log }
+;[1].forEach(log)`);
+ });
+
+ it('does not add a blank line when the semicolon is only the separator', async () => {
+ await expectUnchanged(`if (ready) log()
+;[1].forEach(log)
+for (;;) {
+ break
+ ;[2].forEach(log)
+}
+function log() {}
+export { log }
+;[3].forEach(log)`);
+ });
+
it('drops empty statements from statement lists', async () => {
expect(await format(';log();;\nrun();')).toBeWithNewline('log();\nrun();');
expect(await format('function f() { ; }')).toBeWithNewline('function f() {}');You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 7c62bfa. Configure here.
…text
With `semi: false`, a blank line before a guarded statement was dropped on the
next pass after `if`/`for`/`while` with a statement body, `continue`, `break`,
`debugger`, and `export { … }`, because only a few statement types mapped to
a child that ends their content. Like Prettier's `__contentEnd`, the content
now ends before the statement's final `;` and the whitespace ahead of it,
searching from before any comments that lead the next statement. This also
stops depending on child spans such as the short `<style>` declarator (#287).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merged
leonidaz
added a commit
that referenced
this pull request
Sep 24, 2026
…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]>
leonidaz
added a commit
that referenced
this pull request
Sep 24, 2026
…cast-291 #290 added a rule to printTsrxNode's leading-comment loop: with `semi: false`, a statement's leading `;` goes right before a JSDoc cast comment that touches its `(`. That loop now lives in `printLeadingComments`, so printTsrxNode makes the decision for the comments it prints ahead of the node, and the helper puts the `;` before the last one. `startsWithASIHazard` calls `getTypeCastParens` in place of the renamed `hasTypeCastParens`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Sep 24, 2026
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 was referenced Sep 24, 2026
This branch was successfully deployed
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 #263, #266, #268.
#266: statements without semicolons
With
semi: false, an expression statement that starts with(,[,`,/,+,-or<now starts with;, as Prettier prints it:needsLeadingSemicolonports Prettier'sshouldPrintLeadingSemicolon. It covers every statement list:Program,BlockStatement,StaticBlock,TSModuleBlock,JSXCodeBlock, andSwitchCaseconsequents, including@switchcases.startsWithASIHazardwalks the leftmost operand with the existingneedsParens,hasTypeCastParens, andgetLeftmostChildKey. Sequences count as a hazard becauseprintSequenceExpressionalways prints its own parentheses outside aforhead.;follows the statement's leading comments, except a JSDoc cast. There it goes first (;/** @type {T} */ (value).run()), which is what Prettier's babel parser prints.prettier-ignored statement is checked from its source text, whose parentheses can differ from the printed ones:(new Foo).bar().printsArrowParamWithoutParensis taken out ofprintArrowFunction, sox => xwitharrowParens: "avoid"stays unguarded.Two changes keep this stable across passes:
printStatementSequencedoes. The;before a first statement ({ ;[a].forEach(f) }) parses as anEmptyStatement, and main printed every empty statement as a blank line, including a blank first line in a file that starts with;. Empty statements that carry a comment are still printed ([Bug]: Formatter prints a comment after an empty statement with a stray space and is not idempotent #288).shouldAddBlankLinealso counts blank lines from a statement's content when the statement ends with a;on the next statement's line (a\n\n;[b].c()), like Prettier's__contentEnd. The content end comes from the source text: before the final;and the whitespace ahead of it, searching from before any comments that lead the next statement. This works for every statement type and does not depend on child spans such as the short<style>declarator in [Bug]: An assigned <style> block's declarator ends inside the CSS #287.#263: tagged template type arguments
printTaggedTemplateExpressionprintstypeArguments. The existingTSInstantiationExpressionparens rule keeps(tag<T>)<U>`x`intact. #272 is the compiler-side counterpart and is not changed here.#268: directives
#277 already prints strings from their source text, so
"use\x20strict"survives on main. This PR adds the directive-specific parts:printDirectivefollows Prettier's rule: print the text as written, and swap quotes only when it contains neither quote character.'it\'s'stays as it is.isDirectivecheckstypeof directive === 'string'. The parser stores the empty directive"";asdirective: "", so the old truthiness check parenthesized it. That ended the prologue, and a following"use strict"no longer applied.Verification
pnpm test --project prettier-plugin: 775 passed after merging main (fix(prettier): keep empty bodies and lay out assigned values like Prettier (#254, #255, #256) #283). 33 of the new tests fail against main's plugin.tsgoforprettier-pluginandtsrx-mcp,pnpm --filter tsrx-website typecheck,pnpm format:check,pnpm changeset:check, andpnpm test --project tsrx-mcp..tsrxfile plus about 450 targeted cases, with default options,semi: false,arrowParens: "avoid", andsingleQuote. Then re-parse and compare normalized ASTs. Nothing regresses against main. The hono runtime fixture, which main broke undersemi: false, now round-trips. The leading;lands on the same lines as Prettier'stypescriptparser in all 897 plain-TS comparisons.Related bugs found and filed
;, followed byreturn <div />, fails to parse.expression-spread-ref-components.tsrxstill formats to unparsable code withsemi: falsebecause of it.@caseor@defaultbody.;, soconst x = athen/* c */ <div />fails to parse.semi: false, the guarded cast in those containers is dropped on the second pass.<style>block's declarator ends inside the CSS.🤖 Generated with Claude Code
Note
Medium Risk
Changes core print paths for statements, prologues, and TypeScript tagged templates; wrong ASI or dropped generics would alter runtime or types, but behavior is ported from Prettier with broad tests.
Overview
Aligns
@tsrx/prettier-pluginwith Prettier so formatting no longer changes program meaning in several edge cases.With
semi: false, expression statements that would continue the previous line now get a leading;(after comments, before JSDoc casts), includingprettier-ignoreverbatim spans. Statement lists omit empty statements (fixing stray blank lines), and blank-line logic accounts for semicolons that sit on the next statement’s line.Directives print from source via
printDirective/isDirective, so escaped prologue strings and empty"";stay valid without extra parentheses. Tagged templates again emittypeArguments(e.g.sql<Row>`…`).Extensive tests cover ASI guards, directives, tagged-template types, and empty-statement behavior.
Reviewed by Cursor Bugbot for commit a15a2d9. Bugbot is set up for automated code reviews on this repo. Configure here.