Repository navigation
fix(core): read the text of elements in setup statements as template text, and report syntax errors in element values (#636, #638) - #657
Merged
Conversation
…text, and report syntax errors in element values (#636, #638) Text in an element in a setup statement of a `@{ … }` or directive body, or of an `@case`, was read as code: `#shouldReadTemplateRawTextToken` and the closing tag's `inside_parent_template` checked `#templateScriptParsingDepth` (and `#parsingJSXSwitchCaseScriptStatementDepth`) for the whole statement. Each element now records both depths when it starts, next to `this.labels` (`#elementStarts`), and the gates apply only to code that started after the innermost element: a setup statement's own tokens, or a spread attribute's argument. acorn-typescript tries a value that starts with `<` as an element and undoes the attempt when it fails, treating the token context stack as append-only. TSRX shortened `this.context` directly, so a syntax error after a closing tag surfaced as `A parse effect shortened an append-only array` or `A parse branch shortened the token context stack below its checkpoint`. Every in-place shortening now goes through `parseEffects` (`#popContext`, `#truncateContext`), the self-closing `/>` rule no longer drains the stack for the `/` of `</`, and a tag's missing `>` reports `'>' expected.` as TypeScript does. 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.
Closes #636.
Closes #638.
Text in an element inside a setup statement now reads as it does everywhere else, and renders on every target what the same TSX renders. A syntax error in an element that is a value reports that error, instead of acorn-typescript's internal messages about its rollback. This builds on #641, which is on
main.The bugs
@{ … }body, of a directive body, or of an@case.#parseCodeBlockSetupStatementraises#templateScriptParsingDepthfor the whole statement, and an@case's setup statement raises#parsingJSXSwitchCaseScriptStatementDepth.#shouldReadTemplateRawTextTokenreturned false while either was above 0. The closing tag'sinside_parent_templaterequired#templateScriptParsingDepth === 0.Unexpected character.const a = <span>Hello<b /></span>;) failed. It overflowed the stack before fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) #641, and after fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) #641 it failed with [Bug]: tsrx-core: A syntax error right after an element's closing tag fails with acorn-typescript's internal 'A parse effect shortened an append-only array' #638'sA parse branch shortened the token context stack below its checkpoint.return, an argument, an array or object, a conditional, an arrow, a nested function or component, and an@if,@for,@switch, or@{ … }value.parseMaybeAssigntries a value that starts with<as an element and undoes the attempt when it fails. It treats the token context stack as append-only unless a shortening goes throughparseEffects.this.contextin place in 26 places, such as the closing tag'sthis.context.length = context_depth.A parse effect shortened an append-only arrayor… below its checkpoint. Examples are a closing tag's missing>(const el = <div>x</div;) and [Bug]: tsrx-core: Text in an element in a setup statement is read as code: leading spaces are lost, and text right before a tag overflows the stack #636's no-progress error.x = import(</>);still failed, now withRangeError: Invalid array length. After the failed element attempt, acorn-typescript tries a generic arrow and reads the/of</again. TSRX's rule that drops contexts before a self-closing/>fired for that/, drained the stack, and acorn-typescript then truncated it to a negative length.The fix
All in
packages/tsrx/src/plugin.js:parseElementrecords the two depths when each element starts, next tothis.labelsfrom fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) #641 (#elementLabelsbecomes#elementStarts, read through#elementStart).#shouldReadTemplateRawTextTokenbails for a setup statement only when a depth is above its value at the innermost element's start. That is the statement's own code, or a spread attribute's argument (<div {...props}>), which raises#templateScriptParsingDepthwithout hiding#path. An element opened in the statement reads its children as text.inside_parent_templateasks the same of the innermost template ancestor.#insideSwitchStartedAfter.this.contextgoes throughparseEffects. This covers eachpop(),length =,length -=, and thespliceinparseElement. It uses#popContextand#truncateContext, which callparseEffects.pop/truncateas acorn-typescript's ownparseMaybeAssigndoes.parseEffectsrecords nothing then.this.context = …swaps around directive bodies and setup statements replace the array and never shorten the one an attempt recorded, so they stay./>rule ingetTokenFromCodeskips a/right after a tag start. That/is the/of a closing tag (</>).>reports'>' expected.(TS1005), as TypeScript does, instead ofUnexpected token, at the same position.expectalready does this for'}' expected.. This covers a closing tag's>and a self-closing tag's>after its/.>(<div / >,<div /\n>) reads as code in a value.#shouldReadTemplateRawTextTokenrecognized a self-closing tag's end only when/and>touched.const a = <div /\n>;followed by another statement, which parses onmainonly because the whole statement was code, fails. It already failed like that at the top level and in a plain function's statements (Unexpected token, or the next token read as text), and now parses there too./in the opening tag of an element in a template is read as text:<div / >and division in a spread attribute fail #655.It's narrow in that each gate still applies wherever it did, except to an element opened inside the code the gate describes. The context helpers change nothing outside a failed attempt.
No override: both causes are in TSRX. Plain acorn-typescript reports these syntax errors. One upstream cause turned up: at the top of a statement,
x = </>;fails withRangeError: Invalid array lengthin plain acorn-typescript too. I filed it as sveltejs/acorn-typescript#134 and the TSRX override as #653. It's unchanged here (Findings).Rendered output on the targets
The shared runtime suite from #615 and #641 (
packages/tsrx/tests/shared/runtime/jsx-text-whitespace*) gets 10 cases, rendered on React, Preact, Solid, Vue, and Hono in jsdom. Each compares an element'sinnerHTMLwith what React renders for the same TSX. The elements are in setup statements of a component:const;@ifvalue;@{ … }value;@case;On
mainthe fixture doesn't compile:Unexpected token (61:54), at the<b />after4. A shared compile test checks the same text in each compiler's output.Formatters
I generated the 464 shapes of #641's TSRX-against-TSX matrix in 28 setup-statement places (12,992 sources), and in 6 template places for comparison (2,784). Both formatters format every source, and their output parses.
@tsrx/prettier-pluginchanges the rendered text of none of them. 34 setup sources need a second pass, all in 5 shapes that need one in template places too, onmainand here: a block comment on the opening tag's line ([Bug]: @tsrx/prettier-plugin: A comment on its own line before a multi-line JSX child keeps the text after the child on its closing line, and needs a second format pass #640) and comments in an element in a container ([Bug]: tsrx-core, @tsrx/prettier-plugin: A block comment between children of an element in a {…} container is attached to the element's body, so the formatter moves it before the closing tag #637).tsrx-prettier-pluginis stable on every source. 250 setup sources change what they render, all in the 9 block-comment shapes that change the same way in template places ([Bug]: tsrx-prettier-plugin changes what an element renders when a block comment sits between its children #639).mainand here.Verification
AST and error comparison,
main(8eeec666) against this branch. Each input parses strict, with{ collect: true, errors: [], comments: [], preserveParens: true }, and with{ loose: true }, in 4 worker threads with a hard timeout. The inputs are 18,213: the 70 tracked.tsrxfiles, the input and output of all 2,040 Prettier snapshot cases (readSnapshotEntries/readFormatCase), and 14,063 distinct string literals from test files.<style apply={theme} /at the end of the input (language-servertests) reports'>' expected. (5:24)instead ofUnexpected token (5:24).Mutated inputs. 30,008 inputs made from the same corpus (truncated, a span deleted, or a line break, comment, tag, brace, or non-breaking space inserted), in the three modes. No hangs, and nothing that parsed fails now. 460 inputs change:
Unexpected tokenbecomes'>' expected.at the same position. The sampled ones match TypeScript's TS1005 position.… shortened …) becomes a syntax error. 18 of them are'>' expected.and 7 areUnexpected token,Unterminated comment,Unterminated regular expression, or an unclosed tag. None of these messages remain.<b /\n>(x = () => <b /\n>;).<Bar / >;,<Bar /\n>;, and<div / >\n&& b;at the top level read the token after the tag as code, as after<Bar />. Before,;and&& b;were JSX text.raisedAt).const App = async<div />;reportsUnexpected token (1:23), TypeScript's position, instead of(1:18).<style>at the end of a setup statement reports the unclosed tag in strict mode and'}' expected.orUnexpected tokenin collect and loose mode, as in a plain function or template, instead ofUnterminated JSX contents.iv class={…}>in a fragment in a setup statement's function reports the>in text (Did you mean >), as TSX does, instead of a mismatched closing tag.const el = <div attr= <b>// c\n"foo">text</div>;from an earlier mutation run runs out of memory onmainand here ([Bug]: tsrx-core: An element as an attribute value without braces never finishes parsing when a comment starts its text #654).TSRX against TSX. 25,984 generated sources: fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) #641's 464 shapes in 56 places. Those are fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) #641's 29 plus 27 setup-statement places, and I compare the text children as fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) #641 does.
let,returnin a declared function and in the body, an argument, an array, an object, a conditional, an arrow and an arrow block,@if,@for,@switch, and@{ … }values, the setups of@ifand@{ … }values, a component and a component's setup, a nested element, a container, an attribute value, and a spread argument in a setup statement; a spread argument in a template; and the setups of@if,@for,@{ … }child,@trybodies and a function in an@case.main: 6,876 mismatches, 4,060 of them errors, in the 28 setup places (229 each) and the 2 spread places (232 each).main. An element in a spread argument is parsed as plain JSX, so a comment between its children is text ([Bug]: tsrx-core: An element in a spread attribute's argument is parsed as plain JSX: comments and template syntax read as text #656). None in the other 54 places.Tests. I ran
vitest run --maxWorkers=4fortsrx-utils,tsrx-analyze,tsrx-vite, the five compilers, the five runtime projects,prettier-plugin, andtsrx-prettier-plugin: 53 files, 9,420 passed, 77 skipped. New tests:parse_in_worker_with_ast;<div / >values;parse_in_worker;All of them except two guards fail on
main: the spread attribute test, and the no-progress error in a setup statement, which reportsUnexpected token (2:14)onmaintoo.pnpm typecheckpasses.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, then the steps after it.pnpm formatchanged nothing else, andpnpm format:checkandpnpm changeset:checkpass. Changeset:patchfor@tsrx/core.Findings
Filed, with other causes:
RangeError: Invalid array length#653:x = </>;,export default </>;fail withRangeError: Invalid array length.RangeError: Invalid array lengthwithjsxsveltejs/acorn-typescript#134. After the failed element attempt,parseMaybeAssignpops the tag start's contexts. Its generic-arrow attempt then reads the/after the tag start, andupdateContexttruncates the stack by two again.main. [Bug]: tsrx-core: A closing tag where a statement's expression starts fails withRangeError: Invalid array length#653 is theUPSTREAM(sveltejs/acorn-typescript#134)override ofupdateContext.<div attr=<b>/* c */</b> />) never finishes parsing when a comment starts its text. It's parsed by acorn-typescript's JSX parser, but its children read as TSRX template text, which gives an empty token at a comment. The children loop reads that token forever, out of memory./in the opening tag of an element in a template is read as text:<div / >and division in a spread attribute fail #655: in the opening tag of an element in a template, a/is read as template text. So<div / >as a template child isn't self-closing, and a division in a spread attribute's argument ({...{ a: b / 2 }}) fails. The value-position half of<div / >is fixed here.@ifin it is text and a container. Fixing it changes what such markup means, so it needs a decision.For the user:
'>' expected.A tag's missing>now reports TypeScript's message instead ofUnexpected token, at the same position. It's the bulk of the mutated-input changes (411). If you'd rather keepUnexpected tokenthere, it's thejsxTagEndbranch inexpect.🤖 Generated with Claude Code
Note
Medium Risk
Touches core TSRX parser token/context logic used for all JSX and setup blocks; behavior changes are broad but covered by extensive tests.
Overview
Fixes template text parsing for JSX inside setup statements (
@{ … }, directive bodies,@case) so elements inconst,return, nested functions, control-flow values, etc. keep whitespace and adjacent text like normal template markup—instead of treating that region as plain script (lost spaces, NBSP/Hello<b />failures).The parser now records per-element setup depths (
#elementStarts) and only blocks raw template text for code that started after that element opened; closing-tag parent detection uses the same rule.Context stack mutations route through
#popContext/#truncateContextandparseEffects, so failed speculative<parses surface real syntax errors instead of acorn-typescript rollback internals. Missing tag>reports'>' expected.; tokens after<div / >in value position tokenize as code.Adds parser, compile, and runtime whitespace coverage for setup-statement cases.
Reviewed by Cursor Bugbot for commit 5133ae4. Bugbot is set up for automated code reviews on this repo. Configure here.