Repository navigation
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
Conversation
…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
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]>
This was referenced Sep 25, 2026
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 was referenced Sep 25, 2026
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 #416
Closes #419
Summary
Two parser fixes in
@tsrx/core. Both shapes are valid TypeScript, and both used to fail or parse wrong.<div /> > 5;,<div></div> >= 5;,<div /> === b;,<div /> && b;,<div /> / 2;Unexpected token(/ 2:Unterminated regular expression)ExpressionStatement, with the element as the left operand<div /> ? a : "b";,<div />, b;,<div /> as any;Unexpected tokenConditionalExpression,SequenceExpression,TSAsExpression<div /> + 1;,<div /> - 1;+ 1;BinaryExpressionfunction f() {\n <div /> > 5;\n}Unexpected tokenclass G // comment\n<T> implements I<T> {}Unexpected tokeninterface I\n<T> {},type A\n<T> = T;,function f\n<T>() {}Unexpected tokenclass A {\n m\n <T>() {}\n},const o = {\n m\n <T>() {}\n};,const f = function\n<T>() {};Unexpected tokenTypeScript 5.9.3's TSX parser gives the same statement structure for every source above, with no syntax diagnostics.
Changes
parseStatementreturns 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, orsatisfies), the element becomes the left operand and the statement finishes as an ordinaryExpressionStatement. The new#parseElementExpressionStatementdoes whatparseExpressiondoes after its first atom, starting from the element:**(which Acorn reads next to the unary operand), thenparseExprOp, acorn-typescript'sparseConditional, a sequence, andparseExpressionStatementfor 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.<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#readTagStartAsTypeParameterStartturns a tag start into<again and drops thetc_expr/tc_oTagcontexts it pushed. It runs in atsTryParseTypeParametersoverride (classes, class expressions, interfaces, type aliases, functions, function expressions, getters) and in the two places that test for<before calling it:parsePostMemberNameModifiers(class members) andparsePropertyValue(object literal methods).tsParseTypeParametersalready accepted a tag start. OnlytsTryParseTypeParametersand 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:
<div />\n+ 1is still the element, then+ 1, and<div />\n> 5still 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).<div /> <span />on one line is still two elements. Only a<that can't start a tag (<div /> < 5,<div /> <= 5) is a comparison.@{ … }code block's render node, a directive body's render node, an@casebody, and element children are parsed withoutparseStatement, 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> 5is still text. Statements in plain blocks inside a setup statement (@{ if (x) { <div /> > 5 } <span /> }) go throughparseStatementand continue, like any function body..,[,(,?.,!, 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).<div /> = 5and<div /> /= 2still fail withUnexpected token. An element can't be assigned to: Acorn rejects(<div />) = 5as well, and TypeScript reports it from the checker.f\n<T>(x)is stillf, then an element, the rule thatconst a = b\n<div />relies on. TypeScript reads it as a call with type arguments.Verification
{ collect: true, comments: [] }, and compared the statements withts.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/elseand 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/constmodifiers, trailing commas).packages/tsrx/tests/utils/parser.test.js. Two fail withmain's parser. The third pins template and line-break behavior that already worked. The fullvitest runpasses after rebasing onmainat62ed4705: 118 files, 6580 tests, 60 skipped..tsrxfiles, 35 fixture sources undertests/, 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 (collectplus comments), and in loose mode, withmain's parser (at3e09ec26) and with this branch's. Then I compared the full serialized AST (every node'sstart/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, thejsx/jsx/conditional-expression.jsinputs and outputs, andtypescript/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.compileandcompile_to_volar_mappingsgive the same output as for the parenthesized form ((<div />) > 5;) for every target.semi: trueandsemi: false. All 24 outputs parse again, don't change on a second pass, and match Prettier'stypescriptparser byte for byte, including((<div />), b);and(<div />) as any;.pnpm typecheckpasses. In this worktree pnpm didn't link thetsrx-tscbin, so I ranvite-plugin-hono'stypecheck:testsstep throughnode packages/typescript-plugin/dist/tsc.js.pnpm format:checkandpnpm changeset:checkpass.Once this lands, the 6
rejectedByTsrxParserentries the issues list in #409'smanifest.jsonparse. The manifest lives on #409's branch, so this PR doesn't touch it.Needs a decision
<div />\n+ 1is two statements and<div />\n> 5fails. 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 oneExpressionStatementwith the element as the left operand, via#continuesElementExpressionand#parseElementExpressionStatementinparseStatement. 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.#readTagStartAsTypeParameterStartdrops the tag contexts and re-reads<for type parameters, wired throughtsTryParseTypeParameters,parsePostMemberNameModifiers, andparsePropertyValue(e.g.class G\n<T> {},m\n<T>() {}).Adds parser tests,
parse.d.tsentries forparseConditional/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.