Skip to content

fix(core): parse statements around elements, @case statements, and assigned style spans (#289, #285, #284, #287, #401) - #404

Merged
leonidaz merged 4 commits into
mainfrom
fix/parser-statement-boundaries-289
Sep 25, 2026
Merged

leonidaz merged 4 commits into
mainfrom
fix/parser-statement-boundaries-289

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #289
Closes #285
Closes #284
Closes #287
Closes #401

Summary

Fixes parser bugs around statements that start or end with an element. Valid source now parses, and the formatter's semi: false output parses again.

Input Before Now
const a = <span>x</span> then return <div /> A parse branch shortened the token context stack below its checkpoint parses
const a = <span>x</span> then return <div>{a}</div> Unexpected token parses
const a = <span>x</span> then throw <div />, yield <li />, else <li /> Unexpected token or the checkpoint error parses
const x = a then /* render */ <div /> (the formatter's semi: false output) Unexpected token a declaration, then the element
@case 1: { /a/.test(s); <span /> } Unexpected token parses
@case 1: { `x`; <span /> } Unterminated template parses
@case 1: { const half = total / 2; <span /> } Unexpected token parses
const theme = <style>…</style> then export { theme } declarator and declaration end at offset 30, inside the CSS both end after </style> (60)
semi: false on the scoped-styles fixtures 11 fixtures lose their blank lines on the second pass stable
<div> + <style>…</style> + </div> and a final newline Unterminated JSX contents parses

Changes

  • Return or throw after an element ([Bug]: Parser fails on return or throw of an element after a semicolon-less element with children #289). After a closing tag, parseTemplateBody set exprAllowed = false, but the token after the tag had already been read. The reset applied to the token after that one, so return <div /> read its < as less-than. The line is gone, along with three workarounds in #popTokenContextsAfterTemplateExpressionElement that set exprAllowed = true back after a ;, :, or ,. Every token now sets exprAllowed in its own context update, as in Acorn. This also fixes yield, typeof, else, and case before an element.
  • Comments before an element ([Bug]: A block comment before a template element hides the statement boundary without a semicolon #285). After a statement without a semicolon, a < starts an element only when it's the first token on its line. getTokenFromCode now skips comments when it looks back for the previous character (#previousNonSpaceTabCommentIndex), so /* render */ <div /> on its own line starts an element. As for ASI, a comment that spans lines counts as a line break. A comment on the same line as the previous value leaves a comparison (x = a /* c */ < b) unchanged. The look-back scans the gap forward from lastTokEnd, so comments read exactly as the tokenizer read them (/* a /* b */ is one comment). When lastTokEnd doesn't mark the gap, because a token was re-read after a rewind, it falls back to the old space/tab look-back.
  • Statements in @case bodies ([Bug]: A regex or template literal cannot start a statement in an @case or @default body #284). An @case or @default body now hides the enclosing template from #path while it's read, like an @if body. Before, the template-text rule in getTokenFromCode turned every / in the body into text, which broke regexes and division anywhere in the body, not only at the start of a statement. When a statement's first token is a backtick or (, its context now stays above the statement context, so the rest of the template literal reads as a template and ) pops its own paren. Unbraced case bodies are rejected on main, so only braced ones apply.
  • Assigned <style> spans ([Bug]: An assigned <style> block's declarator ends inside the CSS #287). #parseRawTextElement scans the CSS body itself, and the current token was still the first one after the opening tag when next() recorded it as the last token. Nodes finished after the element (the declarator, the declaration without ;, an object property) ended there. The closing tag now becomes the current token first. The formatter counts blank lines from these spans, so this also fixes the fixtures that changed on every semi: false pass. On main they lose their blank lines on the second pass. When [Bug]: An assigned <style> block's declarator ends inside the CSS #287 was filed they gained one instead.
  • Top-level markup with a raw-text element ([Bug]: core: Top-level markup with a style or script element fails to parse when the file ends with a newline #401). The children context a <style> or <script> opening tag pushes was popped only outside templates. Inside a component, the body's } drops it, but top-level markup has no }, so a final newline read as JSX text that ran into the end of the input. The formatter always writes that newline, so its output for <head><style>…</style></head> didn't parse. Found by the formatter probe below. The fix is four lines in #parseRawTextElement, which [Bug]: An assigned <style> block's declarator ends inside the CSS #287 already changes.

Output differences from Prettier that remain

This PR changes only the parser, so formatter output changes only where parsing changed. Statement boundaries that still fail, all filed as follow-ups:

The CSS inside <style> goes to Prettier's own css parser, which prints [data-d=a\ ] as [data-d="a\"], a string that doesn't close. That's Prettier's bug, not TSRX's, so I didn't file it here.

Verification

  • 12 new tests (7 parser, 5 formatter). 11 fail with main's parser. The other one pins a same-line comment before < staying a comparison.
  • The core parser changed, so after merging main at b9329287 I ran the full set: tsrx-utils, tsrx-react, tsrx-preact, tsrx-solid, tsrx-vue, tsrx-hono, tsrx-analyze, eslint-parser, eslint-plugin, typescript-plugin, language-server, tsrx-mcp, prettier-plugin: 63 files, 5530 pass, 60 skipped. The machine was under heavy load (load average above 100), so I ran them with --testTimeout=60000. With the default 5s limit, a few typescript-plugin, language-server, and tsrx-mcp tests that spawn TypeScript timed out, and all of them passed with the longer limit.
  • tsgo --noEmit passes for packages/tsrx (with its tests) and prettier-plugin, as do Prettier checks of the changed files and all tracked .tsrx files, and pnpm changeset:check.
  • Parse probe. I captured every source the 13 projects above parse during their tests on main (3763 unique), plus the 69 tracked .tsrx files in strict and loose mode (3901 parses). I parsed each with main's parser (at b9329287) and this branch's and compared the result, the loose-mode errors, and every node's start/end. None newly fails or passes, and no error changed. The 282 nodes whose span changed are all declarators, declarations, or object properties whose value is a <style> or <script> element. Each now ends at </style> (or its ;), or, for an unclosed loose-mode style, at the end of the recovered body. None of the 66 sources with @case changed.
  • Formatter probe. I formatted the 3081 non-loose corpus sources with semi: true and semi: false (6162 runs) using main's parser and this branch's. The first-pass output is identical for all 6024 runs that format. 17 runs that weren't idempotent on main (their second pass changed the output or couldn't parse it) now are: 15 assigned <style> blocks with semi: false, and 2 top-level <head><style> files. No run became non-idempotent. Of the tracked .tsrx files formatted with semi: true and semi: false, 12 of 138 runs failed on main (11 not idempotent, and expression-spread-ref-components.tsrx unparsable with semi: false, from [Bug]: Parser fails on return or throw of an element after a semicolon-less element with children #289), and none fail here.

Related findings

Filed separately because they have different causes:

🤖 Generated with Claude Code


Note

Medium Risk
Core parser/tokenizer behavior changes affect all TSRX parsing and formatter idempotency; spans shift for <style>/<script> declarators but probes report no new parse failures.

Overview
Fixes TSRX parser statement boundaries around JSX/elements so valid TypeScript-shaped source and Prettier semi: false output round-trip again.

Tokenizer / ASI: Adds comment-aware lookback (#previousNonSpaceTabCommentIndex) so a < after /* render */ on a new line starts an element, not a comparison. Stops manually forcing exprAllowed after closing tags in #popTokenContextsAfterTemplateExpressionElement and after some closing elements—return/throw/yield/else + JSX after a prior element-with-children now parse.

<style> / <script> raw elements: After scanning the body, the closing tag is set as the current token before next(), so const theme = <style>…</style> declarators and declarations end at </style> (fixes formatter blank-line drift). Pops the children tc_expr context inside templates and handles EOF newline for top-level markup with raw tags.

@switch @case / @default bodies: Clears #path while reading braced arms (like @if) so / is division/regex in JS, not template text; preserves backtick/paren token contexts when parsing setup statements (regex, templates, division).

Parser and Prettier plugin tests cover these cases; changeset bumps @tsrx/core and @tsrx/prettier-plugin patch.

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

@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: Comment lookback misses outer opener
    • The lookback now uses the earliest /* after the previous token that the / closes, so a comment containing / still lets a following < start a tag.

Create PR

Or push these changes by commenting:

@cursor push f44d075285
Preview (f44d075285)
diff --git a/packages/tsrx/src/plugin.js b/packages/tsrx/src/plugin.js
--- a/packages/tsrx/src/plugin.js
+++ b/packages/tsrx/src/plugin.js
@@ -902,10 +902,22 @@
 					this.input.charCodeAt(cursor) === CharCode.slash &&
 					this.input.charCodeAt(cursor - 1) === CharCode.asterisk
 				) {
-					const open = this.input.lastIndexOf('/*', cursor - 3);
-					// Only a comment in the gap before `index` counts: from its start, only
-					// whitespace and comments may lead to `index`. A `*/` that ends a regex
-					// or a string's text fails this check.
+					// Comments do not nest, so this `*/` closes the earliest `/*` in the
+					// gap after the previous token, not the nearest one
+					// (`/* mention /* here */`). `this.end` is still that token's end:
+					// finishToken has not run for the token at `index`. Only a comment in
+					// the gap counts: from its start, only whitespace and comments may
+					// lead to `index`. A `*/` that ends a regex or a string sits inside
+					// the previous token and fails this check.
+					let open = -1;
+					let searchFrom = cursor - 3;
+					while (searchFrom >= this.end) {
+						const found = this.input.lastIndexOf('/*', searchFrom);
+						if (found < this.end) break;
+						if (this.input.indexOf('*/', found + 2) !== cursor - 1) break;
+						open = found;
+						searchFrom = found - 1;
+					}
 					if (open === -1 || skip_space_and_comments_from(this.input, open) !== index) break;
 					for (let i = cursor - 2; i > open + 1; i--) {
 						if (this.#isNewlineCharCode(i)) return i;

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
@@ -648,7 +648,15 @@
 	});
 
 	it('starts an element after comments on the line after a semicolon-less statement', () => {
-		for (const comment of ['/* render */', '/* a */ /* b */', '// note\n  /* render */']) {
+		for (const comment of [
+			'/* render */',
+			'/* a */ /* b */',
+			'// note\n  /* render */',
+			// A `/*` inside the comment is text. The opener is the outer `/*`.
+			'/* mention /* here */',
+			'/** jsdoc mentions /* */',
+			'/* a */ /* mention /* here */',
+		]) {
 			const block = findNode(
 				`export function App() @{\n  const x = a\n  ${comment} <div />\n}`,
 				'JSXCodeBlock',
@@ -666,12 +674,15 @@
 			expect(program.body.map((node) => node.type)).toEqual(['ExpressionStatement', 'JSXElement']);
 		}
 
-		// A comment that spans lines separates the statements like a line break.
-		const block = findNode(
+		// A comment that spans lines separates the statements like a line break,
+		// including when a `/*` in the comment sits after that line break.
+		for (const source of [
 			'export function App() @{\n  const x = a /* a\n  b */ <div />\n}',
-			'JSXCodeBlock',
-		);
-		expect(codeBlockRender(block).type).toBe('JSXElement');
+			'export function App() @{\n  const x = a /* mention\n  still /* here */ <div />\n}',
+		]) {
+			const block = findNode(source, 'JSXCodeBlock');
+			expect(codeBlockRender(block).type).toBe('JSXElement');
+		}
 	});
 
 	it('keeps a `<` after a comment on the same line as the previous value a comparison', () => {
@@ -683,6 +694,25 @@
 		expect(() =>
 			parseModule('export function App() @{\n  const x = a /* note */ <div />\n}', 'App.tsrx'),
 		).toThrow();
+		expect(() =>
+			parseModule('export function App() @{\n  const x = a /* note /* x */ <div />\n}', 'App.tsrx'),
+		).toThrow();
+		// A `/*` inside an earlier string is not the comment opener, so a `<div />`
+		// on the same line as the value is still not an element.
+		expect(() =>
+			parseModule(
+				'export function App() @{\n  const x = "/*" +\n  a /* note /* x */ <div />\n}',
+				'App.tsrx',
+			),
+		).toThrow();
+		const compared = firstStatement(
+			parseModule('x = "/*" +\na /* note /* x */ < b', 'App.tsrx'),
+			'ExpressionStatement',
+		);
+		expect(
+			as_type(as_type(compared.expression, 'AssignmentExpression').right, 'BinaryExpression')
+				.operator,
+		).toBe('<');
 	});
 
 	it('parses mixed scalar and JSX return branches', () => {

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

Reviewed by Cursor Bugbot for commit 32c60da. Configure here.

Comment thread packages/tsrx/src/plugin.js Resolved
leonidaz and others added 3 commits September 24, 2026 21:07
…, and assigned style spans (#289, #285, #284, #287)

- #289: stop forcing `exprAllowed = false` after a closing tag. The token
  after the tag is already read, so the reset applied to the token after
  it and turned the `<` of `return <div />` into a less-than. Remove the
  `;`/`:`/`,` workarounds that compensated for it.
- #285: skip block comments when checking whether a `<` starts its line
  after a statement without a semicolon, so `/* render */ <div />` starts
  an element. A comment that spans lines counts as a line break.
- #284: hide the enclosing template from `#path` while an `@case` or
  `@default` body is read, like an `@if` body, so `/` is a regex or
  division there, and keep a leading backtick's or paren's context on top
  of the statement context.
- #287: make the closing tag of a raw-text element the current token
  before reading the next one, so an assigned `<style>` block's
  declarator and declaration end after `</style>`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ates (#401)

A `<style>` or `<script>` element's closing tag is never tokenized, so the
children context its opening tag pushed was only popped outside templates.
In top-level markup nothing else drops it, and a newline after the last
closing tag was read as JSX text that ran into the end of the input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ious token (#285)

The look-back for the character before a `<` searched backward for the
nearest `/*`, so a comment that contains `/*` (`/* a /* b */`) was cut
short and the `<` after it didn't start a tag. Scan the gap from
`lastTokEnd` forward instead, which reads comments as the tokenizer did,
and fall back to the plain look-back when `lastTokEnd` doesn't mark the
gap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@leonidaz
leonidaz force-pushed the fix/parser-statement-boundaries-289 branch from 32c60da to bcc04f8 Compare September 25, 2026 01:09
@leonidaz
leonidaz merged commit a7246b9 into main Sep 25, 2026
8 checks passed
@leonidaz
leonidaz deleted the fix/parser-statement-boundaries-289 branch September 25, 2026 01:49
leonidaz added a commit that referenced this pull request Sep 25, 2026
Brings in #404 (core parser statement boundaries).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leonidaz added a commit that referenced this pull request Sep 25, 2026
…ixes on main

With #452 (latest ECMAScript version), #404 and #427 (statement boundaries)
on main, 29 cases the parser used to reject now parse and format like
Prettier, and so does a call whose type arguments start on the next line.
The fragment with a comment after `<` now parses but hits #467.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
domgan-oai pushed a commit that referenced this pull request Sep 25, 2026
…ested with Prettier's own tests (#409)

* feat(tsrx-prettier-plugin): add a Prettier plugin built on Prettier's own printer

A new, unpublished package that formats everything except TSRX syntax with
Prettier's `estree` printer (`prettier/plugins/estree`), instead of printing
every node itself like `@tsrx/prettier-plugin`:

- The parser reshapes the acorn-typescript AST into the typescript-estree
  shape Prettier expects, and hands Prettier the comments to attach.
- The printer prints `@{ … }`, `@if`, `@for`, `@switch`, `@try`, `{value}`
  shorthand props, and `<style>`/`<script>` bodies (as CSS/TypeScript), and
  delegates the rest. Directive heads are laid out like their statements.

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

* test(tsrx-prettier-plugin): run Prettier's own JavaScript, JSX, and TypeScript format tests

`scripts/import-prettier-tests.js` imports the cases of Prettier's format
tests (3.9.6) that apply to TSRX: Prettier's `typescript` parser prints the
snapshot's output, and the input is valid TSX in a strict-mode module. The
2044 imported cases run through the plugin: 1807 pass, and 251 known
failures (122 of them rejected by the TSRX parser) run as expected failures
until fixed. Overrides record where TSRX deliberately differs (`<T,>` arrow
type parameters, CommonJS `await(…)`).

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

* fix(tsrx-prettier-plugin): end statements where Prettier's parsers do

Prettier attaches comments using its parsers' `locEnd`, which ends a
statement where its content ends: before a semicolon that comments separate
from it (`__contentEnd`), at the keyword or label of `break`, `continue`, and
`debugger`, at the last declarator, and at the body of `if`, loops, and
labeled statements. Match it, so comments near those statements attach like
Prettier's instead of moving or going unprinted. 39 more Prettier cases pass.

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

* fix(tsrx-prettier-plugin): reshape the AST like Prettier's parser postprocess

Port the steps of Prettier's `parse/postprocess` that the printer relies on:
rebalance same-operator logical expressions (`a || (b || c)`), drop unions
and intersections of one type, join touching JSDoc comments, and make the
program span the whole text. Also rebuild the whitespace between JSX
children, which the TSRX parser leaves out of its text nodes and Prettier
reads to keep blank lines and choose line breaks. 32 more Prettier cases
pass.

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

* fix(tsrx-prettier-plugin): reshape accessors, import options, dotted namespaces, and export import

Match typescript-estree where the acorn-typescript AST differs:
`accessor` fields become `AccessorProperty`, dynamic `import()` options
move from `arguments` to `options`, `namespace A.B {}` is one declaration
named by a qualified name, and `export import a = A` is an export of the
import-equals declaration. The printer also sees the options as its own
`typescript` parser's, since it checks the parser name for TypeScript-only
rules such as keeping the quotes of class property keys. 41 more Prettier
cases pass.

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

* test(tsrx-prettier-plugin): leave out Prettier's sloppy-mode tests

A `.tsrx` file is a strict-mode module, so the importer now also leaves out
Prettier's `js/sloppy-mode` tests and `interface` used as a name, which the
TSRX parser rightly rejects. The rejection messages ("Unexpected token")
don't say strict mode, so the check uses the directory. The known-failures
check also no longer compares against the list while it is being rewritten.

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

* feat(tsrx-prettier-plugin): keep comments between JSX children in place

TSRX reads `//` and `/* */` between JSX children as comments, where TSX reads
text, and Prettier's JSX printer has no place for them. The adapter now
rebuilds each element's text children from the source and turns such a
comment into a `TSRXJSXComment` child. Elements with comment children are
laid out by a copy of Prettier's `printJsxElementInternal`/`printJsxChildren`
(`src/jsx.js`) in which a comment keeps its line: one on its own line stays
there, one after other content stays on that line, a line comment always ends
its line, and JSDoc-style block comments are re-indented. Every other element
is still printed by Prettier.

Comments are also given their source text: the core parser dedents a
multi-line block comment's value for its own printer, which moved the lines
of such comments. All 69 `.tsrx` files in the repository now format stably,
and 9 more Prettier cases pass (one, where TSX reads the text as text, is an
override).

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

* fix(tsrx-prettier-plugin): reshape decorators and heritage names, and reject recovered markup

- Decorators on a constructor parameter property belong to the
  `TSParameterProperty`, as in typescript-estree.
- `export default @d class {}` declares an anonymous class; only a
  parenthesized class stays a `ClassExpression`.
- `extends a.b.C` in `implements`/interface heritage is a member expression,
  not a qualified type name.
- The parser collects errors so that mistakes TypeScript reports only as
  diagnostics (a redeclared variable) still format. But after an unclosed or
  mismatched tag it guesses the markup's structure, and formatting that guess
  garbles the file, so those errors are now thrown like any parse error.

6 more Prettier cases pass. The two layout failures left are parser issues:
#439 (`static` before a line break) and TSRX's line-start tag rule.

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

* fix(tsrx-prettier-plugin): format only code scripts, with this plugin's parser

A `<script>` body is now formatted only when it holds JavaScript or
TypeScript (no `type`, `module`, or a JavaScript/TypeScript type, as in
Prettier's HTML printer). JSON, import maps, and other bodies are kept as
written, instead of being reformatted as code (`[1,2]` became `[1, 2];`,
which isn't JSON; #441 for `@tsrx/prettier-plugin`). Code bodies are
formatted with this plugin's `tsrx` parser instead of Prettier's
`typescript`, so `prettier/standalone` needs no other plugin; a test runs the
plugin there alone.

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

* test(tsrx-prettier-plugin): refresh Prettier's cases for the parser fixes on main

With #452 (latest ECMAScript version), #404 and #427 (statement boundaries)
on main, 29 cases the parser used to reject now parse and format like
Prettier, and so does a call whose type arguments start on the next line.
The fragment with a comment after `<` now parses but hits #467.

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

* test(tsrx-prettier-plugin): refresh Prettier's cases for #471

With #471 on main, the 6 cases behind #416 and #419 parse and format like
Prettier.

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

* feat(tsrx-prettier-plugin): give `@{ … }` values and directives JSX's parentheses

Like `@tsrx/prettier-plugin` on main, and as Prettier lays out a JSX element:
a directive, or a `@{ … }` block used as a value, is wrapped in `(` … `)`
where it is assigned, returned, thrown, or an arrow's body (a `@{ … }` arrow
or function body stays on its line), with its comments inside the
parentheses. While its parent prints, such a value presents itself as a JSX
element, so Prettier's JSX-specific layout applies too, such as keeping a
last-argument arrow on the call's line (`list.map((item) => (` … `))`).

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

* test(tsrx-prettier-plugin): refresh Prettier's cases for #495

With #495 on main, the parser reads JSX spread children, and Prettier's
`jsx/spread/child.js` case formats like Prettier.

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

* test(tsrx-prettier-plugin): skip Prettier's private field destructuring cases

Destructuring private fields (`const { #x: x } = this`) is a TC39 Stage 2
proposal, which TSRX will parse once it becomes part of JavaScript. Its 8
Prettier cases are skipped with that reason instead of listed as known
failures (#424).

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