Skip to content

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
leonidaz merged 3 commits into
mainfrom
fix/core-tokenizer-context
Sep 25, 2026

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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 // c with the ( on the next line, and @switch /* c */ (x) failed with Unexpected keyword 'try'. #isJSXControlFlowDirectiveAt looked for the { or ( after the keyword with skip_whitespace_from, which skips whitespace but not comments, so the @try wasn't a directive.

Fix: it skips comments too (skip_space_and_comments_from), after the keyword and after the await of @for await, both positions. The @ and the keyword still have to touch (@ /* c */ if still fails).

I checked the clause keywords as asked. @else, @else if, @empty, @pending, @catch, @case and @default, with a comment before or after them, already parsed, because the tokenizer had skipped the comment before #eatJSXDirectiveClauseKeyword looks. 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 to Unexpected token or Missing `@catch` or `@pending` . It now skips comments too, so Expected `@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 @{ … } and yield @if …

acorn-typescript's parseYield reads an argument only when the next token has startsExpr. Its @ token doesn't have it, so yield ended before the @ and the @ failed. Plain TypeScript hits this too: yield @dec class {} fails in acorn-typescript, and TypeScript parses it, because its isStartOfExpression includes AtToken.

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 to super.parseYield. Like TypeScript, a line break after yield still ends it. The AST is what upstream would give: a YieldExpression with delegate: false and the expression as argument. 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 default and class fields all accepted @{…} and directives already.

Same cause, not overridden: a < b > @{ … }, and a < b > @dec class {} in plain TypeScript. TypeScript reads these as (a < b) > …. acorn-typescript's parseSubscript takes <b> as type arguments because tokenCanStartExpression(@) is false, and then fails at the @. Covering it here would mean overriding parseSubscript, 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 >

getTokenFromCode treated every / followed by > as the /> of an open tag. It popped contexts, pushed tc_oTag and cleared exprAllowed. 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_oTag on top or exprAllowed false. The one legitimate case without a tag context, (<div />) < <div /> from Prettier's JSX tests, has exprAllowed false. So the narrower condition keeps every hit that parses, and only drops the regex cases.

The issue suggests checking for a tc_oTag anywhere 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 operand

After an operand, < was less-than and /… a regular expression. So <p>{count</p> reported Unterminated regular expression after 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 ',' expected at the same token, and TSRX Unexpected 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 parseSubscripts override returns an unparenthesized element as it is, the way acorn already treats an arrow function. So:

  • a (, [, 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, because parseParenAndDistinguishExpression marks the element metadata.parenthesized, and with preserveParens the base is a ParenthesizedExpression.

Operators are unchanged, including an operator on the next line (#496), as and satisfies, as are the line-start < rule and postfix ++.

Message: TypeScript's message depends on the surrounding list (',' expected in a declaration, ';' expected in a statement, ')' expected in parentheses). Reproducing that would mean reimplementing its list-specific expectations. TSRX gives acorn's Unexpected token at TypeScript's position.

TSRX values: the same rule applies to a @{ … } value and to @if, @for, @switch and @try used as expressions. The override uses is_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 typescript output ((<b>x</b>)(foo), and (\n <div>…\n).foo when 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:

  • hugging the callee: (@{\n <b />\n})(x);
  • breaking inside the parentheses before a member access, index, non-null assertion, or tag.

In @tsrx/prettier-plugin this is a nodeNeedsParens case; in tsrx-prettier-plugin it is subscriptBaseKind in printNode. For the #426 examples, tsrx-prettier-plugin output matches Prettier's typescript output, and new tests check both formatters.

Tests that pinned the old readings

New tests:

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:

Results:

Tests. vitest run --maxWorkers=4 passes for these projects:

Project Passed Skipped
tsrx-utils 1,037 0
tsrx-analyze 143 0
prettier-plugin 2,489 0
tsrx-prettier-plugin 2,066 17
language-server 80 0
tsrx-react 584 6
tsrx-preact 525 6
tsrx-solid 560 15
tsrx-vue 540 15
tsrx-hono 800 18

The Prettier known-failures list didn't change.

Other checks.

  • pnpm typecheck: all 36 steps pass. tsrx-tsc isn't linked after pnpm install --ignore-scripts, so I built @tsrx/typescript-plugin and ran the @tsrx/vite-plugin-hono typecheck:tests step through packages/typescript-plugin/dist/tsc.js. types/parse.d.ts now gives parseSubscripts acorn's signature (base, startPos, startLoc, noCalls, forInit); it listed parseSubscript's.
  • pnpm format (no other diffs), pnpm format:check and pnpm changeset:check pass. The changeset is a patch for @tsrx/core and @tsrx/prettier-plugin.
  • The [Bug]: Parser rejects unparenthesized TSRX expressions after yield #547 reproduction now compiles with @tsrx/react: yield @{ <div /> } gives the same code as yield (@{ <div /> }).

Findings

🤖 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. yield accepts @-starting arguments (yield @{ … }, directives, decorated classes). /> only closes tags when a regexp cannot start; patterns like />/g parse 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/core and @tsrx/prettier-plugin; broad new tests in tokenizer-context.test.js and formatter snapshots.

Reviewed by Cursor Bugbot for commit 9181a6d. Bugbot is set up for automated code reviews on this repo. Configure here.

leonidaz and others added 3 commits September 25, 2026 16:06
, #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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment