Skip to content

fix(resolution): recognize later declarators and destructuring defaults as local bindings (#3293) - #3294

Open
mohitdixit02 wants to merge 2 commits into
colbymchenry:mainfrom
mohitdixit02:fix/js-local-binding-patterns-3293
Open

mohitdixit02 wants to merge 2 commits into
colbymchenry:mainfrom
mohitdixit02:fix/js-local-binding-patterns-3293

Conversation

@mohitdixit02

Copy link
Copy Markdown

When a local variable shadows an outer variable typed with a package type (such as a module-scoped let root: Root | null from react-dom/client), calls made on that local receiver were incorrectly dropped if the local was declared in a comma-separated declaration list (let n = 0, ob = new Chart()) or extracted via destructuring with defaults (const { ob = new Chart() } = opt). Because localBindingPatterns.decl and jsDeclarationReading expected the target identifier to immediately follow const|let|var\s+, and destructuring patterns rejected any =, CodeGraph failed to identify the nearer local binding site and fell back to the outer package-typed symbol, refusing to resolve calls against matching project methods.

This change introduces PREV_VAR_DECL to account for preceding declarators in variable lists, allows destructuring patterns containing default initializers (=), and updates jsBindingSites to inspect both plain and destructured initializer branches. Nearer local bindings in these shapes are now accurately recognized, allowing local calls to resolve cleanly against project methods rather than being suppressed by an outer package type.

  import { createRoot, type Root } from "react-dom/client";
  import { Chart } from "./chart";

  let root: Root | null = null;

  export function laterDeclarator() {
    let n = 0, root = new Chart();
    return root.render(); // now links to Chart::render instead of being dropped
  }

  export function destructuredDefault(opt: any) {
    const { root = new Chart() } = opt;
    return root.render(); // now links to Chart::render
  }

Fixes #3293

Co-authored-by: @inth3shadows

@mohitdixit02
mohitdixit02 force-pushed the fix/js-local-binding-patterns-3293 branch from aa17cb5 to 7ec8922 Compare November 14, 2026 18:54
@inth3shadows

inth3shadows commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for picking this up so quickly, @mohitdixit02. The five shapes from #3293 all link to Other::paint on this branch, and the outer Root still links nothing. Here are some things I noticed while testing it. There may be more.

I merged head 7ec89225 into main at 2b5adb3a and compared the result with plain main. Each case below has a module-level let ob: Gauge (a class in the project) and calls ob.paint() inside a function.

1. Indexing can stall on long declaration lists. In the new prefix pattern for earlier declarators, the whitespace before a , and the whitespace after it can both match the same spaces. When the name is not in the list, the regex therefore backtracks exponentially before it fails. It runs at every const/let/var keyword, once for each receiver name in the file. Verified, by indexing a single file with that list and an unrelated ob.paint():

Declaration in the file main this PR
var a0, a1, …, a29; (30 names) 133 ms 79,620 ms
let a0 = 0, a1 = 1, … (26 items) 122 ms 7,156 ms
jQuery style var a0 = 0,\n a1 = 1, … (14 items) 128 ms killed after about 40 s

Matching the whitespace on only one side of the comma, or making each declarator atomic, should remove the blow-up.

2. Destructuring in a for…of head no longer counts as a binding. The destructuring branch now requires = …, and a for head has none. Verified: for (const [ob] of items) { ob.paint(); } now links to Gauge::paint, the outer variable's type. On main it links nothing. That is a wrong edge. for (const ob of items), for…in and catch (ob) are unaffected.

3. A comma that doesn't separate declarators now reads as one. Each of these makes ob look declared, so the correct Gauge::paint edge is lost (verified; main links it):

  • JSX text: const el = <p>Hi, ob is set</p>;
  • an object-type member: const o: { a: number, ob: string } = make();
  • generics: const m = new Map<string, ob>();
  • in semicolon-free code, a comma expression on a later line: const n = 1\nlog(n), ob.paint()

4. With = allowed inside the braces, the destructuring branch can run past the end of its statement. In semicolon-free code it continues to the next ] = or } =, such as c[s] = 1 or items[0] === 1. Verified: const [s, setS] = useState(0)\nob.paint()\nc[s] = 1 loses the Gauge::paint edge. The same happens in a for head with semicolons: for (const [k, v] of Object.entries(ob)) { c[k] = v; ob.paint(); }.

5. Smaller ones. I only checked these against the regex directly, not end to end:

  • A name used as a default value, as in const { size = defaultSize() } = opts, now counts as bound. A bare defaultSize() call would then lose its cross-file target, as in TS/JS: a call in a parameter's default value (f(x = build())) gets no calls edge #2588.
  • const load: () => Loader = require('./loader'): the type annotation stops at the = of =>, so the captured value no longer looks like a require.
  • jsBindingEnclosesReference and jsCodeBindsName still use the old pattern. With import { foo } plus let n = 0, foo = make(); foo();, the call still resolves to the import.

None of these would fail the new test, because it covers only the positive shapes. A few negative cases, a for…of destructuring head and a long declaration list for example, would pin them. Building the declarator prefix from the existing PARAM_PART piece, which already balances <…> and =>, might also cover finding 3.

Checked and fine on this branch: renamed and nested destructuring ({ a: ob }, { a: { ob } }), typed declarators, export const, and commas inside strings, template literals, regexes and comments in an earlier declarator.


Edit (2026-11-16): Thanks for the quick update. I re-ran everything on 54a08fe9, merged into main at 932a7fab, against plain main. All the cases from my first comment pass now. That includes the 30-name and jQuery-style lists, the for…of heads, and the single-line JSX comma. A few things still come up. As before, there may be more.

  1. Large files are still much slower than on main. An earlier declarator's initializer or type can run past ; and newlines, so the search from each const/let/var reaches the end of the file before it gives up. Verified, time to index one file:

    File main this PR
    8,000 lines of const vI = foo(I) 2.1 s 8.6 s
    16,000 lines of the same 6.3 s 29.8 s
    8,000 such lines plus 20 module-level receivers 2.1 s 110.7 s
    one function with 2,000 const lines and 100 calls to other files 0.4 s 74.5 s

    Seven real 130–250 KB files (from decimal.js, chai, acorn, rollup and others) indexed within noise of main. The exposure is generated constant tables and very long functions. Stopping an earlier declarator at ; fixed the semicolon rows in a quick test. Newline-separated code stayed slow, so it probably also needs a stop at the end of the statement.

  2. A comma followed by the name inside a string, comment or template literal now reads as a declarator, so a call to that name loses its target in another file. For example, const q = 'SELECT id, helper FROM t'; return helper(); or const MAX = 3; // try once, helper both lose helper()'s edge. They link on main. The check that tells a real declarator apart doesn't seem to apply on the path that reads raw source, or in the check for whether a function binds the name (jsCodeBindsName).

  3. A comma expression can read as a declarator too. const n = 1;\nlog(n), helper(); loses helper()'s edge, and so does const a = 1\nx.y = 2, ob\nob.paint() in semicolon-free code.

  4. Some nested patterns and types are no longer seen as declarations, which gives wrong edges. With an outer let ob: Gauge, each of these now links ob.paint() to Gauge::paint, where main links nothing:

    • const { a: { x, ob } } = make();
    • const [[k, ob]] = pairs;
    • const ob: { a: { b: { c: number } } } = make();

    With an imported helper, these now link helper() to the import:

    • let helper: Map<string, Array<Set<number>>> = make();
    • let helper // later
  5. A name inside a default value still counts as bound when it follows a comma or a bracket. These all lose the outer edge: const { size = pick(1, defaultSize) } = opts, const { a = fn(1, ob) } = cfg, const { a = [ob] } = cfg, const [a = fn(x, ob)] = cfg.

  6. Multi-line JSX text: const el = <p>\n Hello, ob\n</p>; still drops ob.paint()'s edge. The single-line form is fixed.

On a broader check of about 40,000 call edges from real packages (svelte, vitest, rollup, chai, acorn and others), only 4 edges changed: 3 were correct removals, and the 4th exposed a mismatch that already exists on main. So real code looks fine apart from the cases above. Negative tests for these shapes would help keep them fixed.

@mohitdixit02

Copy link
Copy Markdown
Author

Thanks a lot for the detailed review and test cases, @inth3shadows! I've pushed an update (54a08fe9) addressing all 5 points:

  • Regex performance / ReDoS: Reworked PREV_VAR_DECL using the PARAM_PART approach to avoid whitespace overlap around commas. Scanning long lists (like the 30-item and jQuery-style fixtures) now runs in ~5ms.
  • for..of / for..in destructuring: Supported of and in so loop heads without an = are properly recognized as local bindings.
  • Non-declarator commas: Added a check for valid declarator follow-tokens, so commas inside JSX text, object types, generics, and comma expressions are no longer mistaken for variable separators.
  • Statement boundaries: Made the destructuring patterns bracket-balanced so they don't bleed across lines into subsequent statements in semicolon-free code.
  • Other edge cases: Fixed arrow return types (() => Loader) so they don't consume = require(...), ensured default values like defaultSize() aren't treated as local variable names, and updated jsCodeBindsName / jsBindingEnclosesReference to recognize preceding declarators too.

I also added tests covering each of these positive and negative shapes in __tests__/js-receiver-binding-scope.test.ts. Let me know if everything looks good on your end now!

This branch has not been deployed

No deployments
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.

JS/TS: a call on a local is dropped when an outer same-named variable has a package type

2 participants