Skip to content

feat: add tsrx-prettier-plugin, built on Prettier's own printer and tested with Prettier's own tests - #409

Merged
domgan-oai merged 18 commits into
mainfrom
feat/tsrx-prettier-plugin
Sep 25, 2026
Merged

domgan-oai merged 18 commits into
mainfrom
feat/tsrx-prettier-plugin

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds packages/tsrx-prettier-plugin (package name tsrx-prettier-plugin, private, not published): a Prettier plugin that formats everything except TSRX syntax with Prettier's own JavaScript/TypeScript printer, instead of printing every node itself like @tsrx/prettier-plugin. It is tested with Prettier's own format tests. @tsrx/prettier-plugin is unchanged.

Of the 2040 Prettier test cases that apply to TSRX, 1954 pass; 74 more are inputs the TSRX parser rejects, and 8 use a Stage 2 proposal and are skipped (tracked in the parser issues below). For comparison, the same kind of run against @tsrx/prettier-plugin on main passed 297 of 787 of the typescript/jsx cases, and 92 of 219 Prettier-formatted TS/JS files came out unchanged (217 with this plugin).

How it works

  • src/parse.js parses with @tsrx/core (collect: true), then reshapes the acorn-typescript AST into the typescript-estree shape Prettier's printer expects. That covers renames such as superTypeParameters → superTypeArguments, accessor fields → AccessorProperty, dotted namespaces → TSQualifiedName, and import() options. It also ports the steps of Prettier's parser postprocess the printer relies on: __contentEnd, locEnd, logical-expression rebalancing, merging touching JSDoc comments, and dropping single-type unions. Comments go to Prettier as a flat list, and Prettier attaches them itself.
  • src/printer.js is prettier/plugins/estree's printer, with TSRX syntax printed by the plugin: @{ … }, @if/@else, @for (index, key, @empty), @switch/@case, @try/@pending/@catch (e, reset), {value} shorthand props, and <style>/<script> bodies. <style> bodies are formatted as CSS. A <script> body is formatted with this plugin's own parser when it holds JavaScript or TypeScript (no type, module, or a JavaScript/TypeScript type); anything else, such as JSON or an import map, is kept as written ([Bug]: @tsrx/prettier-plugin: Formatter formats JSON script bodies as TypeScript and makes them invalid JSON #441 is the same problem in @tsrx/prettier-plugin).
    • @{ … } is printed as a block statement with an @, and @case bodies as blocks, so blank lines and comments follow Prettier's rules.
    • Directives are presented to Prettier as do { … } expressions, the closest JavaScript relative, so its layout rules apply to them (an arrow body stays on the => line, and so on).
    • A directive's head is printed while the node presents itself as its statement (IfStatement, ForOfStatement), so @if (…) breaks like if (…), and @for (const x of …) has no ;.
  • src/jsx.js handles comments between JSX children (// … and /* … */), which are comments in TSRX and text in TSX. The adapter turns each one into a TSRXJSXComment child. Only elements with such children are laid out by this copy of Prettier's printJsxElementInternal/printJsxChildren, in which a comment keeps its line. Every other element is printed by Prettier itself.
  • Comments are given their source text: @tsrx/core dedents a multi-line block comment's value for its own printer.
  • The parser runs with collect: true, so mistakes TypeScript reports only as diagnostics (a redeclared variable) still format. After an unclosed or mismatched tag, the parser guesses the markup's structure, and formatting that guess would garble the file, so those errors are thrown like any parse error.
  • The printer sees the options as Prettier's typescript parser's (parser: "typescript"), because it checks the parser name for TypeScript-only rules such as keeping quoted class property keys.

Prettier's tests

scripts/import-prettier-tests.js imports Prettier 3.9.6's tests/format/{js,jsx,typescript} snapshots into tests/prettier/<dir>.snap, unchanged except that non-applicable cases are dropped. A case is imported when:

  • Prettier's typescript parser prints exactly the snapshot's output, so the expected output is what Prettier prints for TypeScript, and
  • the input is TSRX: valid TSX (checked with Prettier's typescript parser on a .tsx path) in a strict-mode module.

tests/prettier/manifest.json records the version, what was left out and why, and the imported cases the TSRX parser rejects:

cases
imported 2040
left out: error tests, or entries that record another parser's error 2849
left out: cursor, range, or end-of-line tests 50
left out: formatted differently by, or rejected by, the typescript parser 116
left out: not valid TSX (27), not valid in a strict-mode module (29, including Prettier's js/sloppy-mode tests), namespaced tags (3) 59

tests/prettier.test.js runs every imported case:

  • tests/prettier-known-failures.json lists the 76 cases that don't pass yet. They run as test.fails, so a listed case that starts passing fails the run and the list only shrinks. Refresh it with UPDATE_KNOWN_FAILURES=1 pnpm test --project tsrx-prettier-plugin.
  • tests/prettier-overrides.js records where TSRX deliberately differs, with the reason. For example, <T,> for a lone arrow type parameter, which Prettier prints everywhere but in .ts files.
  • A test checks that every override and known failure still names an imported case.

After upgrading Prettier, run pnpm --filter tsrx-prettier-plugin import-prettier-tests and refresh the known failures.

tests/tsrx.test.js covers the TSRX syntax, including comments between JSX children (26 tests, one of them in prettier/standalone; the formatting ones also check that a second format changes nothing).

Known failures (76)

Not done yet

  • More TSRX-specific tests, written from the language rules and Prettier's behavior. @tsrx/prettier-plugin's tests are deliberately not used: they are still being changed, so they aren't a reliable expected output, and this package stays independent of them.
  • Wiring it into the playground. It works in prettier/standalone with no other plugin loaded, and a test covers that.

Parser issues

Every input the TSRX parser rejects is covered by a tsrx issue. Each issue has a repro at 24df8571 and its cause. Where the cause is in acorn or @sveltejs/acorn-typescript (1.0.13 on acorn 8.17.0), the upstream item is linked. This table gets kept up to date as the upstream items move.

tsrx Cause Cases Upstream
#414 Fixed by #452: @tsrx/core parsed with ecmaVersion: 13 (ES2022), rejecting using/await using, hashbangs, regex v flag and modifiers 0 (was 28) acorn 8.17 already supports all of it (acornjs/acorn#1366, #1367, #1323); with 'latest', all 28 parse and every other imported case and repository .tsrx file parses to the same AST
#415 Parser throws on mistakes that TypeScript reports only as type-check diagnostics (redeclared types, abstract members outside an abstract class, ambient initializers, duplicate attribute keys, …), even with collect: true 59, and 6 error-recovery inputs noted in the issue sveltejs/acorn-typescript#89
#416 Fixed by #471: an operator after an element that starts a statement (<div /> > 5); <div /> + 1 was split into two statements 0 (was 5) none (TSRX)
#417 JSX spread children (<div>{...children}</div>): a TSRX override drops acorn-typescript's branch 1 none needed: upstream parses it (sveltejs/acorn-typescript#78, closed)
#418 Fixed on main (#404/#427): < b /> or < > at the start of a statement after an element with a closing tag 0 (was 1; that case now hits #467) none (TSRX)
#419 Fixed by #471: type parameters that start on the line after a declaration name 0 (was 1) none (TSRX)
#420 A generic call signature as an interface's first member 2 acorn-typescript tsParseInterfaceBody; no upstream issue yet
#421 Classes named after TypeScript contextual keywords (class global {}) 2 acorn-typescript tokenizer; no upstream issue yet
#422 Import attributes in import types (import("foo", { with: … })) 3 acorn-typescript tsParseImportType; no upstream issue yet
#423 assert (…) on the line after an import read as import assertions 1 acorn-typescript parseMaybeImportAttributes; no upstream issue yet
#424 Closed as not planned: destructuring private fields (const { #x: x } = this) is a Stage 2 proposal. Its cases are skipped in tests/prettier-overrides.js until it becomes JavaScript 0 (8 skipped) none: acorn has no production for it
#289 Fixed by #404: yield <div>…</div> on the line after a semicolon-less element 0 (was 1) none (TSRX)
#439 static before a line break is read as a field name, so static members become instance members (parsed, not rejected) 1 acorn-typescript tsTokenCanFollowModifier; no upstream issue yet
#467 An element or fragment with whitespace or a comment after < starts inside the gap (wrong location, not rejected) 1 none (TSRX)

Other upstream items that affect this plugin:

Upstream Status tsrx Effect here
sveltejs/acorn-typescript#114: export import A = B isn't wrapped in an ExportNamedDeclaration open — 4 imported cases pass because the adapter wraps it (src/parse.js, TSImportEqualsDeclaration); drop the workaround once released
sveltejs/acorn-typescript#112, fix in #113: anonymous export default class with implements or abstract open #194 none imported
sveltejs/acorn-typescript#116: compare quoted import attribute keys by value open #342 none: the 2 Duplicated key in attributes cases are real duplicates, rejected per spec (#415)
sveltejs/acorn-typescript#111: constrained or defaulted single type parameters on generic arrows in JSX open #169 none rejected: the 13 imported cases with such arrows parse through tsrx's own lookahead

Related

Validation

  • pnpm test --project tsrx-prettier-plugin: 1982 passed, 76 expected failures, 10 skipped
  • All 69 .tsrx files in the repository format, and format the same on a second pass
  • pnpm test --project prettier-plugin: 961 passed (unchanged)
  • tsgo --noEmit -p packages/tsrx-prettier-plugin/tsconfig.typecheck.json (added to pnpm typecheck)
  • prettier --check on the changed files

No changeset: the package is private and not published.

🤖 Generated with Claude Code

leonidaz and others added 5 commits September 24, 2026 20:57
… 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]>
…ypeScript 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]>
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]>
…tprocess

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]>
…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]>
@cursor

cursor Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

This PR is too large for Bugbot to review. It changes 116,481 lines and 3,005,939 characters. Split the change into smaller pull requests to get a review.

leonidaz and others added 2 commits September 24, 2026 21:39
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]>
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]>
… 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]>
…'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]>
…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]>
leonidaz and others added 2 commits September 24, 2026 23:54
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]>
leonidaz and others added 4 commits September 25, 2026 01:26
… 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]>
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]>
…ng 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants