Repository navigation
fix(core): read the token after an element, await, a type, and a setup statement's first token in its own context (#393, #392, #394, #398, #428) - #427
Merged
Conversation
…p statement's first token in its own context (#393, #392, #394, #398) - An element that closes outside a template leaves #path and restores the tokenizer context before its closing `>` reads the next token, and a self-closing one stays off #path, so `<b>x</b> / 2` divides at the top level. parseElement keeps the contexts the already-read token pushed (a sibling's `<`, a template literal's backquote) when it drops body residue. - `await` allows an expression after it where it is a keyword, like `yield`. - #parseCodeBlockSetupStatement no longer forces exprAllowed after the first token is read, and puts the statement context under the contexts that token pushed; the next statement's first token keeps its contexts too. - Once the outermost type ends, a `<` that starts a line is read again by the rules for code, so an element there starts a new statement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…their own context (#428) - parseElement's pre-element context depth skips the context the token after `<` pushed (the `{` of `<{tag}>`), so a dynamic element that closes outside a template restores the context before the token after it is read. - #parseCodeBlockRenderNode drops the contexts the render node's `<` pushed when it was first read before reading it again, so the block's `}` isn't read in a leftover tag context (`@{ <b /> } / 2` divides). 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 #393
Closes #392
Closes #394
Closes #398
Closes #428
Summary
Fixes parser bugs where the token after an element, after
await, after a type, or after the first token of a code block statement was read in the wrong tokenizer state. Valid source now parses, and the formatter'ssemi: falseoutput parses again.const render = (item) => <><Item /></>then<List renderItem={render} />(the formatter'ssemi: falseoutput)Unexpected tokenconst a = <b>x</b>then`t`Unterminated template<b />const half = <span /> / 2at the top levelUnexpected tokenreturn <span>x</span> / 2in a functionUnexpected tokenawait <div />,await <></>at the top levelUnexpected tokenAwaitExpression@{ total / count > 1 && log(); <span /> }Unterminated regular expression@{ const q = 1; (a) / b; <span /> }Unterminated regular expressionconst x = y as Foothen<Bar />(the formatter'ssemi: falseoutput)Unexpected tokenlet x: Foothen<Bar />at the top levelUnexpected tokenconst a = @{ <b /> } / 2Unterminated regular expressionChanges
All four had the same shape as #289: state that belongs to one token was set up after the parser had already read the next one.
parseTemplateBodynow takes it off#pathand restores the tokenizer context to the depth before its<before the closing>reads the next token. Before, the next token was read while the element was still on#path, and while#functionBodyDepthwas 0: at the top level, and after any closing tag, because an element's body (its closing tag included) resets that depth. So the template-text rule ingetTokenFromCoderead a/after the element as text, even inside a function (return <span>x</span> / 2). A self-closing element outside a template no longer goes on#pathwhile/>reads the next token, for the same reason.parseElementstill drops the context residue a body leaves (for unclosed elements in loose mode), but it now keeps the contexts the already-read token pushed. Before, it truncated them too, so the<of<List …>lost itstc_oTagand the attributes read as code and text, and a backquote lost its template context. A new helper,#currentTokenContextCount(), says how many contexts the current token pushed (two for a tag start, one for(,{,${,function,class, and an opening backquote).parseElementuses it too when it records the depth to restore: for a dynamic tag (<{tag}>) the token after<is a{that pushed its own context, which used to count as part of the enclosing stack. The first CI run caught this with the Hono playground's dynamic-tag example: the element left#pathwithout its context being restored.await([Bug]: core: An element after await is read as a less-than comparison #392). Acorn'snamecontext update allows an expression only afterofandyield. AnupdateContextoverride now also allows one afterawaitwhere it is a keyword (this.canAwait: an async function, or the module top level), unless it's a member name (x.await < ystill compares).#parseCodeBlockSetupStatementsetexprAllowed = trueafter the statement's first token was already read, so the/aftertotalread as a regex. It's now set only when the first token was read as template text and gets read again. The function also pushed its statement context above the context the first token pushed, so the)of(a) / bpopped the statement context instead of its own paren and allowed a regex. The statement context now goes under that token's contexts. When it restores the context afterwards, it keeps the contexts the next statement's first token pushed, which it used to drop./after a@{ … }code block value reads as a regular expression #428).#parseCodeBlockRenderNodereads the render node's<a second time, and the second read pushed anothertc_expr/tc_oTagpair on top of the first. After a self-closing element the leftovertc_oTaglet the block's}allow an expression, so@{ <b /> } / 2read a regex. The pair from the first read is now dropped before the second. After a setup statement the old context restore used to drop it, which [Bug]: core: A code block setup statement cannot divide after its first token #394's fix no longer does, so this keeps both paths the same. Found by a probe that comparesmain's parser with this branch's on elements in expression positions.<is always a type operator. AtsInTypeoverride now reads a<again by the rules for code once the outermost type has ended, when it starts its own line and can start a tag. Soconst x = y as Foo,const x = y satisfies Foo,let x: Foo, andtype T = Foofollowed by an element on the next line end likeconst x = ydoes. A<that starts a line inside a type stays a type operator (type F =\n <T>(x: T) => T, a call signature after an interface or type literal member), and so does one that can't start a tag (x as number\n< y). A generic arrow (<T,>(a: T) => a) on the next line still reads as one.Differences from TypeScript and Prettier that remain
main, and as Babel reads it. TypeScript ends the statement at the element instead, and treats(,[, and.after an element the same way. That's a separate, older difference, filed as [Bug]: core: A call, index, or template literal after an element continues the element, unlike TypeScript #426, and it may need a decision.await (<div />)asawait <div />. Prettier keeps the parentheses, and adds them for!,typeof,-,as, and spread operands too: [Bug]: prettier-plugin leaves out Prettier's parentheses around an element operand of await, unary operators, casts, and spreads #425. That output used to fail to parse on the second pass, and now it parses.This PR changes only the parser, so formatter output changes only where parsing changed.
Verification
main's parser. The other two pin behavior that already worked: a<inside a type or before a space stays a type operator or a comparison, and a template literal after an element with a semicolon still gets its;guard withsemi: false.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, 5542 pass, 60 skipped (with--testTimeout=60000, since the spawn-heavytypescript-plugin,language-server, andtsrx-mcptests can time out under load). After the [Bug]: core: A/after a@{ … }code block value reads as a regular expression #428 fix, the wholevitest run(118 files, 6185 tests) passed locally too, and CI covers the rest.mainmerged at6c390ca4;pnpm formatchanges nothing.tsgo --noEmitpasses forpackages/tsrx(with its tests) andprettier-plugin, as do Prettier checks of the changed files andpnpm changeset:check..tsrxfiles in strict and loose mode (3901 parses), parsed withmain's parser (ata7246b96) and with this branch's. I compared the result, the loose-mode errors, and every node'sstart/end: none newly fails or passes, no error changed, and no span changed. None of those sources hit these bugs, so the probe checks that nothing else moved.semi: trueandsemi: false(6162 runs), withmain's parser and this branch's. The first-pass output is identical for all 6024 runs that format. 10semi: falseruns whose output didn't parse on the second pass onmainnow round-trip: elements afterascasts, type aliases, and semicolon-less fragments (the [Bug]: core: The token after an element's closing tag is misread (attributes, template literal, slash) #393 and [Bug]: core: An element after a semicolon-less statement that ends with a type is read as a comparison #398 shapes). No run became non-idempotent. All 138 runs over the tracked.tsrxfiles (semi: trueandfalse) are idempotent before and after.Related findings
await, a unary operator, a cast, or a spread (nodeNeedsParenshas only the grammar's cases). Found with [Bug]: core: An element after await is read as a less-than comparison #392./after a@{ … }code block value reads as a regular expression #428: fixed here (see Changes).🤖 Generated with Claude Code
Note
Medium Risk
Changes core parser/tokenizer state across JSX, async, and TypeScript boundaries; behavior is heavily tested but any missed edge case could affect all parses.
Overview
Fixes @tsrx/core parser bugs where the next token was lexed/parsed in the wrong tokenizer state after JSX,
await, TypeScript types, or the first token of a@{ … }setup statement. Valid TS/TSX-shaped source and Prettiersemi: falseround-trips work again instead of errors likeUnexpected token,Unterminated template, orUnterminated regular expression.After a closing JSX element (or self-closing tag outside a template), the parser now restores
#pathand tokenizer context before the closing>reads the following token, tracks per-element restore depth, and uses#currentTokenContextCount()so context resets keep stacks the current token already pushed (tag starts,(,{, etc.). That fixes division after elements (<span /> / 2), sibling elements on the next line after semicolon-less JSX, and tagged templates after elements with children.await <div />is handled via anupdateContextoverride soawaitallows a following expression where it is a keyword. After type annotations (as,satisfies,let x: T,type T = …), a line-leading<that can start a tag is re-tokenized as JSX for a new statement;<inside types stays relational. Code blocks fix setup-statement context (division vs regex,(a) / b) and drop duplicate JSX contexts when re-reading a render node's<.Adds parser and prettier-plugin tests plus a patch changeset;
hasPrecedingLineBreakis declared on the parse types.Reviewed by Cursor Bugbot for commit ae95b02. Bugbot is set up for automated code reviews on this repo. Configure here.