Repository navigation
fix(core): collect type-check-level errors in collect mode instead of throwing (#415) - #558
Merged
Merged
Conversation
… throwing (#415) In `collect` and `loose` mode, `raise` and `raiseRecoverable` record the errors that TypeScript's parser accepts and reports only from its checker (`CHECKER_LEVEL_ERRORS` in plugin.js) and keep parsing, as the parser already did for a redeclared variable. A strict parse still throws every one of them, and every other error still throws. Sites where the raising code can't continue get narrow overrides instead: - a comma after a rest element: a trailing comma is skipped (as acorn-typescript does in ambient contexts), and `parseBindingList` keeps reading elements after a rest element - `const` without an initializer (`parseVarStatement`, `parseVar`, `parseVarId`), recorded with TypeScript's TS1155 message - `await` in a namespace, which acorn-typescript marks as a class static block: `canAwait` looks through namespaces, and `finishNode` records TypeScript's message for an await expression, `for await`, or `await using` - `#x in obj` outside a class: private-field checks are off when collecting, and `parsePrivateIdent` records a private name outside any class Errors recorded while acorn-typescript tries a parse it then abandons are rolled back with it, and an error acorn raises twice at one position is recorded once. The modifier order and compatibility errors are recorded at the modifier, not at acorn-typescript's column (sveltejs/acorn-typescript#122). All 59 Prettier format tests that failed on these now pass. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…omma and the closing paren Co-Authored-By: Claude Opus 5.5 <[email protected]>
Regenerated prettier-known-failures.json: the 7 cases #511 skips remain. 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.
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 4cf9d1a. Configure here.
…he parseVar override Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merged
This was referenced Sep 25, 2026
This was referenced Sep 27, 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 #415
This is item 1.3 of Phase 1 in #511 (decision 14). Item 1.4, reporting
'}' expectedfor a missing}, touches error reporting as well and follows in a separate PR.The rule
Some mistakes are accepted by TypeScript's parser and reported only by its checker. In
collectandloosemode (the language server, the formatter, and other editor tooling) the parser now records these inerrorsand keeps parsing. It already did this for a redeclared variable. A strict parse, which is what every compile does, still throws each of them, with the same message and position as before. Any error not on the list still throws in every mode.raiseandraiseRecoverableboth go through a single allow-list,CHECKER_LEVEL_ERRORSinpackages/tsrx/src/plugin.js. The comment above it states the rule. Before this changeraiseRecoverablematched onlyhas already been declaredandArgument name clash, andraisewasn't overridden at all. acorn-typescript routes both through acorn's baseraiseRecoverable, which skipped TSRX's override, and that's whytype 'T' has already been declared.was thrown.The allow-list
Each message went on the list only after I read the code that raises it and checked that parsing continues correctly when
raisereturns: the node gets finished, no token is skipped, and nothing loops. For every row, TypeScript 5.9.3 gives no syntax diagnostic and reports the code shown from its checker.Identifier '…' has already been declared(optional., optional#)let a; let a;, duplicate imports and private namesdeclareName, class body; acorn-typescriptdeclareNametype '…' has already been declared.type T = 1; type T = 2;declareNameArgument name clashfunction f(a, a) {}checkLValSimple(already collected)Export '…' is not definedexport { missing };parseTopLevelOptional chaining cannot appear in left-hand sidea?.b = c;toAssignable,checkLValSimpleThe only valid meta property for import is 'import.meta'import.source('x');parseImportMeta'new.target' can only be used in functions and class static blockconst x = new.target;parseNew'super' keyword outside a methodsuper();parseExprAtom(raise)super() call outside constructor of a subclasssuper()at top level or in a base classparseExprAtom(raise, same site)Comma is not permitted after the rest elementfunction f(...a,) {}Abstract methods can only appear within an abstract class.class A { abstract m(): void; }parseClassElementInitializers are not allowed in ambient contexts.declare class A { x = 1; },declare let x = 1;parseClassField,parseVarStatement'…' modifier must precede '…' modifier./'…' modifier cannot be used with '…' modifier.readonly public x,static abstract xtsParseModifiersDuplicate modifier: '…'.readonly readonly xtsParseModifiersPrivate elements cannot have an accessibility modifier ('…').private #x = 1;parseClassFieldPrivate elements cannot have the 'abstract' modifier.abstract accessor #s;parseClassFieldA binding pattern parameter cannot be optional in an implementation signature.function f({ a }?: T) {}parseBindingListItemDuplicated key in attributeswith { type: 'json', type: 'x' }parseWithEntriesPrivate elements cannot have the 'abstract' modifier.andsuper() call outside constructor of a subclassaren't rows in #415's table. The first is whatdecorator-auto-accessors-*.tsfails on once the accessibility error is collected. The second comes from the sameparseExprAtomsite assuper();, and it also rejectssuper()in a class withoutextends.Sites handled without
raisereturningUnexpected tokenon the comma....a,),,],,}) is recorded and skipped in#collectCheckerLevelError, the same way acorn-typescript already skips one in ambient contexts. A trailing comma after a rest parameter in an ambient context (declare function f(...a: T[],)) is valid TypeScript, so it's still skipped silently, as before.function fn5(x: string, ...y: any[], z: string);infunctionOverloadErrorsSyntax.ts, acorn leaves the list. When collecting,parseBindingListis acorn's loop with one change: the rest branch records the error and keeps reading elements. Without collecting it calls acorn's own method.constwithout an initializer (export const v: string;, TS1155). acorn callsunexpected()inparseVar. When collecting,parseVarStatementandparseVar(for aforhead) letconstdeclarators omit the initializer, except in an ambient context, where they already could.parseVarIdruns acorn's own check at that point: for a name it records TypeScript's message,'const' declarations must be initialized., and for a pattern (const { a };) it throws acorn'sUnexpected tokenat the same position as before.#x in objoutside a class (TS18016). acorn callsunexpected()unlesscheckPrivateFieldsis off. When collecting, the constructor turns it off, andparsePrivateIdentrecordsPrivate field '#x' must be declared in an enclosing classfor a private name outside any class, which is the error acorn raises forobj.#xthere. One consequence: a class that uses#ywithout declaring it isn't reported by the parser when collecting any more. TypeScript reports it as TS2339, and the editor shows that diagnostic.awaitin a namespace (TS1308). acorn-typescript gives a namespace body acorn's class static block scope flag, which makes it a var scope. As a result acorn readsawaitthere as an identifier and throwsCannot use await in class static initialization block, and returning from that raise would leave42as an unexpected token. When collecting,canAwaitlooks through namespace scopes. It only does that when acorn's owncanAwaitsays no.finishNodethen records TypeScript's message for anawaitexpression, afor awaitloop (TS1103), or anawait usingdeclaration (TS2852), at theawaitkeyword. The flag values are acorn internals that neither package exports, so they're constants in plugin.js, and the tests fail if they change.this.lastTokStart). The strict message is unchanged, including its wrong location.Two more safeguards:
parseEffects.willAppend).toAssignableandcheckLValSimple.Upstream
CHECKER_LEVEL_ERRORSandcanAwaitreference it withUPSTREAM(sveltejs/acorn-typescript#89). I didn't file a duplicate or comment there.UPSTREAM(sveltejs/acorn-typescript#110).UPSTREAM(sveltejs/acorn-typescript#122).parseWithEntriescheck, and doesn't conflict with this change. I found nothing else relevant in the open issues or PRs.Language server: duplicate diagnostics
The language server compiles with
loose: true(compile_to_volar_mappings). It shows collected errors as TSRX diagnostics next to TypeScript's diagnostics on the virtual code. Before this change, each of these mistakes was a fatal compile error, and the TypeScript diagnostic filter drops every TypeScript diagnostic while a fatal error exists, so the editor showed one TSRX error. Now the file compiles, so both show up. I checked each row with@tsrx/react'scompile_to_volar_mappingsand a TypeScript 5.9.3 program over the generated code:abstractin a concrete class (TS1244), an ambient initializer (TS1039),static abstract(TS1243),private #x(TS18010),abstract #x(TS18019), a parameter after a rest parameter (TS1014),export { missing }(TS2304),a?.b = c(TS2779),import.source(TS18061),new.target(TS17013),super()(TS2337),awaitin a namespace (TS1308),#x in obj(TS18016), andconstwithout an initializer (TS1155).readonly public xandreadonly readonly x(the printer writespublic readonly xandreadonly x), a trailing comma after a rest parameter (the printer drops it), an optional binding pattern (the printer drops the?, [Bug]: tsrx-core: Optional binding pattern parameters lose their?in compiled and editor output #556), and a duplicate import attribute (TypeScript doesn't check it).This is the convention
let a = 1; let a = 2;already follows: TSRX'sIdentifier 'a' has already been declarednext to TypeScript's TS2451, twice. Nothing in the language server removes TSRX errors that TypeScript also reports. Suppressing TSRX's copy would be a separate change to the language server, and it would lose the errors in the last group, so I left the convention as it is.Verification
AST comparison with
origin/main(41be7e80, which includes fix(core): readstaticbefore a line break as a modifier, a generic call signature first in an interface, a class named after a contextual keyword, andassertafter an import (#439, #420, #421, #423) #551 and fix(core): parse import attributes in import types (#422) #555). 10,477 distinct sources: the 69 tracked.tsrxfiles, 10 fixture sources, 7,292 code-like string and template literals from 137 test files (including fix(core): readstaticbefore a line break as a modifier, a generic call signature first in an interface, a class named after a contextual keyword, andassertafter an import (#439, #420, #421, #423) #551's and fix(core): parse import attributes in import types (#422) #555's), and the 2,040 inputs and outputs of the Prettier snapshots underpackages/tsrx-prettier-plugin/tests/prettier/(read withreadSnapshotEntries/readFormatCase). Each was parsed in three modes: strict,{ collect: true, errors: [], comments: [], preserveParens: true }, and{ loose: true }. That's 31,431 parses, run in four workers, each parse killed after 20 s, with no hangs. I compared every AST, the comments, and the collected errors, or the thrown message and position:collectorloose: no AST, comment, or error differs.collectandloose, all intended:semanticcases.typescript/import-type/comma/comma.ts. fix(core): parse import attributes in import types (#422) #555 parses its import types, and what stopped it after that is a redeclaredtype A.export { value },export { x }, andexport { missing }, whose tests run strict and still get the throw, and\tconst depth: number;, a line from adeclare namespacefixture.#x;,#x in,#internal,#value,#missing,<Child cls={#style.root} />, fix(core): readstaticbefore a line break as a modifier, a generic call signature first in an interface, a class named after a contextual keyword, andassertafter an import (#439, #420, #421, #423) #551's test strings#xand#secret = 1, and two strings that are error messages. acorn now reads the private name before it finds noin, soUnexpected tokenis at the token after it instead of at the#.Compile. For every row above, the 59 Prettier inputs, and the 6 recovery inputs,
@tsrx/react'scompilethrows exactly whatorigin/main's strict parse throws (77 of 77).Prettier's format tests. I ran
UPDATE_KNOWN_FAILURES=1 pnpm vitest run --project tsrx-prettier-plugin, then the project normally. All 59semanticcases pass, and nothing was added. With fix(core): readstaticbefore a line break as a modifier, a generic call signature first in an interface, a class named after a contextual keyword, andassertafter an import (#439, #420, #421, #423) #551 and fix(core): parse import attributes in import types (#422) #555 merged in, 7 known failures remain, the cases feat(tsrx-prettier-plugin): Phase 1 formatting decisions, Prettier-style parse errors, and fixes (#503, #504, #505, #509) #511 skips:typescript/error-recovery/index-signature.tsandjsdoc_only_types.ts, three each), which still throw withcollect;typescript/call/callee-comments.ts.Tests. In
packages/tsrx/tests/utils/parser.test.js,mistakes that TypeScript reports only from its checkercovers 31 sources (every row of [Bug]: tsrx-core: Parser throws on mistakes that TypeScript reports only as type-check diagnostics, even withcollect: true#415's table, plus the siblings above). They run in a worker throughparse_in_worker, extended asparse_in_worker_with_astto return ASTs and error positions, so a parse that never returns fails the test instead of hanging the run. For each source:collectandloosemode;declare function f({ a }?: T): void;for the optional pattern, a derived class's constructor forsuper(), and top-levelawaitfor the namespace), or it matches the expected shape where there's no valid equivalent;origin/mainwithout collecting.Further tests check that every valid source parses strictly, that the recovery inputs throw in all three modes, that nothing is recorded where TypeScript reports nothing, and that a
constpattern without an initializer still throws.Local runs: These all pass:
tsrx-utils,tsrx-analyze,tsrx-vite,prettier-plugin,tsrx-prettier-plugin,language-server,typescript-plugin,tsrx-react, andeslint-parser(--maxWorkers=4), after mergingmainpnpm typecheck,pnpm format:check, andpnpm changeset:checkA
patchchangeset for@tsrx/coreis included.Findings
?in compiled and editor output #556 (new): the printer drops the?of an optional binding pattern parameter, even in valid code such asdeclare function f({ a }?: T): void;. The editor then reports TS2554 forf().main. With this PR,collectmode records the error instead, so it's still a false error there. test: run the parser over the TypeScript compiler corpus sveltejs/acorn-typescript#110 drops the check.collect: true#415, and not covered here because they aren't in [Bug]: tsrx-core: Parser throws on mistakes that TypeScript reports only as type-check diagnostics, even withcollect: true#415's table or the Prettier cases:(...a, b) => a, TS1014) still throws when collecting. acorn'sparseParenAndDistinguishExpressionleaves the list after the rest element, likeparseBindingListdoes.argumentsin a namespace (TS2304) andawaitin a real class static block (TS18037) still throw acorn's class-static-block errors.new.targetdirectly in a namespace is accepted without an error. That's the same acorn-typescript scope flag, and TypeScript reports it as TS17013.Duplicated key in attributesafter the repeated attribute's value, not at its key. It's collected where acorn-typescript raises it.tsParseModifierspasses that template toraiseuncalled, so its message matches no entry, and it still throws in every mode, as before. TypeScript reports those modifiers from its checker too (TS1070, TS1274), so once [Bug]: tsrx-core: Parser error for a misplaced modifier shows a JavaScript function instead of a message #550 is fixed their messages can join the list.Merged with #551 and #555
mainis merged in, with #551 (Phase 1 item 1.1) and #555 (item 1.2). The only conflict wasprettier-known-failures.json, which I regenerated.plugin.jsandtypes/parse.d.tsmerged cleanly. The modifier errors work with #551'stsParseModifierandtsParseModifiersoverrides:static abstract,abstract static,readonly public, andreadonly readonlyare recorded at the modifier.staticon one line andabstract xon the next is recorded atabstract.class C { static static a() {} }throwsUnexpected tokenin every mode, as onmain: TypeScript's parser rejects it as well, so it isn't a checker-level error.🤖 Generated with Claude Code
Note
Medium Risk
Changes core parser error handling for collect/loose tooling paths across many syntax edge cases; strict compile behavior is preserved but editor/formatter parsing semantics shift materially.
Overview
In
collectandloosemode (language server, Prettier, and other editor tooling), the parser now records a broad set of TypeScript checker-level mistakes inerrorsand keeps building an AST, instead of aborting on acorn/acorn-typescript parse errors that TypeScript only reports from its checker. Strict compiles are unchanged and still throw the same messages as before.The behavior is driven by a
CHECKER_LEVEL_ERRORSallow-list inplugin.js, wired through overriddenraise/raiseRecoverable, plus targeted recovery for cases where a bareraisereturn would break parsing (rest parameters after a rest element,constwithout an initializer,awaitin a namespace,#privateoutside a class, deduped error recording, and ambient trailing commas).Tests add a large matrix in
parser.test.js(worker parses with AST + positions), extendparse_in_worker_with_ast, updateparse.d.ts, and drop many Prettier known failures now that invalid-but-checker-level snippets format successfully.Reviewed by Cursor Bugbot for commit 8916d08. Bugbot is set up for automated code reviews on this repo. Configure here.