Repository navigation
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
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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
This was referenced Sep 25, 2026
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
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.
- A
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.
… 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]>
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.


Six
@tsrx/coreparser bugs around class headings, type arguments,export, and array patterns, follow-ups to #614. Three are caused in@sveltejs/acorn-typescript1.0.13 and worked around by overriding the responsible method inTSRXPlugin(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{orimplementson the next line parsed with an instantiation expression (Base<T>) as the superclass and nosuperTypeParameters. acorn-typescript'sparseSubscriptreadsBase<T>as an instantiation expression unless the next token starts an expression on the same line, so the<T>is gone whenparseClassSuperlooks 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 unparenthesizedTSInstantiationExpressionsuperclass is taken apart intosuperClassandsuperTypeParameters, as acorn-typescript's ownparseNewdoes fornew 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 Bwith<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
implementsread), the tag start is read again as<, without the tag contexts it pushed, and the type arguments andimplementsclause 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>andfunction <T>(x: T) { return x; }<string>failed, because a<after a}reads as a tag start.Fix: in #635's
parseSubscriptsoverride, a tag start on the same line after an unparenthesized class or function expression is read again as<. acorn-typescript'sparseSubscriptthen 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>andfunction () {}<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 abstractfollowed by a line break crashedexport abstract/class A {},export abstract;,export type/Foo = 1;,export namespace/N {},export module/M {},export declare abstract/class A {}, andexport @if (…) { … }(or@{,@for,@switch,@try) threwTypeError: Cannot read properties of undefined (reading 'start')in every mode. acorn-typescript'sshouldParseExportStatementtakes these words, and any@, for the start of a declaration.tsParseDeclarationdeclines the words before a line break (TypeScript's same-line rule) or before anything but a class or a name.parseExportDeclarationthen falls back toparseStatement, which reads the word or the at-sign construct as a statement, andparseExportreads that statement'sid.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 nowUnexpected tokenat the@, as forexport foo, and afterexport declareacorn-typescript's'export declare' must be followed by an ambient declaration..parseExportDeclaration(UPSTREAM): when the statement it parsed isn't a declaration, it reportsUnexpected tokenat the token afterexport. "Isn't a declaration" means noidand not a variable declaration, which is exactly whenparseExportcrashed. TypeScript reports TS1128Declaration or statement expected.for all of these.#608 isn't decided. The fix stops at "no crash".
export declare/class A {}andexport 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-ofandcatchpatterns parsed, and compiling dropped the decorators. (Both formatters printed them.) acorn-typescript'sparseAssignableListItemreads decorators for every binding list item, including the elements of an array pattern.Fix: one check in the
parseAssignableListItemoverride from #614 and #647. When the list is an array pattern (#bindingListClose === tt.bracketR, from #618),@isUnexpected 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:
consttype parameters on an object method{ m<const T>(x: T) {} }failed withUnexpected keyword 'const'. TSRX'sparsePropertyValuereads a plain generic method's type parameters without a modifier parser. Fix: passthis.tsParseConstModifier, as acorn-typescript does for the methods it parses.inandoutstill get their error. #633's change, which starts the method's function at its type parameters, is unchanged.Overrides
plugin.jsparseClassSuper(new)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 unparenthesizedTSInstantiationExpressionsuperclass when the class has nosuperTypeParameters, giving the one-line heading's AST. The UPSTREAM marker is on (b) only.parseSubscripts(#635's, extended)ClassExpressionorFunctionExpressionfollowed by a tag start on its line, and not</.shouldParseExportStatement(new)@{,@if,@for,@switchand@try. Everything else goes tosuper.parseExportDeclaration(new)super. It raises only when the result isn't a variable declaration and has noid, which is exactly whenparseExportcrashed.parseAssignableListItem(#614's, extended)@in an array pattern.parsePropertyValue(TSRX's own)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.
superClassplussuperTypeParametersinstead of aTSInstantiationExpression. The meaning is the same: TypeScript reads both as the heritage clause's type arguments. Compiled and editor output change fromextends (Base<T>)toextends Base<T>, what the one-line heading gives. A comment between the type arguments andimplementsnow trailssuperTypeParameters(it trailed the instantiation expression). Both formatters print these inputs exactly as before.class {} <b> c, which is a comparison, as in TypeScript;consttype parameters on object methods.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).Unexpected token, or'export declare' must be followed by an ambient declaration.afterexport 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 asa16a32cb, 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:.tsrxfiles;readSnapshotEntries/readFormatCase);Out of 18,349 inputs, 72 changed, all intended. No parse hung.
TSInstantiationExpressionsuperclass becomessuperClass+superTypeParameterstypescript/class-comment.snap :: declare.tsinput;typescript/class.snap :: extends_implements.tsinput and output;class.snap :: issue-16723.tsinput (collect only, since the strict parse throws a redeclaration error before and after);typescript/classes.snap :: break.tsoutput; 3 strings inprettier-plugin/src/index.test.js[@a ...x]'s error moves from the...to the@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.jsstrings. In 2 of them, the comment beforeimplementsmoves as described above. In the third,class A\n extends /** @type {X} */ (\n a // c\n )<T>\n{, the JSDoc cast now leadsa, exactly as in the same heading with the{on the<T>line.Compile output. I compared
compileandcompile_to_volar_mappingsfor every target (react,preact,solid,vue,hono) on the #523 inputs and ten new inputs, including component bodies. Every output that changed differs only byextends (X<T>)becomingextends 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'stypescriptparser prints, and their output now parses on the next pass. #523'sclass D /* c */\n extends Base…<T…>\n{now reparses withsuperTypeParameters, and #578's(class<T> {\n x?: T;\n}<string>).name;reparses. For #545's own example, see the findings.Tests.
upstream-parser-workarounds.test.js: a describe for each of Version Packages #131, Review/pr 129 #132 and fix(typescript-plugin): apply tsc patches under Deno #133 (6 tests). fix(core): parse anonymous and decorated default-exported classes as declarations, and decorators on a rest parameter (#194, #533, #564) #614's test for...in an array pattern moved into fix(typescript-plugin): apply tsc patches under Deno #133's describe.tokenizer-context.test.js: a describe for [Bug]: core rejects a superclass's type arguments that start on the line after the superclass #545 and [Bug]: core rejects type arguments right after a class or function expression #578 (6 tests) in strict, collect and loose mode, including fix(core): read tokens by their context like TSX: comments after directive keywords,yield @…,/>/,</after an operand, and subscripts after elements (#477, #547, #584, #586, #426) #635's element rule, the line-start<, and a comment right after the<.parser.test.js: an at-sign construct afterexport([Bug]: tsrx-core: Parser crashes with a TypeError onexport abstractfollowed by a line break #607) andconsttype parameters ([Bug]: tsrx-core: An object literal method with a const type parameter fails to parse #631), 4 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-vueandtsrx-hono: 3,019 passed, 60 skipped.prettier-known-failures.jsondoesn't change (UPDATE_KNOWN_FAILURES=1).pnpm typecheck: every step passes.tsrx-tscisn't linked after--ignore-scripts, sovite-plugin-hono'stypecheck:testsran throughpackages/typescript-plugin/dist/tsc.jsafter building@tsrx/typescript-plugin.types/parse.d.tsgainstsParseConstModifierandtsParseHeritageClause.pnpm formatandpnpm changeset:check: clean.The changeset is a
patchfor@tsrx/core.Findings
Filed upstream, each with a repro using only
acornand@sveltejs/acorn-typescript, checked against #110's head:export abstractfollowed by a line break crashes with a TypeError sveltejs/acorn-typescript#132:export abstractfollowed by a line break crashes with a TypeError (andexport type,namespace,module,export abstract;)Filed here, separate causes, not fixed in this PR:
abstract,type,namespaceormoduleafterexportis dropped before a declaration it does not start #651:abstract,type,namespaceormoduleafterexportis dropped before a declaration it doesn't start (export abstract function f() {}compiles toexport function f() {}). It's acorn-typescript'stsParseDeclarationagain, which consumes the word before it declines it (export abstractfollowed by a line break crashes with a TypeError sveltejs/acorn-typescript#132 describes it too). It's code that parses today, andabstractthere is a checker error in TypeScript (TS1242), so it needs a decision.class A extends B // d/<T> {}, which both formatters print for a comment before the type arguments, like Prettier) moves into the class body with@tsrx/prettier-plugin. Prettier andtsrx-prettier-pluginkeep it after the class (class A extends B<T> {} // d).printClassmoves every trailing line comment of the superclass into the body. Onmain, the second pass failed to parse instead.Closes #523
Closes #545
Closes #578
Closes #607
Closes #609
Closes #631
🤖 Generated with Claude Code