Skip to content

fix(core): read type arguments after superclasses and class and function expressions, and reject what follows export or decorates an array pattern (#523, #545, #578, #607, #609, #631) - #650

Merged
leonidaz merged 5 commits into
mainfrom
fix/core-class-heads-type-arguments
Sep 25, 2026

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Six @tsrx/core parser bugs around class headings, type arguments, export, and array patterns, follow-ups to #614. Three are caused in @sveltejs/acorn-typescript 1.0.13 and worked around by overriding the responsible method in TSRXPlugin (packages/tsrx/src/plugin.js), marked // UPSTREAM(sveltejs/acorn-typescript#<n>): remove once a release includes the fix. The other three are TSRX's own code.

The bugs and the fixes

#523: a superclass's type arguments before a line break

class D<T> extends Base<T> with the { or implements on the next line parsed with an instantiation expression (Base<T>) as the superclass and no superTypeParameters. acorn-typescript's parseSubscript reads Base<T> as an instantiation expression unless the next token starts an expression on the same line, so the <T> is gone when parseClassSuper looks for it. Prettier breaks a long heading right there, so the formatter's output parsed to a different tree than its input.

Fix: after acorn-typescript's parseClassSuper, an unparenthesized TSInstantiationExpression superclass is taken apart into superClass and superTypeParameters, as acorn-typescript's own parseNew does for new A<T>. The heading then has the AST it has on one line. class A extends (B<T>) keeps its instantiation expression.

#545: type arguments on the line after the superclass

class A extends B with <T> {} on the next line failed at the <: a < that starts its own line reads as a tag start, and the heading stopped before it.

Fix: as #419 does after a declaration name, when the heading stopped at a tag start right after the superclass (with no type arguments or implements read), the tag start is read again as <, without the tag contexts it pushed, and the type arguments and implements clause are parsed as acorn-typescript does. A closing tag's </ stays a tag start, so its error stays where it was, but a comment right after the < (</* c */ T>, <// c) starts type arguments, as for a </ after an operand (#586); Bugbot found that case, fixed in 90c7da6. Before, a tag start there was always an error.

#578: type arguments right after a class or function expression

class<T> { x?: T }<string> and function <T>(x: T) { return x; }<string> failed, because a < after a } reads as a tag start.

Fix: in #635's parseSubscripts override, a tag start on the same line after an unparenthesized class or function expression is read again as <. acorn-typescript's parseSubscript then reads type arguments (an instantiation expression, a call, new, or a tagged template), or a less-than when no type arguments fit, as after an identifier. Only code that failed to parse changes: on the same line, a tag start after a class or function expression was always an error.

How it fits #635: #635's rule that an element, fragment or TSRX value takes no subscripts comes first in the same override and is unchanged. <b /><T> and @{ … }<T> still fail at the <, and (<b />)<T> still parses. A class or function expression is a left-hand-side expression in TypeScript, so it takes type arguments like any other subscript, and (class {})<T> and function () {}<T> now follow TypeScript. On the next line, a < after one still starts an element (const f = function () {} then <div />), by the line-start < rule, which this PR leaves as it is. A </ stays a closing tag (#586). A test checks each of these.

#607: export abstract followed by a line break crashed

export abstract / class A {}, export abstract;, export type / Foo = 1;, export namespace / N {}, export module / M {}, export declare abstract / class A {}, and export @if (…) { … } (or @{, @for, @switch, @try) threw TypeError: Cannot read properties of undefined (reading 'start') in every mode. acorn-typescript's shouldParseExportStatement takes these words, and any @, for the start of a declaration. tsParseDeclaration declines the words before a line break (TypeScript's same-line rule) or before anything but a class or a name. parseExportDeclaration then falls back to parseStatement, which reads the word or the at-sign construct as a statement, and parseExport reads that statement's id.

Fix, in two overrides:

  • shouldParseExportStatement, TSRX's own: an at-sign construct isn't a declaration. acorn-typescript is right to take every @ for decorators in TypeScript. It's now Unexpected token at the @, as for export foo, and after export declare acorn-typescript's 'export declare' must be followed by an ambient declaration..
  • parseExportDeclaration (UPSTREAM): when the statement it parsed isn't a declaration, it reports Unexpected token at the token after export. "Isn't a declaration" means no id and not a variable declaration, which is exactly when parseExport crashed. TypeScript reports TS1128 Declaration or statement expected. for all of these.

#608 isn't decided. The fix stops at "no crash". export declare / class A {} and export default abstract / class A {} parse as before; a test pins them, with a comment that #608 decides them. export abstract / class A {} is now a syntax error, which both of #608's options allow. Under TypeScript's rule it stays an error, since TypeScript reports TS1128. If #608 keeps reading these words as modifiers across a line break, it would become an abstract class. It crashed before, so no code that parses today changes meaning.

#609: decorators in an array binding pattern

const [@a x] = y;, function f([@a x]) {}, and the same in nested, for-of and catch patterns parsed, and compiling dropped the decorators. (Both formatters printed them.) acorn-typescript's parseAssignableListItem reads decorators for every binding list item, including the elements of an array pattern.

Fix: one check in the parseAssignableListItem override from #614 and #647. When the list is an array pattern (#bindingListClose === tt.bracketR, from #618), @ is Unexpected token, as in an object pattern. TypeScript reports TS1181 at the @. This moves the error for [@a ...x] from the ... to the @, so #614's special case for ... in an array pattern goes. Parameter decorators are unchanged, including a decorated pattern parameter and the parameters of a function inside a pattern. #647's modifier and rest-parameter handling next to it isn't touched.

#631: const type parameters on an object method

{ m<const T>(x: T) {} } failed with Unexpected keyword 'const'. TSRX's parsePropertyValue reads a plain generic method's type parameters without a modifier parser. Fix: pass this.tsParseConstModifier, as acorn-typescript does for the methods it parses. in and out still get their error. #633's change, which starts the method's function at its type parameters, is unchanged.

Overrides

Override in plugin.js tsrx issue Upstream Why it's narrow
parseClassSuper (new) #523, #545 sveltejs/acorn-typescript#131 (filed) for #523; #545 is TSRX's tokenizer Calls super, then: (a) re-reads a tag start left right after the superclass when nothing else was read, which was always an error before; (b) takes apart an unparenthesized TSInstantiationExpression superclass when the class has no superTypeParameters, giving the one-line heading's AST. The UPSTREAM marker is on (b) only.
parseSubscripts (#635's, extended) #578 none; TSRX's tokenizer makes the tag start Only for an unparenthesized ClassExpression or FunctionExpression followed by a tag start on its line, and not </.
shouldParseExportStatement (new) #607 none; TSRX's at-sign constructs Only for @{, @if, @for, @switch and @try. Everything else goes to super.
parseExportDeclaration (new) #607 sveltejs/acorn-typescript#132 (filed) Calls super. It raises only when the result isn't a variable declaration and has no id, which is exactly when parseExport crashed.
parseAssignableListItem (#614's, extended) #609 sveltejs/acorn-typescript#133 (filed) One check for an @ in an array pattern.
parsePropertyValue (TSRX's own) #631 none One argument.

Upstream first: I checked the issues and PRs (gh issue list / gh pr list -R sveltejs/acorn-typescript --state all) and a build of #110's head (65376678). None of the three causes is covered or fixed there. sveltejs/acorn-typescript#130 (filed for #616) has #133's cause for ? and type annotations, and #133 links it. #132 and #133 are errors, so there's no AST to mirror. For #131 the override gives the one-line heading's AST, which is what an upstream fix gives.

Behavior changes to review

All follow TypeScript.

  • AST change for code that parses today ([Bug]: core: A superclass's type arguments before a line break parse as an instantiation expression #523). A superclass whose type arguments are followed by a line break is now superClass plus superTypeParameters instead of a TSInstantiationExpression. The meaning is the same: TypeScript reads both as the heritage clause's type arguments. Compiled and editor output change from extends (Base<T>) to extends Base<T>, what the one-line heading gives. A comment between the type arguments and implements now trails superTypeParameters (it trailed the instantiation expression). Both formatters print these inputs exactly as before.
  • Now rejected ([Bug]: tsrx-core: Parser accepts decorators in array binding patterns, which TypeScript rejects, and drops them #609): decorators on array pattern elements (TS1181). Compiling dropped them; the formatters printed them.
  • Now accepted: type arguments on the line after a superclass; type arguments after a class or function expression on its line; class {} <b> c, which is a comparison, as in TypeScript; const type parameters on object methods.
  • Error positions: in invalid code with a tag start on the same line after a class or function expression, the error moves to where TypeScript reports it. const f = function () {} <div />; now fails at the > (TypeScript: TS1109 at the same offset) instead of the <. x = class {}<div>a</div>; fails at the </ (TypeScript: TS1005 there).
  • Crashes are now syntax errors: Unexpected token, or 'export declare' must be followed by an ambient declaration. after export declare.

Carried over from #614

6fc5d2bf (test(core): cover decorators on both sides of `export default` ) was pushed to #614's branch after it merged, so it isn't in main. It's cherry-picked here as a16a32cb, and it passes, also with #647 merged in.

Verification

AST comparison. I compared main (8eeec666, after #635, #641 and #647) with this branch. Each input was parsed strictly and with { collect: true, errors: [], comments: [], preserveParens: true }. The comparison covers the full AST (ranges included), collected errors, comments, and thrown messages, in 4 worker threads with a hard timeout. The inputs:

  • the 70 tracked .tsrx files;
  • the 2,040 Prettier snapshot inputs and 2,040 outputs (readSnapshotEntries / readFormatCase);
  • 14,199 distinct string literals from test files, this PR's included.

Out of 18,349 inputs, 72 changed, all intended. No parse hung.

Change Inputs
#523: TSInstantiationExpression superclass becomes superClass + superTypeParameters 8: typescript/class-comment.snap :: declare.ts input; typescript/class.snap :: extends_implements.ts input and output; class.snap :: issue-16723.ts input (collect only, since the strict parse throws a redeclaration error before and after); typescript/classes.snap :: break.ts output; 3 strings in prettier-plugin/src/index.test.js
#609: [@a ...x]'s error moves from the ... to the @ 2: #614's test strings
This PR's own test strings 62: the shapes the new tests exercise

For the 8 #523 inputs, the new AST is the old one with the instantiation expression taken apart; I checked this by applying that transformation to the old AST. The one exception is comments in 3 of the index.test.js strings. In 2 of them, the comment before implements moves as described above. In the third, class A\n extends /** @type {X} */ (\n a // c\n )<T>\n{, the JSDoc cast now leads a, exactly as in the same heading with the { on the <T> line.

Compile output. I compared compile and compile_to_volar_mappings for every target (react, preact, solid, vue, hono) on the #523 inputs and ten new inputs, including component bodies. Every output that changed differs only by extends (X<T>) becoming extends X<T> (95 outputs). The inputs that used to throw now compile (80 outputs).

Formatters. No formatter code changes. For every input that changed and parsed before, both formatters give the same output as on main. For the issue examples, both print what Prettier's typescript parser prints, and their output now parses on the next pass. #523's class D /* c */\n extends Base…<T…>\n{ now reparses with superTypeParameters, and #578's (class<T> {\n x?: T;\n}<string>).name; reparses. For #545's own example, see the findings.

Tests.

Without the fix, 11 of the 16 new parser tests fail. The other 5 guard behavior that already worked.

Commands.

  • pnpm vitest run --project tsrx-utils --project tsrx-analyze --project prettier-plugin --project tsrx-prettier-plugin --maxWorkers=4: 34 files, 5,893 passed, 17 skipped.
  • tsrx-react, tsrx-preact, tsrx-solid, tsrx-vue and tsrx-hono: 3,019 passed, 60 skipped.
  • prettier-known-failures.json doesn't change (UPDATE_KNOWN_FAILURES=1).
  • pnpm typecheck: every step passes. tsrx-tsc isn't linked after --ignore-scripts, so vite-plugin-hono's typecheck:tests ran through packages/typescript-plugin/dist/tsc.js after building @tsrx/typescript-plugin. types/parse.d.ts gains tsParseConstModifier and tsParseHeritageClause.
  • pnpm format and pnpm changeset:check: clean.

The changeset is a patch for @tsrx/core.

Findings

Filed upstream, each with a repro using only acorn and @sveltejs/acorn-typescript, checked against #110's head:

Filed here, separate causes, not fixed in this PR:

Closes #523
Closes #545
Closes #578
Closes #607
Closes #609
Closes #631

🤖 Generated with Claude Code

leonidaz and others added 4 commits September 25, 2026 16:16
…ion expressions, and reject what follows export or decorates an array pattern (#523, #545, #578, #607, #609, #631)

- #523: `parseClassSuper` takes an unparenthesized instantiation-expression
  superclass apart into `superClass` and `superTypeParameters`, as
  acorn-typescript's `parseNew` does for `new A<T>`, so a heading that breaks
  after `Base<T>` has the AST it has on one line. UPSTREAM
  sveltejs/acorn-typescript#131.
- #545: after the superclass, a tag start is read again as `<` and the type
  arguments and `implements` clause parsed, as #419 does after a declaration
  name.
- #578: `parseSubscripts` reads a tag start on the same line after a class or
  function expression again as `<`, so `class<T> {}<string>` and
  `function <T>() {}<string>()` parse as in TypeScript. Elements still take
  no subscripts (#426), and a `<` on the next line still starts an element.
- #607: `shouldParseExportStatement` doesn't take an at-sign construct for a
  declaration, and `parseExportDeclaration` reports `Unexpected token` when
  the statement it parsed isn't a declaration (`export abstract` before a line
  break, `export abstract;`), instead of crashing reading its `id`. UPSTREAM
  sveltejs/acorn-typescript#132. #608's readings are unchanged.
- #609: a decorator on an element of an array pattern is `Unexpected token`
  at the `@`. UPSTREAM sveltejs/acorn-typescript#133.
- #631: an object method's type parameters take `const`, as acorn-typescript
  reads them for the methods it parses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	packages/tsrx/src/plugin.js

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Comments mistaken for closing tags
    • A < followed by /* or // is now re-read as a type-argument start, while a real closing tag's </ stays a tag start.

Create PR

Or push these changes by commenting:

@cursor push a2231ba975
Preview (a2231ba975)
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
@@ -3848,12 +3848,17 @@
 			/**
 			 * The same where a tag can't start but type arguments can: after a
 			 * superclass, and after a class or function expression on its line. A
-			 * closing tag's `</` stays a tag start, so an error stays at it. Returns
-			 * whether the token is now `<`.
+			 * closing tag's `</` stays a tag start, so an error stays at it. A
+			 * comment glued to the `<` (`</*` or `<//`) is whitespace, as it is
+			 * after a name, so that `<` is read again too. Returns whether the
+			 * token is now `<`.
 			 */
 			#readTagStartAsTypeArgumentStart() {
 				if (this.type !== tstt.jsxTagStart) return false;
-				if (this.input.charCodeAt(this.start + 1) === CharCode.slash) return false;
+				if (this.input.charCodeAt(this.start + 1) === CharCode.slash) {
+					const after_slash = this.input.charCodeAt(this.start + 2);
+					if (after_slash !== CharCode.slash && after_slash !== CharCode.asterisk) return false;
+				}
 				this.#readTagStartAsTypeParameterStart();
 				return true;
 			}

diff --git a/packages/tsrx/tests/utils/tokenizer-context.test.js b/packages/tsrx/tests/utils/tokenizer-context.test.js
--- a/packages/tsrx/tests/utils/tokenizer-context.test.js
+++ b/packages/tsrx/tests/utils/tokenizer-context.test.js
@@ -453,6 +453,8 @@
 		/** @type {Array<[source: string, superClass: string, typeArguments: string, implements: string[]]>} */
 		const cases = [
 			['class A extends B\n<T> {}', 'B', '<T>', []],
+			['class A extends B\n</* props */ T> {}', 'B', '</* props */ T>', []],
+			['class A extends B\n<// props\nT> {}', 'B', '<// props\nT>', []],
 			['class C extends (a || b)// d\n<T> {}', 'a || b', '<T>', []],
 			['class A extends B.C\n  <T, U>\n  implements I\n{}', 'B.C', '<T, U>', ['I']],
 			['const X = class extends B\n<T,> {};', 'B', '<T,>', []],
@@ -539,6 +541,46 @@
 		).toEqual(cases.map(([source]) => (source.includes('<string>') ? '<string>' : '<T>')));
 	});
 
+	it('reads a comment glued to the `<` of a class or function expression', async () => {
+		/** @type {Array<[source: string, path: string[], typeArguments: string]>} */
+		const cases = [
+			[
+				'const A = class {}</* T */ string>;',
+				['TSInstantiationExpression', 'ClassExpression'],
+				'</* T */ string>',
+			],
+			[
+				'const f = function () {}<// T\nstring>;',
+				['TSInstantiationExpression', 'FunctionExpression'],
+				'<// T\nstring>',
+			],
+			[
+				'function App() @{\n  const A = class {}</* T */ string>;\n  <div />\n}',
+				['TSInstantiationExpression', 'ClassExpression'],
+				'</* T */ string>',
+			],
+		];
+		const programs = await parse_all(cases.map(([source]) => source));
+		expect(
+			programs.map((program) => {
+				const path = [];
+				/** @type {(AST.Node & Record<string, any>) | undefined} */
+				let node = value_of(statements(program)[0]);
+				while (node) {
+					path.push(node.type);
+					node = node.expression ?? node.callee ?? node.tag ?? node.object;
+				}
+				return path;
+			}),
+		).toEqual(cases.map(([, path]) => path));
+		expect(
+			programs.map((program, index) => {
+				const node = find(program, (type) => type === 'TSInstantiationExpression');
+				return text(cases[index][0], node?.typeArguments);
+			}),
+		).toEqual(cases.map(([, , typeArguments]) => typeArguments));
+	});
+
 	it('keeps a comparison, and an element on the next line, after a class or function expression', async () => {
 		const [comparison, element] = await parse_all([
 			// `(class {} < b) > c`, as in TypeScript.
@@ -567,6 +609,7 @@
 			// TypeScript reports these at the same token.
 			['const f = function () {} <div />;', 'Unexpected token', '>;'],
 			['x = class {}<div>a</div>;', 'Unexpected token', '</'],
+			['x = class {}</div>;', 'Unexpected token', '</'],
 			['x = <div>{function () {}</div>', "'}' expected.", '</'],
 		]);
 	});

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit db9d70f. Configure here.

Comment thread packages/tsrx/src/plugin.js Resolved
… a tag could start

A tag start after a superclass or a class or function expression that is
followed by `/*` or `//` starts type arguments with a comment
(`class A extends B` with `</* c */ T> {}` on the next line,
`class {}</* c */ T>`), as for a `</` after an operand (#586). A closing
tag's `</` stays a tag start.

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