Skip to content

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
leonidaz merged 4 commits into
mainfrom
fix/parser-token-context-393
Sep 25, 2026

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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's semi: false output parses again.

Input Before Now
const render = (item) => <><Item /></> then <List renderItem={render} /> (the formatter's semi: false output) Unexpected token a declaration, then the element
const a = <b>x</b> then `t` Unterminated template a tagged template, as after <b />
const half = <span /> / 2 at the top level Unexpected token a division
return <span>x</span> / 2 in a function Unexpected token a division
await <div />, await <></> at the top level Unexpected token an AwaitExpression
@{ total / count > 1 && log(); <span /> } Unterminated regular expression a division
@{ const q = 1; (a) / b; <span /> } Unterminated regular expression a division
const x = y as Foo then <Bar /> (the formatter's semi: false output) Unexpected token a declaration, then the element
let x: Foo then <Bar /> at the top level Unexpected token a declaration, then the element
const a = @{ <b /> } / 2 Unterminated regular expression a division

Changes

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.

  • The token after an element ([Bug]: core: The token after an element's closing tag is misread (attributes, template literal, slash) #393). When an element or fragment closes and no template encloses it, parseTemplateBody now takes it off #path and 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 #functionBodyDepth was 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 in getTokenFromCode read 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 #path while /> reads the next token, for the same reason. parseElement still 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 its tc_oTag and 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). parseElement uses 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 #path without its context being restored.
  • An element after await ([Bug]: core: An element after await is read as a less-than comparison #392). Acorn's name context update allows an expression only after of and yield. An updateContext override now also allows one after await where it is a keyword (this.canAwait: an async function, or the module top level), unless it's a member name (x.await < y still compares).
  • Division in code block setup statements ([Bug]: core: A code block setup statement cannot divide after its first token #394). #parseCodeBlockSetupStatement set exprAllowed = true after the statement's first token was already read, so the / after total read 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) / b popped 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.
  • A code block's render node ([Bug]: core: A / after a @{ … } code block value reads as a regular expression #428). #parseCodeBlockRenderNode reads the render node's < a second time, and the second read pushed another tc_expr/tc_oTag pair on top of the first. After a self-closing element the leftover tc_oTag let the block's } allow an expression, so @{ <b /> } / 2 read 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 compares main's parser with this branch's on elements in expression positions.
  • An element after a type ([Bug]: core: An element after a semicolon-less statement that ends with a type is read as a comparison #398). The token after a type is read while still inside the type, where < is always a type operator. A tsInType override 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. So const x = y as Foo, const x = y satisfies Foo, let x: Foo, and type T = Foo followed by an element on the next line end like const x = y does. 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

This PR changes only the parser, so formatter output changes only where parsing changed.

Verification

  • 12 new tests (7 parser, 5 formatter). 10 fail with 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 with semi: false.
  • The core parser changed, so 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, 5542 pass, 60 skipped (with --testTimeout=60000, since the spawn-heavy typescript-plugin, language-server, and tsrx-mcp tests can time out under load). After the [Bug]: core: A / after a @{ … } code block value reads as a regular expression #428 fix, the whole vitest run (118 files, 6185 tests) passed locally too, and CI covers the rest. main merged at 6c390ca4; pnpm format changes nothing.
  • tsgo --noEmit passes for packages/tsrx (with its tests) and prettier-plugin, as do Prettier checks of the changed files and pnpm changeset:check.
  • Parse probe. The 3763 sources captured from the 13 projects' tests, plus the tracked .tsrx files in strict and loose mode (3901 parses), parsed with main's parser (at a7246b96) and with this branch's. I compared the result, the loose-mode errors, and every node's start/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.
  • Formatter probe. The 3081 non-loose corpus sources formatted with semi: true and semi: false (6162 runs), with main's parser and this branch's. The first-pass output is identical for all 6024 runs that format. 10 semi: false runs whose output didn't parse on the second pass on main now round-trip: elements after as casts, 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 .tsrx files (semi: true and false) are idempotent before and after.

Related findings

🤖 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 Prettier semi: false round-trips work again instead of errors like Unexpected token, Unterminated template, or Unterminated regular expression.

After a closing JSX element (or self-closing tag outside a template), the parser now restores #path and 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 an updateContext override so await allows 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; hasPrecedingLineBreak is 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.

leonidaz and others added 3 commits September 24, 2026 21:50
…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]>
@leonidaz leonidaz changed the title 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) 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) Sep 25, 2026
@leonidaz
leonidaz merged commit cb59a43 into main Sep 25, 2026
8 checks passed
@leonidaz
leonidaz deleted the fix/parser-token-context-393 branch September 25, 2026 02:21
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