Repository navigation
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
Merged
Conversation
, #426) - A comment after a directive's keyword (and after `@for await`) is whitespace: `#isJSXControlFlowDirectiveAt` and the clause-keyword hint skip comments, not only whitespace (#477). - `yield` takes an argument that starts with `@` (`yield @{ … }`, `yield @if …`, `yield @dec class {}`): override `parseYield` for the `@` case (UPSTREAM sveltejs/acorn-typescript#128) (#547). - The `/>` branch of `getTokenFromCode` only fires in an open tag or where no expression can start, so `/>/` reads as a regular expression (#584). - `</` after an operand starts a closing tag, as in TSX, so a missing `}` before a closing tag reports `'}' expected.` at the `</` (#586). - An element, fragment, `@{ … }` value, or directive value isn't a left-hand-side expression: `parseSubscripts` stops after one unless it's parenthesized (#426). Both formatters keep the parentheses around a `@{ … }` value or a directive that is called, indexed, or a tag. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-tokenizer-context # Conflicts: # packages/tsrx/tests/utils/closing-brace.test.js
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.
Closes #477.
Closes #547.
Closes #584.
Closes #586.
Closes #426.
Five places where the parser read a token without the context TSX gives it. Each fix is in
TSRXPlugin(packages/tsrx/src/plugin.js); #426 also touches both formatters so a parenthesized TSRX value keeps its parentheses.The bugs and the fixes
#477: a comment after a directive keyword
@try /* c */ {,@if /* c */ (x),@for // cwith the(on the next line, and@switch /* c */ (x)failed withUnexpected keyword 'try'.#isJSXControlFlowDirectiveAtlooked for the{or(after the keyword withskip_whitespace_from, which skips whitespace but not comments, so the@trywasn't a directive.Fix: it skips comments too (
skip_space_and_comments_from), after the keyword and after theawaitof@for await, both positions. The@and the keyword still have to touch (@ /* c */ ifstill fails).I checked the clause keywords as asked.
@else,@else if,@empty,@pending,@catch,@caseand@default, with a comment before or after them, already parsed, because the tokenizer had skipped the comment before#eatJSXDirectiveClauseKeywordlooks. Tests now pin them. One related check had the same whitespace-only skip:#isUnprefixedDirectiveClauseContinuation, the hint for a clause written without its@. With a comment after the keyword (} else /* c */ {), it fell back toUnexpected tokenorMissing `@catch` or `@pending`. It now skips comments too, soExpected `@else` after `@if` block.still shows.Changed reading: in element children,
<div>@if /* c */ (x) { <b /> }</div>used to parse as the text@if (x)followed by the container{ <b /> }, and the comment was dropped. It now parses as the directive, the same as without the comment. This follows the rule that a comment is whitespace.#547:
yield @{ … }andyield @if …acorn-typescript's
parseYieldreads an argument only when the next token hasstartsExpr. Its@token doesn't have it, soyieldended before the@and the@failed. Plain TypeScript hits this too:yield @dec class {}fails in acorn-typescript, and TypeScript parses it, because itsisStartOfExpressionincludesAtToken.Override:
parseYield, marked// UPSTREAM(sveltejs/acorn-typescript#128), which I filed. It handles only the case where the next token is@, found with a lookahead that skips comments. Everything else goes tosuper.parseYield. Like TypeScript, a line break afteryieldstill ends it. The AST is what upstream would give: aYieldExpressionwithdelegate: falseand the expression asargument. So the override can be removed with no AST change.I checked the other places an expression starts for the same gap.
await,return,throw,=>, spread, unary operators,yield*, arguments, array and object members,${}, JSX containers,case,for … of,export defaultand class fields all accepted@{…}and directives already.Same cause, not overridden:
a < b > @{ … }, anda < b > @dec class {}in plain TypeScript. TypeScript reads these as(a < b) > …. acorn-typescript'sparseSubscripttakes<b>as type arguments becausetokenCanStartExpression(@)is false, and then fails at the@. Covering it here would mean overridingparseSubscript, a long method, for a comparison of a boolean with markup. So I left it to the upstream fix, and #128 covers both sites.#584: a regular expression that starts with
>getTokenFromCodetreated every/followed by>as the/>of an open tag. It popped contexts, pushedtc_oTagand clearedexprAllowed. Where a regular expression starts (const re = />/g), the regex was still read, but the corrupted context stack broke the tokens after it. A/>/in an attribute or child container failed at once.Fix: that branch only runs when a regex can't start there (
!this.exprAllowed) or when the current context is the open tag (tc_oTag). Otherwise the base tokenizer reads the regular expression.I checked this against the whole corpus below. I logged every time the branch fired: 1,700+ inputs, mostly tags. Every hit that parses had
tc_oTagon top orexprAllowedfalse. The one legitimate case without a tag context,(<div />) < <div />from Prettier's JSX tests, hasexprAllowedfalse. So the narrower condition keeps every hit that parses, and only drops the regex cases.The issue suggests checking for a
tc_oTaganywhere on the stack. That wouldn't fix<div title={/>/.source} />, where the open tag's context sits under the attribute's brace. It would also break that Prettier case.#586:
</after an operandAfter an operand,
<was less-than and/…a regular expression. So<p>{count</p>reportedUnterminated regular expressionafter the tag.Fix: as TypeScript's TSX scanner does, a
<right before/(not//or/*) outside a type starts a tag (jsxTagStart) even after an operand. The expression ends there. Inside a container, #590's rule then reports'}' expected.at the</, at the same position as TypeScript.a < /re/with a space is still less-than.a </re/.test(b)is now a syntax error at the</, as in TSX (TypeScript reports',' expectedat the same token, and TSRXUnexpected token).#426: what can follow an element
Following the user's decision, an element or fragment isn't a left-hand-side expression, as in TypeScript's
parseUpdateExpression.Fix: a
parseSubscriptsoverride returns an unparenthesized element as it is, the way acorn already treats an arrow function. So:(,[, or template literal on the next line starts a new statement (ASI);<b />.foo,<b />?.foo,<b />!,<b />(x),<b />[0]and<b />`t`fail at the token after the element, where TypeScript reports its error;(<b />).foo,(<b />)(x)and the rest still work, becauseparseParenAndDistinguishExpressionmarks the elementmetadata.parenthesized, and withpreserveParensthe base is aParenthesizedExpression.Operators are unchanged, including an operator on the next line (#496),
asandsatisfies, as are the line-start<rule and postfix++.Message: TypeScript's message depends on the surrounding list (
',' expectedin a declaration,';' expectedin a statement,')' expectedin parentheses). Reproducing that would mean reimplementing its list-specific expectations. TSRX gives acorn'sUnexpected tokenat TypeScript's position.TSRX values: the same rule applies to a
@{ … }value and to@if,@for,@switchand@tryused as expressions. The override usesis_tsrx_render_output_node, which covers elements, fragments,<style>, code blocks and directives. Today, after any of these, the parser read calls, members, indexes, non-null assertions and tagged templates, across line breaks too:const v = @if (x) { <b /> }followed by(foo)on the next line called the directive. I chose the element rule for them because they end in}and the formatters lay them out like JSX, over several lines in parentheses. A(on the next line has the same hazard as after an element. A@{ … }function body isn't a subscript base, so it's unaffected.Formatters: both already printed an element before a subscript with parentheses, matching Prettier's
typescriptoutput ((<b>x</b>)(foo), and(\n <div>…\n).foowhen it breaks). They dropped the parentheses around a TSRX value used as a callee:(@{ <b /> })(x)printed@{…}(x), which the new rule rejects on the next pass. Both now print them the same way as for JSX:(@{\n <b />\n})(x);In
@tsrx/prettier-pluginthis is anodeNeedsParenscase; intsrx-prettier-pluginit issubscriptBaseKindinprintNode. For the #426 examples,tsrx-prettier-pluginoutput matches Prettier'stypescriptoutput, and new tests check both formatters.Tests that pinned the old readings
packages/tsrx/tests/utils/parser.test.js:TaggedTemplateExpressionon the element ([Bug]: core: A call, index, or template literal after an element continues the element, unlike TypeScript #426). It is now "ends the statement at an element before a template literal on the next line".<value> /…/in the setup section as a less-than against a regex" parsed3</div>/as3 < /div>/([Bug]: tsrx-core: A missing}before a closing tag reads</as less-than and a regular expression, unlike TSX #586). It now uses3 < /div>/with a space. The no-space form is in the new test file and fails at the</.packages/tsrx/tests/utils/closing-brace.test.js:x = <div>{a</div>;was in fix(core): report '}' expected for a missing closing brace (#583) #590's list of shapes that fail first for another reason (Unterminated regular expression (1:13)). It moved to the container cases, now'}' expected.at the</, with two more shapes.New tests:
packages/tsrx/tests/utils/tokenizer-context.test.jscovers all five issues in strict, collect and loose mode, in a worker.upstream-parser-workarounds.test.jscoversyield @dec class {}(Deno support: how to get the type checking working under Deno? #128).yield @{…}, and a comment after a directive keyword.Verification
Comparison. I compared
main(03de6568, after merging it into this branch) with this branch, parsing strict and with{ collect: true, errors: [], comments: [], preserveParens: true }, in 4 worker threads with a hard timeout. There were 17,777 inputs:.tsrxfiles;readSnapshotEntries/readFormatCase);packages/*/src/**/*.jsfiles, added for [Bug]: core: A regular expression that starts with > fails to parse unless it ends the input #584.Results:
.tsrxfile and no Prettier input or output changed at all.autoInsertPlugin.test.jsfragments ($0</div>, …) and one rendered-HTML string in the formatter tests (a <b>1</b> b):Unterminated regular expressionbecameUnexpected tokenat the</([Bug]: tsrx-core: A missing}before a closing tag reads</as less-than and a regular expression, unlike TSX #586). These are editor-text and markup strings, not parsed as programs by their tests.x = <div>{a</div>;:'}' expected. (1:11)instead ofUnterminated regular expression (1:13)([Bug]: tsrx-core: A missing}before a closing tag reads</as less-than and a regular expression, unlike TSX #586).packages/tsrx/src/utils/escaping.js(const CLOSE_TAG_REGEX = />/g;) now parses ([Bug]: core: A regular expression that starts with > fails to parse unless it ends the input #584).3</div>/source fromparser.test.jsnow throws at the</([Bug]: tsrx-core: A missing}before a closing tag reads</as less-than and a regular expression, unlike TSX #586), as described above.Tests.
vitest run --maxWorkers=4passes for these projects:tsrx-utilstsrx-analyzeprettier-plugintsrx-prettier-pluginlanguage-servertsrx-reacttsrx-preacttsrx-solidtsrx-vuetsrx-honoThe Prettier known-failures list didn't change.
Other checks.
pnpm typecheck: all 36 steps pass.tsrx-tscisn't linked afterpnpm install --ignore-scripts, so I built@tsrx/typescript-pluginand ran the@tsrx/vite-plugin-honotypecheck:testsstep throughpackages/typescript-plugin/dist/tsc.js.types/parse.d.tsnow givesparseSubscriptsacorn's signature (base, startPos, startLoc, noCalls, forInit); it listedparseSubscript's.pnpm format(no other diffs),pnpm format:checkandpnpm changeset:checkpass. The changeset is apatchfor@tsrx/coreand@tsrx/prettier-plugin.@tsrx/react:yield @{ <div /> }gives the same code asyield (@{ <div /> }).Findings
a < b > @{ … }anda < b > @dec class {}(see [Bug]: Parser rejects unparenthesized TSRX expressions after yield #547 above;@isn't read as the start of an expression afteryieldor aftera < b >sveltejs/acorn-typescript#128 covers both).yield @foo;now reportsLeading decorators must be attached to a class declaration.at the token after the decorator instead ofUnexpected tokenat the@, becauseyieldnow reads a decorator there.yield @;reportsUnexpected tokenone column later.<b />++still reportsAssigning to rvalue, where TypeScript reports',' expected. TypeScript doesn't read a postfix operator after an element either, but postfix++and--were left out of [Bug]: core: A call, index, or template literal after an element continues the element, unlike TypeScript #426's scope.🤖 Generated with Claude Code
Note
Medium Risk
Changes core parsing and tokenization behavior (including breaking reads like tagged templates after elements); format output may shift for parenthesized TSRX values, but corpus comparison reported no AST changes on existing inputs.
Overview
Aligns the TSRX parser and formatters with TSX-style token context so five edge cases parse and print correctly.
Parser (
@tsrx/core): Comments after directive keywords (@try /* c */ {, etc.) are skipped like whitespace, so directives parse in markup children instead of as text.yieldaccepts@-starting arguments (yield @{ … }, directives, decorated classes)./>only closes tags when a regexp cannot start; patterns like/>/gparse as regex.</after an operand starts a closing tag (better'}' expected.for{count</p>). Elements, fragments,@{…}, and directive values are not left-hand-side expressions—no bare.foo/(x)/[0]/tagged templates; ASI applies for(/[/templates on the next line.Formatters: Both Prettier plugins keep parentheses around TSRX values used as callees, members, indexes, non-null assertions, or tag templates—matching JSX element behavior.
Patch releases for
@tsrx/coreand@tsrx/prettier-plugin; broad new tests intokenizer-context.test.jsand formatter snapshots.Reviewed by Cursor Bugbot for commit 9181a6d. Bugbot is set up for automated code reviews on this repo. Configure here.