Skip to content

refactor(core): simplify lazy pattern parsing and extend valid positions - #11

Merged
leonidaz merged 6 commits into
mainfrom
refactor/simplify-lazy-arrow-parsing
Aug 27, 2026
Merged

leonidaz merged 6 commits into
mainfrom
refactor/simplify-lazy-arrow-parsing

Conversation

@leonidaz

@leonidaz leonidaz commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up review of #7 and #9.

Lazy pattern parsing (#9 rework)

Replaces the candidate-pattern stack, parseSubscript override, and arrow-only containment validation with Acorn's own DestructuringErrors protocol — the same mechanism Acorn uses for the analogous {a = b} shorthand ambiguity ("valid if this becomes a pattern, error if it stays an expression"):

  • parseExprAtom parses &{…}/&[…] wherever a DestructuringErrors context exists (exactly the pattern-ambiguous positions) and records it as a pending error (lazyBindingPos).
  • toAssignable resolves the pending record when the pattern lands in a pattern-forming slot of a converted binding/assignment target (pattern_position_contains_lazy — object property values, array elements, assignment-default lefts, rest arguments, looking through parentheses and the TypeScript wrappers toAssignable itself unwraps, so [&{ a }!] = arr, [&{ a } as T] = arr, and satisfies forms work, parenthesized or not). A lazy pattern reachable only through an expression position inside a target — e.g. &{ a }.b = x — keeps its record and raises. The walk fails closed and runs only when a conversion actually carries a pending lazy record, not on every paren.
  • checkExpressionErrors — which Acorn already calls in every lane that stays an expression, sync and async, generics included — raises for expression uses.

Because validation now rides the pattern-conversion lanes instead of an arrow-only allowlist, lazy patterns become valid anywhere a destructuring pattern is valid:

  • nested in destructuring assignment targets: [&{ name }] = pairs; and the parenthesized forms ({ pair: &{ a } } = obj) / (&{ name } = obj) (the object-rooted spelling only exists parenthesized, since a bare { starts a block; the shared transform already handles these — { pair: &[a, b] } = obj → { pair: __lazy0 } = obj)
  • as for–of / for–in / @for loop targets: @for (&{ label } of items) works end-to-end in react, solid, and vue today because the @for lowering turns the target into the iteration callback's parameter, where the existing lazy-param transform picks it up ((__lazy0) => __lazy0.label).

Expression uses (foo(&{a}), const v = &{a}, &{ a }.b = x) now fail with a descriptive error instead of a generic unexpected-token failure.

Line-count-wise this ends up near parity with #9 (vs #9's +98 in plugin.js for arrow params alone) — the wins are elsewhere: a substantially wider grammar for the same budget, no per-paren stack/try–finally bookkeeping, validation only on conversions that actually carry a pending lazy pattern, and expression-lane coverage (async, generic, nested arrows, defaults) by construction from Acorn's protocol rather than by enumerating lanes. The toAssignable refinements came out of review on this PR — all three Bugbot findings were verified real and fixed.

Export scope lookup cache (#7 tidy)

Moves the per-scope name-set sync into a #scopeDeclaredNames helper, drops the rebuild branch for shrunken scope arrays (Acorn only ever appends to a scope's lexical/var arrays during its lifetime, so it was unreachable), and types the backing WeakMap.

Known gaps (pre-existing, transformers to follow up)

Plain JS for (const &{ a } of items) in code blocks parses but the shared transform silently drops the lazy flag (emits eager destructuring); if (cond) &{ x } = obj(); emits invalid output (if (cond) const __lazy0 = …). Both predate this PR — the parser now also accepts bare for (&{ a } of items), which awaits the same transform support. See issue #12.

Validation

  • pnpm test: 76/76 test files pass (includes new parser tests — valid and invalid positions, parenthesized targets, expression-position leaks, TypeScript-wrapped targets (!, as, satisfies) — and a shared @for lazy-target compile test exercised by all four targets)
  • pnpm typecheck, pnpm format:check, pnpm changeset:check: clean

Note

Medium Risk
Changes core parser binding/assignment validation in plugin.js; behavior is broad but covered by new parser and compile tests, with transform gaps for some plain-JS loop forms noted as pre-existing.

Overview
Lazy &{…} / &[…] parsing is reworked to follow Acorn’s DestructuringErrors flow (same idea as ambiguous {a = b} shorthand): parseExprAtom records a pending lazyBindingPos when & opens a pattern inside a destructuring context, toAssignable clears it only when pattern_position_contains_lazy finds the pattern in a real binding/assignment slot (including through parens and TS wrappers like [&{ a } as T] = arr), and checkExpressionErrors raises "Lazy binding patterns are only valid as binding or assignment targets" for expression uses (foo(&{a}), &{a}.b = x). The old per-paren #potentialLazyArrowPatterns stack, parseSubscript hook, and arrow-only validation are removed; checkLValPattern unwraps TS expression wrappers so wrapped destructuring targets validate correctly.

That widens the grammar to nested destructuring assignment targets ([&{ name }] = pairs, ({ pair: &{ a } } = obj)) and for-of / for-in / @for loop targets (@for (&{ label } of items)), with a new shared compile test for @for lazy targets.

A small export lookup tidy moves scope name syncing into #scopeDeclaredNames and types the backing WeakMap. Types add lazyBindingPos and preserveTypeScriptWrapper on toAssignable.

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

Replace the candidate-pattern stack, parseSubscript override, and recursive
containment validation with Acorn's own DestructuringErrors protocol — the
mechanism it already uses for the analogous `{a = b}` shorthand ambiguity.
parseExprAtom records a pending lazy pattern on the active context; pattern
conversion accepts it, and checkExpressionErrors raises for uses that stay
expressions.

Since validation now rides the pattern-conversion lanes instead of an
arrow-only allowlist, lazy patterns become valid anywhere a destructuring
pattern is: nested in destructuring assignment targets ([&{ name }] = pairs)
and as for-of/for-in/@for loop targets (@for (&{ label } of items) lowers to
the iteration callback parameter and rides the existing lazy-param
transform). Expression uses now fail with a descriptive error instead of a
generic unexpected-token failure.
Move the per-scope name-set sync into a #scopeDeclaredNames helper and drop
the rebuild branch for shrunken scope arrays: Acorn only ever appends to a
scope's lexical and var arrays during the scope's lifetime, so the branch
was unreachable. Also type the backing WeakMap.
@vercel

vercel Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
tsrx-website Ready Ready Preview Aug 27, 2026 4:24pm
tsrx-website-mcp Ready Ready Preview Aug 27, 2026 4:24pm

Request Review

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Stale lazy pattern pending error
    • parseMaybeAssign now clears lazyBindingPos after converting a construct to an assignment, so parenthesized targets such as ({ pair: &{ a } } = obj) no longer raise a stale expression-position error.

Create PR

Or push these changes by commenting:

@cursor push 83ca053922
Preview (83ca053922)
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
@@ -3270,6 +3270,29 @@
 			}
 
 			/**
+			 * Acorn resets `shorthandAssign` once `parseMaybeAssign` converts the
+			 * left-hand side through `toAssignable`. Do the same for a recorded
+			 * lazy binding pattern so enclosing `checkExpressionErrors` calls
+			 * (parenthesized assignment, call arguments, …) do not treat a valid
+			 * target as an expression-position error.
+			 *
+			 * @type {Parse.Parser['parseMaybeAssign']}
+			 */
+			parseMaybeAssign(forInit, refDestructuringErrors, afterLeftParse) {
+				const expr = super.parseMaybeAssign(forInit, refDestructuringErrors, afterLeftParse);
+				if (
+					expr &&
+					expr.type === 'AssignmentExpression' &&
+					refDestructuringErrors &&
+					get_lazy_binding_pos(refDestructuringErrors) >=
+						/** @type {AST.NodeWithLocation} */ (expr.left).start
+				) {
+					refDestructuringErrors.lazyBindingPos = -1;
+				}
+				return expr;
+			}
+
+			/**
 			 * A recorded lazy binding pattern that never became a binding or
 			 * assignment target is a pending error, exactly like `{a = b}` shorthand
 			 * outside a destructuring pattern. Acorn calls this in every context that

diff --git a/packages/tsrx/tests/utils/parser.test.js b/packages/tsrx/tests/utils/parser.test.js
--- a/packages/tsrx/tests/utils/parser.test.js
+++ b/packages/tsrx/tests/utils/parser.test.js
@@ -3217,6 +3217,19 @@
 		const assignment = as_type(statement.expression, 'AssignmentExpression');
 		const target = as_type(assignment.left, 'ArrayPattern');
 		expect(as_type(target.elements[0], 'ObjectPattern').lazy).toBe(true);
+
+		// Object destructuring assignment must be parenthesized (a leading `{` is a
+		// block). The shared DestructuringErrors context is still live after the
+		// `=` conversion, so the pending lazy-pattern flag must be cleared.
+		const object_ast = parseModule(`({ pair: &{ a } } = obj);`, 'App.tsrx');
+		const object_assignment = as_type(
+			firstStatement(object_ast, 'ExpressionStatement').expression,
+			'AssignmentExpression',
+		);
+		const object_target = as_type(object_assignment.left, 'ObjectPattern');
+		expect(
+			as_type(as_type(object_target.properties[0], 'Property').value, 'ObjectPattern').lazy,
+		).toBe(true);
 	});
 
 	it('parses lazy binding patterns as for-of and for-in loop targets', () => {

You can send follow-ups to the cloud agent here.

Comment thread packages/tsrx/src/plugin.js Resolved
…nversion

A lazy binding pattern recorded inside a node that toAssignable converts
into an assignment target has landed in a valid position, so its pending
error must not survive the conversion — otherwise the enclosing context's
checkExpressionErrors still rejects it, making object-rooted targets like
({ pair: &{ a } } = obj) unwritable (a bare { starts a block, so the
parenthesized form is the only spelling). Mirrors Acorn's shorthandAssign
reset for shorthand that ends up inside a converted left-hand side.

The record points at the pattern's &, one character before the pattern node
(parseBindingAtom consumes it before starting the node), so the containment
check extends to node.start - 1.
Comment thread packages/tsrx/src/plugin.js Resolved
…sitions

The span-containment clear in toAssignable also resolved lazy patterns
reached through expression positions inside a valid assignment target —
(&{ a }.b = x) parsed and produced an ObjectPattern as a member
expression's object. Replace the span check with a walk of the
pattern-forming slots of the pre-conversion node (object/array
properties and elements, assignment defaults, rest arguments): a lazy
pattern found there resolves its pending record; one reachable only
through an expression position keeps it and raises.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Lazy walk skips TypeScript wrappers
    • pattern_position_contains_lazy now follows TSAsExpression, TSTypeAssertion, and TSNonNullExpression the same way toAssignable unwraps them, so wrapped lazy patterns in real pattern slots clear lazyBindingPos instead of being rejected as expression uses.

Create PR

Or push these changes by commenting:

@cursor push 598f99805e
Preview (598f99805e)
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
@@ -165,7 +165,13 @@
 		case 'RestElement':
 			return pattern_position_contains_lazy(node.argument, pos);
 		case 'ParenthesizedExpression':
-			return pattern_position_contains_lazy(node.expression, pos);
+		case 'TSAsExpression':
+		case 'TSTypeAssertion':
+		case 'TSNonNullExpression':
+			return pattern_position_contains_lazy(
+				/** @type {{ expression: AST.Node }} */ (node).expression,
+				pos,
+			);
 		default:
 			return false;
 	}

diff --git a/packages/tsrx/tests/utils/parser.test.js b/packages/tsrx/tests/utils/parser.test.js
--- a/packages/tsrx/tests/utils/parser.test.js
+++ b/packages/tsrx/tests/utils/parser.test.js
@@ -3252,8 +3252,32 @@
 		expect(() => parseModule(`({ k: &{ a }.b } = obj);`, 'App.tsrx')).toThrow(
 			/Lazy binding patterns are only valid as binding or assignment targets/,
 		);
+		expect(() => parseModule(`((&{ a }!).b = x);`, 'App.tsrx')).toThrow(
+			/Lazy binding patterns are only valid as binding or assignment targets/,
+		);
+		expect(() => parseModule(`({ k: &{ a }!.b } = obj);`, 'App.tsrx')).toThrow(
+			/Lazy binding patterns are only valid as binding or assignment targets/,
+		);
 	});
 
+	it('parses lazy binding patterns wrapped in TypeScript non-null assertions', () => {
+		// Non-null assertions are valid assignment targets; nested conversion
+		// does not pass refDestructuringErrors, so the walk must look through
+		// those wrappers itself.
+		expect(() => parseModule(`([&{ a }!] = pairs);`, 'App.tsrx')).not.toThrow();
+		expect(() => parseModule(`({ pair: &{ a }! } = obj);`, 'App.tsrx')).not.toThrow();
+		expect(() => parseModule(`(&{ name }! = obj);`, 'App.tsrx')).not.toThrow();
+
+		const ast = parseModule(`({ pair: &{ a }! } = obj);`, 'App.tsrx');
+		const statement = firstStatement(ast, 'ExpressionStatement');
+		const assignment = as_type(statement.expression, 'AssignmentExpression');
+		const target = as_type(assignment.left, 'ObjectPattern');
+		const pair = as_type(target.properties[0], 'Property');
+		expect(
+			as_type(as_type(pair.value, 'TSNonNullExpression').expression, 'ObjectPattern').lazy,
+		).toBe(true);
+	});
+
 	it('parses lazy binding patterns as for-of and for-in loop targets', () => {
 		const for_of = parseModule(`for (&{ name } of items);`, 'App.tsrx');
 		const of_statement = firstStatement(for_of, 'ForOfStatement');

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit b839985. Configure here.

Comment thread packages/tsrx/src/plugin.js Resolved
pattern_position_contains_lazy treated a lazy pattern wrapped in a
TypeScript assertion as an expression use, falsely rejecting targets
acorn-typescript's toAssignable accepts ([&{ a }!] = arr). Look through
the same wrapper set toAssignable unwraps (parentheses, as/satisfies,
non-null, type assertions, type casts); a wrapper feeding a member
access ((&{ a }!.b = x)) still rejects.
Two blockers kept ([&{ a } as T] = arr) from parsing:

1. checkExpressionErrors reported the pending lazy record on the
   non-throwing form too, so Acorn's parseExprOps early-exit cut the
   pattern off before parseExprOp could consume as/satisfies. Report only
   on the throwing form — every path that keeps a stale record still ends
   in a throwing boundary check, and toAssignable clears valid ones.

2. At statement level, acorn-typescript unwraps TS wrappers only in
   checkLValSimple, so a wrapper around a destructuring pattern (kept by
   toAssignableList, which ignores return values) fell through to
   'Assigning to rvalue'. Unwrap in checkLValPattern so wrapped patterns
   take the pattern lane, matching the non-lazy [b as any] = arr baseline.
@leonidaz
leonidaz merged commit decbe8f into main Aug 27, 2026
9 checks passed
@leonidaz
leonidaz deleted the refactor/simplify-lazy-arrow-parsing branch August 27, 2026 16:32
@github-actions github-actions Bot mentioned this pull request Aug 27, 2026

This branch was successfully deployed

2 active deployments
Preview – tsrx-website — f7fefa81 Deployed Aug 27, 2026 by vercel[bot]
Preview – tsrx-website-mcp — f7fefa81 Deployed Aug 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant