Repository navigation
fix(core): parse anonymous and decorated default-exported classes as declarations, and decorators on a rest parameter (#194, #533, #564) - #614
Merged
Conversation
…declarations, and decorators on a rest parameter (#194, #533, #564) Four parser bugs caused upstream in @sveltejs/acorn-typescript 1.0.13, each worked around by overriding the responsible method in TSRXPlugin, marked `UPSTREAM(sveltejs/acorn-typescript#<n>)`, with the AST of the upstream fix: - #194: `parseClassId` skips `implements` wherever the class name is optional, with `id: null`, and `parseExportDefaultDeclaration` parses `export default abstract class` with an optional name. Upstream: sveltejs/acorn-typescript#113 (also #110 for the abstract part). - #533: `parseExportDefaultDeclaration` reads the decorators after `export default` and parses `class` or `abstract class` as a declaration, so `export default @dec class B {}` is a ClassDeclaration that binds `B` and `export default @dec abstract class {}` parses. Node ranges don't change. Upstream: sveltejs/acorn-typescript#124. - #533 (last row): `parseDecorators` checks that decorators written before `export` are followed by an exported class, and reports them otherwise with the existing "Leading decorators must be attached to a class declaration." error, instead of dropping them or moving them onto a class expression. Upstream: sveltejs/acorn-typescript#125. - #564: `parseAssignableListItem` reads the decorators before `...` and hangs them off the RestElement, as typescript-estree does. Like any parameter decorator this is not an error: TypeScript's checker decides (TS1206 unless experimentalDecorators). Upstream: sveltejs/acorn-typescript#126. tsrx-prettier-plugin no longer retypes a decorated default-exported class expression as a declaration, which the parser now produces. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Leading decorators slip past TSRX exports
parseDecoratorsnow rejects@if,@{,@for,@switch, and@tryafter a leading decorator'sexport, so those expressions no longer leave the decorator on the stack for a later class.
Or push these changes by commenting:
@cursor push c68456c9ab
Preview (c68456c9ab)
diff --git a/.changeset/parser-default-class-decorators.md b/.changeset/parser-default-class-decorators.md
--- a/.changeset/parser-default-class-decorators.md
+++ b/.changeset/parser-default-class-decorators.md
@@ -19,8 +19,9 @@
failing with `Unexpected token`.
- Decorators written before `export` must be followed by an exported class,
as TypeScript requires. Before anything else (`@dec export function f() {}`,
- `@dec export const A = class {}`, `@dec export default (class {})`) they used
- to be dropped or moved onto a class expression inside; they are now an error,
+ `@dec export const A = class {}`, `@dec export default (class {})`,
+ `@dec export default @if (a) { … }`) they used to be dropped or moved onto a
+ class expression inside or a following class; they are now an error,
`Leading decorators must be attached to a class declaration.`, as they already
were before a statement that isn't a class.
- A rest parameter can have decorators (`m(@dec ...rest: T[]) {}`), like any
diff --git a/packages/tsrx/src/plugin.js b/packages/tsrx/src/plugin.js
--- a/packages/tsrx/src/plugin.js
+++ b/packages/tsrx/src/plugin.js
@@ -3763,6 +3763,11 @@
* With no class, as in `@dec export function f() {}`, they were dropped.
* Report them at the exported declaration with acorn-typescript's error
* for leading decorators before something else (TypeScript's TS1206).
+ * An `@` that opens `@if`, `@{`, `@for`, `@switch`, or `@try` is an
+ * expression, not a decorator. `parseExportDefaultDeclaration` parses
+ * those without calling `parseDecorators`, so reject them here;
+ * otherwise the leading decorators stay on the stack and a later class
+ * takes them.
* @type {Parse.Parser['parseDecorators']}
*/
parseDecorators(allowExport) {
@@ -3773,8 +3778,16 @@
const is_default = next.type === tt._default;
if (is_default) next = this.lookahead(++ahead);
const declaration_start = next.start;
- // Decorators after `export` as well are checked when they are read.
- if (next.type === tstt.at) return;
+ // A later decorator is checked when it is read. An at-sign construct
+ // (`@if`, `@{`, `@for`, `@switch`, `@try`) is an expression, so that
+ // check never runs.
+ if (
+ next.type === tstt.at &&
+ !this.#isCodeBlockStart(next.start) &&
+ !this.#isJSXControlFlowDirectiveAt(next.start)
+ ) {
+ return;
+ }
if (!is_default && next.type === tstt.declare && !next.containsEsc) {
next = this.lookahead(++ahead);
}
diff --git a/packages/tsrx/tests/utils/upstream-parser-workarounds.test.js b/packages/tsrx/tests/utils/upstream-parser-workarounds.test.js
--- a/packages/tsrx/tests/utils/upstream-parser-workarounds.test.js
+++ b/packages/tsrx/tests/utils/upstream-parser-workarounds.test.js
@@ -590,6 +590,14 @@
['@dec export interface I {}', 'interface'],
['@dec export { a };', '{ a }'],
['@dec export default abstract;', 'abstract'],
+ ['@dec export default @if (a) { <div /> }', '@if'],
+ ['@dec export default @{ <div /> }', '@{'],
+ ['@dec export default @for (const x of y) { <div /> }', '@for'],
+ ['@dec export default @for await (const x of y) { <div /> }', '@for'],
+ ['@dec export default @switch (a) { @case 1: { <div /> } }', '@switch'],
+ ['@dec export default @try { <div /> } @catch (e) { <span /> }', '@try'],
+ ['@dec export @if (a) { <div /> }', '@if'],
+ ['@a @b export default @if (a) { <b /> }', '@if'],
]);
const outcomes = await parseBothModes(cases.map(([source]) => source));
for (const [index, [source, declaration]] of cases.entries()) {You can send follow-ups to the cloud agent here.
…ecorator (#533) The check for decorators written before `export` deferred to the later decorator check when `@` followed `export` or `export default`. An at-sign construct there (`@if (a) { … }`, `@{ … }`) is an expression, not a decorator, so nothing checked the leading decorators, and the next class took them: `@dec export default @if (a) { … }` followed by `class A {}` decorated `A`. Report them at the construct instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves a conflict in upstream-parser-workarounds.test.js, where main (#602) and this branch both added tests after the sveltejs/acorn-typescript#121 block: both sets are kept, and the import takes main's parse_in_worker. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the conflicts with #618 in plugin.js, keeping both sides: the OPTIONAL_BINDING_PATTERN_PARAMETER constant next to UNEXPECTED_LEADING_DECORATOR, and #618's parseBindingListItem after this branch's parseExportDefaultDeclaration, parseDecorators and parseAssignableListItem, which both sides added at the same place. parseAssignableListItem now uses #618's #bindingListClose to leave a decorated `...` in an array pattern an error, as on main, instead of accepting it like the other decorated array elements (#609). Tests cover errors inside a decorated rest parameter, which keep their message and position, and a decorated optional pattern parameter in an overload. Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 tasks done
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix is ON. A cloud agent has been kicked off to fix the reported issue. You can view the agent here.
Reviewed by Cursor Bugbot for commit c4235bf. Configure here.
This was referenced Sep 25, 2026
Closed
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.


Fixes three parser bugs around default-exported classes and decorators that come from
@sveltejs/acorn-typescript1.0.13. Each is worked around by overriding the responsible acorn-typescript method inTSRXPlugin(packages/tsrx/src/plugin.js), marked// UPSTREAM(sveltejs/acorn-typescript#<n>): remove once a release includes the fix, with the AST of the upstream fix where one exists.The bugs
export default class implementsandexport default abstract class#194.export default class implements I {}failed withThe keyword 'implements' is reserved, andexport default abstract class {}(also withimplements,extendsor type parameters) withUnexpected token. acorn-typescript skipsimplementsinparseClassIdonly whenisStatementis falsy, butexport default classpasses'nullableID'. Itsexport default abstract classpath passestrue, which requires a name.export default @dec class B {}parsed as aClassExpression, soBwasn't a module binding and the class didn't end the statement, andexport default @dec abstract class {}failed. acorn-typescript'sparseExportDefaultDeclarationleaves@to acorn, which parses an expression. The issue's last row,@dec export default (class {});, hung the decorators on the parenthesized class expression. The cause there is different: decorators written beforeexportwere never checked against what follows, so the next class parsed took them, and with no class they were dropped (@dec export function f() {}compiled to a function without them).m(@a ...rest: unknown[]) {}failed withUnexpected token. acorn'sparseBindingListchecks for...beforeparseAssignableListItem, where acorn-typescript reads a parameter's decorators.Overrides
plugin.jsparseClassId(extended)isStatement !== true),implementsstarts the heritage clause andidisnull. The #421 part (contextual keywords as names, sveltejs/acorn-typescript#110) is unchanged. A class statement still rejectsimplementsas a name.parseExportDefaultDeclaration(new)abstract(also in #110); sveltejs/acorn-typescript#124 (filed) for decorators@(not TSRX's@{,@if,@for,@switch,@try, which stay expressions) andabstract class; everything else goes tosuper. After@it calls acorn-typescript's ownparseDecorators(), which already rejects anything but a class, thenparseClass(node, 'nullableID'), as acorn does forclass.parseDecorators(new)super, and only whenexportfollows the decorators looks at the declaration afterexport/export default:class,abstract class,declare [abstract] class(not afterdefault), or more decorators (checked when they're read, as today; TSRX's@if,@{and the other at-sign constructs aren't decorators). Anything else raises acorn-typescript's existingLeading decorators must be attached to a class declaration.at the declaration.parseAssignableListItem(new)@. The decorators are read first; before...they go on theRestElement(except in an array pattern, where TypeScript takes no decorators and...stays an error, using #618's#bindingListClose), otherwise the item is parsed bysuperand gets them where acorn-typescript puts them (the parameter, or a parameter property'sparameter), so the AST of every other decorated parameter is unchanged. Because the list takes the rest element for an ordinary one, a comma after it is reported as for an undecorated rest parameter: thrown in a strict parse, recorded when collecting (as the existingparseBindingListoverride does), and allowed as a trailing comma in an ambient context.parseBindingListisn't touched.Upstream first: sveltejs/acorn-typescript#113 is my open PR for #194's cause, and the override mirrors it. sveltejs/acorn-typescript#110 contains the same
abstractchange, and also parsesexport default @dec abstract class C {}, but as aClassExpression(inparseExprAtom, fixturedecorators_export_default_abstract). #533 asks for the declaration that TypeScript and typescript-estree produce, so the override doesn't mirror #110 there, and sveltejs/acorn-typescript#124 says that #110's fixture would change. I checked a build of #110's head (65376678): none of the three new upstream issues is fixed there.#117 and #118. They're about the range of a class whose decorators come before
export(#118 starts it atclassinstead of the decorator), not about #533's node type; #118 leaves theClassExpressiondifference for after #110. This PR doesn't adopt #118's range: node ranges don't change anywhere (the comparison below found nostart/endchange). A decorated default-exported class still starts at its first decorator, whichlocStartin@tsrx/prettier-pluginandtsrx-prettier-plugincount on, and@dec export default class {}still starts at the decorator beforeexport.#564: accepted, not a collected error
TypeScript's parser accepts a decorator on a rest parameter. Its checker reports TS1206
Decorators are not valid here.only withoutexperimentalDecorators: with it, a method's or constructor's decorated rest parameter has no diagnostic (checked with TypeScript 5.9.3), exactly like a decorated ordinary parameter. The parser here already takes decorators on ordinary parameters (and on function parameters, where TypeScript always reports TS1206) without any error. So a decorated rest parameter now parses the same way: no error in any mode, nothing to add toCHECKER_LEVEL_ERRORS, and a strict compile doesn't throw. Whether the decorator is allowed stays with TypeScript's checker, which sees the file through the editor andtsrx-tsc.Behavior changes to review
All match TypeScript and typescript-estree.
export default @dec class {}followed by(foo)on the next line was a call of the class (export default (@dec class {})(foo)); it's now a declaration and an expression statement.export default @dec class {} + 1;becomes a declaration and+1;, andexport default @dec class {}.name;is nowUnexpected token, as without the decorator. No input in the comparison corpus has such a form.exportfollowed by anything but a class:@dec export function f() {},@dec export const A = class {},@dec export default (class {}),@dec export default 1,@dec export interface I {},@dec export { a }, … all now fail withLeading decorators must be attached to a class declaration.at the declaration, in every mode, like@dec function f() {}always has. They used to parse and drop the decorators or move them onto a class expression. TypeScript reports these as TS1206 from its checker; [Bug]: tsrx-core: Collect mode throws for decorators where TypeScript reports TS1206 from its checker #610 covers recording them in collect mode instead of throwing, for these and the forms that already threw.implements(const X = class implements I {}) now hasid: nullinstead of noidproperty, as in fix: parse anonymous default-exported classes with implements or abstract sveltejs/acorn-typescript#113 and every other anonymous class.export default class implements {}(TypeScript:implementsis the name, TS1213) now fails with'implements' list cannot be empty.instead ofThe keyword 'implements' is reserved, as with refactor: remove array_slice, iterable_array_from, and buildFallback #113.export default @dec abstractfollowed byclass A {}on the next line (a syntax error in TypeScript) used to exportabstractand hang@decon the next class; it's now one decorated abstract class, like the undecoratedexport default abstract/class A {}already was. That existing reading differs from TypeScript's; it's [Bug]: tsrx-core:abstractordeclarebefore a line break afterexportis read as a modifier, unlike TypeScript #608, which needs a decision because it changes what valid code means.Formatters
tsrx-prettier-pluginretyped a decorated default-exportedClassExpressionas aClassDeclarationin its adapter. The parser now produces the declaration, and aClassExpressiondirectly underexport defaultis always parenthesized, so the block is removed.@tsrx/prettier-plugin: two comments that said a decorated default-exported class parses as aClassExpressionare updated. No code change: it already printed that class as a declaration, and its tests pass unchanged.export default class implements I {},export default @dec abstract class {},m(@a ...rest: unknown[]), …) stably and like Prettier'stypescriptparser.Verification
AST comparison. Every input parsed on
main(03de6568, after #602, #615, #595, #618, #633 and #605) and on this branch, strict and with{ collect: true, errors: [], comments: [], preserveParens: true }, comparing the full AST (ranges included), collected errors, comments, and thrown messages:.tsrxfilespackages/tsrx-prettier-plugin/tests/prettier/(readSnapshotEntries/readFormatCase)Out of 17,617 inputs, 24 changed, all intended, and no error, thrown message, or range changed. No parse hung.
export default @dec class …:ClassExpression→ClassDeclarationjs/decorators-export.snap :: after_export.js(input and output), and 11 strings inprettier-plugin/src/index.test.jsconst X = class implements …:idabsent →nullprettier-plugin/src/index.test.js, 1 inupstream-parser-workarounds.test.jsThe new strings in
upstream-parser-workarounds.test.jschange as the tests describe.Compile output. For every target (
react,preact,solid,vue,hono),compileandcompile_to_volar_mappingsgive the same code before and after for the inputs that parsed before (a decorated default-exported class, a class expression withimplements, a component module with one). The inputs that used to throw now compile. Parameter decorators, rest or not, don't appear in any compiled output because esrap 2.3.2 doesn't print them; that's #606, fixed in esrap 2.3.10.Tests.
packages/tsrx/tests/utils/upstream-parser-workarounds.test.jsgets 18 tests in fourdescribes, one per upstream cause, all through the parse worker (parse_in_worker_with_ast), strict and collecting:export default class implementsandexport default abstract class#194: the five issue forms as anonymous declarations, heritage clauses and type parameters kept, a named abstract default export still binding its name, a class expression'sid: null,class implements I {}still rejected@if/@{/@forconstructs still expressions, decorators before a function, interface or expression still rejected@dec export, the class range kept, eleven other exports rejected at the declaration, including an at-sign construct afterexport/export defaultRestElement(method, constructor with a pattern, ambient method, function), other parameters' decorators unchanged, a comma after it handled like an undecorated rest parameter's, the ambient trailing comma allowed, errors inside it (...rest?, a repeated name, a default) at the same message and place as without the decorator,...after decorators in an array pattern still rejected, and a decorated optional pattern in an overload (with fix(core): collect more checker-level mistakes, report a disallowed modifier's message, and accept an optional binding pattern in an overload (#587, #588, #550, #557) #618)Without the fix, 11 of the 18 fail; the other 7 guard behavior that worked before (or, for the optional pattern, that #618 added). Bugbot found that an at-sign construct after
export(@dec export default @if (a) { … }) slipped past the check for decorators beforeexport; 392785b fixes that and adds three cases.pnpm vitest run --project tsrx-utils --project tsrx-analyze --project prettier-plugin --project tsrx-prettier-plugin --maxWorkers=4: 33 files, 5,714 passed, 17 skipped (withmainat03de6568).prettier-known-failures.jsondoesn't change (UPDATE_KNOWN_FAILURES=1). The target compiler projects weren't run locally, since their output doesn't change.pnpm typecheck: every step passes.vite-plugin-hono'stypecheck:testsran throughpackages/typescript-plugin/dist/tsc.js, sincetsrx-tscwasn't linked in the new worktree.pnpm format: clean.A
patchchangeset for@tsrx/core.@tsrx/prettier-pluginonly has comment changes, andtsrx-prettier-pluginis private.Findings
Filed upstream (each with a repro using only
acornand@sveltejs/acorn-typescript, checked against #110's head):export default @dec classparses as a class expression, andexport default @dec abstract classfails sveltejs/acorn-typescript#124:export default @dec classis a class expression; the abstract form failsexportare accepted before any declaration, and go to the next class or are dropped sveltejs/acorn-typescript#125: decorators beforeexportare accepted before any declarationFiled here, separate causes, not fixed in this PR:
export abstractfollowed by a line break #607:export abstractfollowed by a line break crashes the parser with aTypeErrorabstractordeclarebefore a line break afterexportis read as a modifier, unlike TypeScript #608:abstractordeclarebefore a line break afterexportis read as a modifier, unlike TypeScript (changes what valid code means, so it needs a decision)Same cause, noted here: with the parser change, a class or function expression directly under
export defaultin@tsrx/prettier-pluginis always a parenthesized one, soisParenthesizedDefaultExport's source check is now redundant; it's left as it is.Closes #194
Closes #533
Closes #564
🤖 Generated with Claude Code