Repository navigation
fix(core): parse statements around elements, @case statements, and assigned style spans (#289, #285, #284, #287, #401) - #404
Merged
Conversation
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: 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.
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.
…, 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
force-pushed
the
fix/parser-statement-boundaries-289
branch
from
September 25, 2026 01:09
32c60da to
bcc04f8
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
This was referenced Sep 25, 2026
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]>
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.


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: falseoutput parses again.const a = <span>x</span>thenreturn <div />A parse branch shortened the token context stack below its checkpointconst a = <span>x</span>thenreturn <div>{a}</div>Unexpected tokenconst a = <span>x</span>thenthrow <div />,yield <li />,else <li />Unexpected tokenor the checkpoint errorconst x = athen/* render */ <div />(the formatter'ssemi: falseoutput)Unexpected token@case 1: { /a/.test(s); <span /> }Unexpected token@case 1: { `x`; <span /> }Unterminated template@case 1: { const half = total / 2; <span /> }Unexpected tokenconst theme = <style>…</style>thenexport { theme }</style>(60)semi: falseon the scoped-styles fixtures<div>+<style>…</style>+</div>and a final newlineUnterminated JSX contentsChanges
parseTemplateBodysetexprAllowed = false, but the token after the tag had already been read. The reset applied to the token after that one, soreturn <div />read its<as less-than. The line is gone, along with three workarounds in#popTokenContextsAfterTemplateExpressionElementthat setexprAllowed = trueback after a;,:, or,. Every token now setsexprAllowedin its own context update, as in Acorn. This also fixesyield,typeof,else, andcasebefore an element.<starts an element only when it's the first token on its line.getTokenFromCodenow 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 fromlastTokEnd, so comments read exactly as the tokenizer read them (/* a /* b */is one comment). WhenlastTokEnddoesn't mark the gap, because a token was re-read after a rewind, it falls back to the old space/tab look-back.@casebodies ([Bug]: A regex or template literal cannot start a statement in an @case or @default body #284). An@caseor@defaultbody now hides the enclosing template from#pathwhile it's read, like an@ifbody. Before, the template-text rule ingetTokenFromCodeturned 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 onmain, so only braced ones apply.<style>spans ([Bug]: An assigned <style> block's declarator ends inside the CSS #287).#parseRawTextElementscans the CSS body itself, and the current token was still the first one after the opening tag whennext()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 everysemi: falsepass. Onmainthey 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.<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:
const render = () => <><Item /></>then<List a={1} />). The formatter prints this shape withsemi: false: [Bug]: core: The token after an element's closing tag is misread (attributes, template literal, slash) #393.as Foo,satisfies Foo,let x: Foo), an element on the next line fails, and the formatter prints that shape withsemi: false: [Bug]: core: An element after a semicolon-less statement that ends with a type is read as a comparison #398.The CSS inside
<style>goes to Prettier's owncssparser, 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
main's parser. The other one pins a same-line comment before<staying a comparison.mainatb9329287I 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 fewtypescript-plugin,language-server, andtsrx-mcptests that spawn TypeScript timed out, and all of them passed with the longer limit.tsgo --noEmitpasses forpackages/tsrx(with its tests) andprettier-plugin, as do Prettier checks of the changed files and all tracked.tsrxfiles, andpnpm changeset:check.main(3763 unique), plus the 69 tracked.tsrxfiles in strict and loose mode (3901 parses). I parsed each withmain's parser (atb9329287) and this branch's and compared the result, the loose-mode errors, and every node'sstart/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@casechanged.semi: trueandsemi: false(6162 runs) usingmain's parser and this branch's. The first-pass output is identical for all 6024 runs that format. 17 runs that weren't idempotent onmain(their second pass changed the output or couldn't parse it) now are: 15 assigned<style>blocks withsemi: false, and 2 top-level<head><style>files. No run became non-idempotent. Of the tracked.tsrxfiles formatted withsemi: trueandsemi: false, 12 of 138 runs failed onmain(11 not idempotent, andexpression-spread-ref-components.tsrxunparsable withsemi: 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:
awaitreads as less-than, because Acorn'snamecontext update disallows an expression afterawait.semi: falseformatter output), a template literal on the next line, and a/at module scope.parseElementtruncates the context stack after the next token has pushed its contexts.@{ }or directive body, a setup statement liketotal / count > 1 && log()reads/as a regex, because#parseCodeBlockSetupStatementsetsexprAllowed = trueafter the first token is read. This has the same shape as [Bug]: Parser fails on return or throw of an element after a semicolon-less element with children #289, but in a function this PR doesn't touch.semi: falseformatter output).<script>body that doesn't parse on every pass.🤖 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: falseoutput 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 forcingexprAllowedafter closing tags in#popTokenContextsAfterTemplateExpressionElementand 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 beforenext(), soconst theme = <style>…</style>declarators and declarations end at</style>(fixes formatter blank-line drift). Pops the childrentc_exprcontext inside templates and handles EOF newline for top-level markup with raw tags.@switch@case/@defaultbodies: Clears#pathwhile 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/coreand@tsrx/prettier-pluginpatch.Reviewed by Cursor Bugbot for commit e5d02db. Bugbot is set up for automated code reviews on this repo. Configure here.