Skip to content

fix(core): continue an expression after an element that starts a statement, and read type parameters on the line after a declaration name (#416, #419) - #471

Merged
leonidaz merged 1 commit into
mainfrom
fix/parser-element-operators-416
Sep 25, 2026

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #416
Closes #419

Summary

Two parser fixes in @tsrx/core. Both shapes are valid TypeScript, and both used to fail or parse wrong.

Input Before Now
<div /> > 5;, <div></div> >= 5;, <div /> === b;, <div /> && b;, <div /> / 2; Unexpected token (/ 2: Unterminated regular expression) one ExpressionStatement, with the element as the left operand
<div /> ? a : "b";, <div />, b;, <div /> as any; Unexpected token ConditionalExpression, SequenceExpression, TSAsExpression
<div /> + 1;, <div /> - 1; the element, then a separate statement + 1; one BinaryExpression
function f() {\n <div /> > 5;\n} Unexpected token as at the top level
class G // comment\n<T> implements I<T> {} Unexpected token a class with type parameters
interface I\n<T> {}, type A\n<T> = T;, function f\n<T>() {} Unexpected token declarations with type parameters
class A {\n m\n <T>() {}\n}, const o = {\n m\n <T>() {}\n};, const f = function\n<T>() {}; Unexpected token methods and a function expression with type parameters

TypeScript 5.9.3's TSX parser gives the same statement structure for every source above, with no syntax diagnostics.

Changes

  • An operator after an element that starts a statement ([Bug]: tsrx-core: Parser rejects or splits off an operator after an element that starts a statement #416). parseStatement returns an element that starts a statement as the statement itself, and nothing continued the expression after it. Now, when the next token is on the element's line and continues an expression (a binary, logical, or relational operator, **, ?, ,, as, or satisfies), the element becomes the left operand and the statement finishes as an ordinary ExpressionStatement. The new #parseElementExpressionStatement does what parseExpression does after its first atom, starting from the element: ** (which Acorn reads next to the unary operand), then parseExprOp, acorn-typescript's parseConditional, a sequence, and parseExpressionStatement for the semicolon. The tokenizer already read these tokens as operators, so no tokenizer state changes. The AST is the one (<div />) > 5; already gave, without the parentheses.
  • Type parameters on the line after a declaration name ([Bug]: tsrx-core: Parser rejects type parameters that start on the line after a declaration name #419). A < that starts a line reads as a tag start, so that an element there can start a new statement. After the name of a class, interface, type alias, function, or method, only type parameters can follow. A new #readTagStartAsTypeParameterStart turns a tag start into < again and drops the tc_expr/tc_oTag contexts it pushed. It runs in a tsTryParseTypeParameters override (classes, class expressions, interfaces, type aliases, functions, function expressions, getters) and in the two places that test for < before calling it: parsePostMemberNameModifiers (class members) and parsePropertyValue (object literal methods). tsParseTypeParameters already accepted a tag start. Only tsTryParseTypeParameters and those two checks didn't.

Boundaries kept

TSRX reads an element at the start of a line or statement as the start of a new statement or template output. This PR keeps that rule everywhere except in the positions above:

  • Same line only. An operator on the next line doesn't continue the element: <div />\n+ 1 is still the element, then + 1, and <div />\n> 5 still fails. TypeScript continues both. The issue leaves this to TSRX's statement-boundary rules, and I didn't change it. It needs a language decision (see below).
  • A tag start is the next element. <div /> <span /> on one line is still two elements. Only a < that can't start a tag (<div /> < 5, <div /> <= 5) is a comparison.
  • Templates don't change. A @{ … } code block's render node, a directive body's render node, an @case body, and element children are parsed without parseStatement, so they don't change: @{ <div /> > 5 } still fails, @{\n const a = 1\n <div /> + 1\n} still reports "statements cannot follow the rendered output" (with the same loose-mode AST), and in <div><span /> > 5</div> the > 5 is still text. Statements in plain blocks inside a setup statement (@{ if (x) { <div /> > 5 } <span /> }) go through parseStatement and continue, like any function body.
  • Subscripts don't change. ., [, (, ?., !, and ++ after an element that starts a statement are unchanged. TypeScript also ends the expression at the element there (the expression-position difference is [Bug]: core: A call, index, or template literal after an element continues the element, unlike TypeScript #426).
  • Assignment stays rejected. <div /> = 5 and <div /> /= 2 still fail with Unexpected token. An element can't be assigned to: Acorn rejects (<div />) = 5 as well, and TypeScript reports it from the checker.
  • A call on the next line doesn't change ([Bug]: tsrx-core: Parser rejects type parameters that start on the line after a declaration name #419). The re-read happens only where type parameters are the only thing that can follow. f\n<T>(x) is still f, then an element, the rule that const a = b\n<div /> relies on. TypeScript reads it as a call with type arguments.

Verification

  • Issue repros. I ran every source in both issues with and without { collect: true, comments: [] }, and compared the statements with ts.createSourceFile('x.tsx', …, ScriptKind.TSX). All parse with the same structure as TypeScript's. I also compared 115 more sources with TypeScript: every binary operator, ** with its precedence (<div /> ** 2 ** 3 > 1), fragments in function bodies followed by regexes, objects, and templates, if/else and labeled bodies, the @{ … } template cases above, and [Bug]: tsrx-core: Parser rejects type parameters that start on the line after a declaration name #419's forms (exported, abstract, declare, generator and async functions, export default function, static, private, computed, string-named, async, generator, and optional class methods, object literal methods and getters, a comment between name and <, in/out/const modifiers, trailing commas).
  • Tests. 3 new parser tests in packages/tsrx/tests/utils/parser.test.js. Two fail with main's parser. The third pins template and line-break behavior that already worked. The full vitest run passes after rebasing on main at 62ed4705: 118 files, 6580 tests, 60 skipped.
  • AST probe. The corpus has 8774 unique sources: the 69 tracked .tsrx files, 35 fixture sources under tests/, 6398 code-like string literals from the test files, and the 2040 inputs and 2040 outputs of the Prettier format snapshots on feat: add tsrx-prettier-plugin, built on Prettier's own printer and tested with Prettier's own tests #409's branch. I parsed each one in strict mode, with the formatter's options (collect plus comments), and in loose mode, with main's parser (at 3e09ec26) and with this branch's. Then I compared the full serialized AST (every node's start/end/loc), the comments, and the loose-mode errors. 93 of the 26322 parses differ, and 92 of them are fixed cases: the new tests' sources, jsx/binary-expressions/relational-operators.js, the jsx/jsx/conditional-expression.js inputs and outputs, and typescript/class-comment/generic.ts. The one other difference is <div /> <, an incomplete line from a language-server completion test that only runs a regex on it. It fails on both parsers, but the error moved from 1:8 to 1:9, because the < is now an operator after the element and its right operand is missing.
  • Compile output. The compile tests for React, Preact, Solid, Vue, and Hono pass unchanged. For the fixed shapes, compile and compile_to_volar_mappings give the same output as for the parenthesized form ((<div />) > 5;) for every target.
  • Formatter. I formatted the 12 repro shapes with semi: true and semi: false. All 24 outputs parse again, don't change on a second pass, and match Prettier's typescript parser byte for byte, including ((<div />), b); and (<div />) as any;.
  • pnpm typecheck passes. In this worktree pnpm didn't link the tsrx-tsc bin, so I ran vite-plugin-hono's typecheck:tests step through node packages/typescript-plugin/dist/tsc.js. pnpm format:check and pnpm changeset:check pass.

Once this lands, the 6 rejectedByTsrxParser entries the issues list in #409's manifest.json parse. The manifest lives on #409's branch, so this PR doesn't touch it.

Needs a decision

  • Should an operator on the next line continue an element that starts a statement? TypeScript and Babel say yes for all of them. In TSRX today, <div />\n+ 1 is two statements and <div />\n> 5 fails. For operators that can't start a statement (>, ?, &&, ===, ,), continuing wouldn't be ambiguous. For +, -, /, (, [, and template literals it would change what parses today. This PR leaves both as they are.

🤖 Generated with Claude Code


Note

Medium Risk
Changes core parser disambiguation for JSX vs operators and generics; behavior is bounded by same-line rules and existing template boundaries, with broad test coverage.

Overview
Aligns the TSRX parser with TypeScript for two JSX/TSX edge cases that previously errored or split statements incorrectly.

When a JSX element or fragment starts a statement, a same-line operator (>, +, ?, as, etc.) now continues one ExpressionStatement with the element as the left operand, via #continuesElementExpression and #parseElementExpressionStatement in parseStatement. Line breaks, adjacent tags, @{ … } render nodes, and template children still end the element as before.

When < begins a new line after a declaration or member name, the tokenizer had treated it as JSX. #readTagStartAsTypeParameterStart drops the tag contexts and re-reads < for type parameters, wired through tsTryParseTypeParameters, parsePostMemberNameModifiers, and parsePropertyValue (e.g. class G\n<T> {}, m\n<T>() {}).

Adds parser tests, parse.d.ts entries for parseConditional / buildBinary, and a patch changeset for @tsrx/core.

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

…ement, and read type parameters on the line after a declaration name (#416, #419)

- An element or fragment that starts a statement becomes the left operand
  when the token after it, on the same line, continues an expression: a
  binary, logical, or relational operator, `**`, `?`, `,`, `as`, or
  `satisfies` (`<div /> > 5;`, `<div /> + 1;`). The statement is then an
  ordinary ExpressionStatement, as in TSX. On the next line, and for a code
  block's render node or template children, the element still ends where it
  closes.
- A `<` that starts its own line reads as a tag start. Where only type
  parameters can follow (after the name of a class, interface, type alias,
  function, class member, or object method), the tag start is read again as
  `<` without the tag contexts it pushed, so `class G // comment\n<T> {}`
  parses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@leonidaz
leonidaz merged commit 3b3e128 into main Sep 25, 2026
8 checks passed
@leonidaz
leonidaz deleted the fix/parser-element-operators-416 branch September 25, 2026 03:53
leonidaz added a commit that referenced this pull request Sep 25, 2026
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]>
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

Labels

None yet

Projects

None yet

1 participant