Repository navigation
refactor(core): simplify lazy pattern parsing and extend valid positions - #11
Merged
Merged
Conversation
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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Contributor
There was a problem hiding this comment.
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.
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.
…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.
…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.
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
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.
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.
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.
Merged
This branch was successfully deployed
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.


Summary
Follow-up review of #7 and #9.
Lazy pattern parsing (#9 rework)
Replaces the candidate-pattern stack,
parseSubscriptoverride, and arrow-only containment validation with Acorn's ownDestructuringErrorsprotocol — the same mechanism Acorn uses for the analogous{a = b}shorthand ambiguity ("valid if this becomes a pattern, error if it stays an expression"):parseExprAtomparses&{…}/&[…]wherever aDestructuringErrorscontext exists (exactly the pattern-ambiguous positions) and records it as a pending error (lazyBindingPos).toAssignableresolves 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 wrapperstoAssignableitself unwraps, so[&{ a }!] = arr,[&{ a } as T] = arr, andsatisfiesforms 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:
[&{ 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)for–of/for–in/@forloop targets:@for (&{ label } of items)works end-to-end in react, solid, and vue today because the@forlowering 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.jsfor 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. ThetoAssignablerefinements 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
#scopeDeclaredNameshelper, drops the rebuild branch for shrunken scope arrays (Acorn only ever appends to a scope'slexical/vararrays during its lifetime, so it was unreachable), and types the backingWeakMap.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 barefor (&{ 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@forlazy-target compile test exercised by all four targets)pnpm typecheck,pnpm format:check,pnpm changeset:check: cleanNote
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’sDestructuringErrorsflow (same idea as ambiguous{a = b}shorthand):parseExprAtomrecords a pendinglazyBindingPoswhen&opens a pattern inside a destructuring context,toAssignableclears it only whenpattern_position_contains_lazyfinds the pattern in a real binding/assignment slot (including through parens and TS wrappers like[&{ a } as T] = arr), andcheckExpressionErrorsraises "Lazy binding patterns are only valid as binding or assignment targets" for expression uses (foo(&{a}),&{a}.b = x). The old per-paren#potentialLazyArrowPatternsstack,parseSubscripthook, and arrow-only validation are removed;checkLValPatternunwraps 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 /@forloop targets (@for (&{ label } of items)), with a new shared compile test for@forlazy targets.A small export lookup tidy moves scope name syncing into
#scopeDeclaredNamesand types the backingWeakMap. Types addlazyBindingPosandpreserveTypeScriptWrapperontoAssignable.Reviewed by Cursor Bugbot for commit f7fefa8. Bugbot is set up for automated code reviews on this repo. Configure here.