Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### Fixes

- In JavaScript and TypeScript, a call on a local variable whose name shadows an outer variable typed with a package type no longer loses its edge when the local is a later declarator (`let n = 0, ob = ...`) or a destructured variable with a default (`const { ob = ... } = o`). Thanks @inth3shadows for the report. (#3293)
- In TypeScript, an awaited call with type arguments like `await fetchApi<User>("/me")` or `await api.get<T>(url)` now links to the function it calls. Before, the call was dropped, so typed fetch wrappers looked like they had no callers. (#2586)
- In JavaScript and TypeScript, a call or `new` in a parameter's default value, like `function renderWithNote(note = buildNote())`, a destructured `{ size = defaultSize() }` or `constructor(private svc = new Service())`, now counts as the function's own call. Before, it was dropped, so `buildNote` was missing that caller and impact on it came back incomplete. Re-index JavaScript and TypeScript projects after upgrading. Thanks @inth3shadows for the report and the pull request. (#2588)
- In React, a component rendered at module scope, in a top-level constant or inside a test's `it(…)` callback, like `createRoot(el).render(<App />)` or `render(<Card />)`, now counts as rendered there, so an app's entry reaches its root component and a component's tests show among its callers. (#2587)
Expand Down
129 changes: 129 additions & 0 deletions __tests__/js-receiver-binding-scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ function methodCalls(graph: CodeGraph, file: string): string[] {
return out.sort();
}

/** `caller -> target` for every `calls` edge out of `file`. */
function allCalls(graph: CodeGraph, file: string): string[] {
const out: string[] = [];
for (const node of graph.getNodesInFile(file)) {
for (const e of graph.getOutgoingEdges(node.id)) {
if (e.kind !== 'calls') continue;
const target = graph.getNode(e.target)!;
out.push(`${node.name} -> ${target.name}`);
}
}
return out.sort();
}

const BOUNDARY = 'import { Component } from "react";\nexport class Boundary extends Component<{ children?: React.ReactNode }> {\n render() { return this.props.children; }\n}\n';

describe('a receiver is read by its binding in scope at the call', () => {
Expand Down Expand Up @@ -139,4 +152,120 @@ describe('a receiver is read by its binding in scope at the call', () => {
]);
expect(methodCalls(graph, 'src/later.jsx')).toEqual(['stop -> Gauge::close']);
}, 120_000);

it('recognizes a nearer binding across later declarators and destructuring defaults (#3293)', async () => {
const graph = await index({
'package.json': JSON.stringify({ name: 'app', dependencies: { 'react-dom': '^18.0.0' } }),
'src/chart.tsx': 'export class Chart {\n render() { return 1; }\n}\n',
'src/views.tsx':
'import { createRoot, type Root } from "react-dom/client";\nimport { Chart } from "./chart";\n' +
'let root: Root | null = null;\n' +
'export function laterDeclarator() {\n' +
' let n = 0, root = new Chart();\n' +
' return root.render();\n' +
'}\n' +
'export function destructuredDefault(opt: any) {\n' +
' const { root = new Chart() } = opt;\n' +
' return root.render();\n' +
'}\n' +
'export function destructuredAfterDefault(opt: any) {\n' +
' const { x = 1, root } = opt;\n' +
' return root.render();\n' +
'}\n',
});
expect(methodCalls(graph, 'src/views.tsx')).toEqual([
'destructuredAfterDefault -> Chart::render',
'destructuredDefault -> Chart::render',
'laterDeclarator -> Chart::render',
]);
}, 120_000);

it('bounds declaration list scanning and preserves outer bindings across non-declarator commas (#3293)', async () => {
const list30 = Array.from({ length: 30 }, (_, i) => `a${i}`).join(', ');
const jqueryList = Array.from({ length: 15 }, (_, i) => ` j${i} = ${i}`).join(',\n');
const graph = await index({
'package.json': JSON.stringify({ name: 'app' }),
'src/gauge.ts': 'export class Gauge {\n paint() { return 1; }\n}\nexport class Other {\n paint() { return 2; }\n}\nexport function defaultSize() { return 10; }\n',
'src/long-list.ts':
'import { Gauge } from "./gauge";\n' +
'let ob: Gauge = new Gauge();\n' +
`var ${list30};\n` +
`var\n${jqueryList};\n` +
'export function run() { return ob.paint(); }\n',
'src/for-of.ts':
'import { Gauge } from "./gauge";\n' +
'let ob: Gauge = new Gauge();\n' +
'export function loop(items: any[]) {\n' +
' for (const [ob] of items) { ob.paint(); }\n' +
'}\n' +
'export function loopObj(items: any[]) {\n' +
' for (const { ob } of items) { ob.paint(); }\n' +
'}\n',
'src/non-declarator-commas.tsx':
'import { Gauge } from "./gauge";\n' +
'let ob: Gauge = new Gauge();\n' +
'declare function make(): any;\n' +
'declare function log(x: any): void;\n' +
'export function jsx() {\n' +
' const el = <p>Hi, ob is set</p>;\n' +
' return ob.paint();\n' +
'}\n' +
'export function objType() {\n' +
' const o: { a: number, ob: string } = make();\n' +
' return ob.paint();\n' +
'}\n' +
'export function generic() {\n' +
' const m = new Map<string, typeof ob>();\n' +
' return ob.paint();\n' +
'}\n' +
'export function commaExpr() {\n' +
' const n = 1\n' +
' log(n), ob.paint()\n' +
'}\n',
'src/multiline-destruct.ts':
'import { Gauge } from "./gauge";\n' +
'let ob: Gauge = new Gauge();\n' +
'declare function useState(n: number): any;\n' +
'export function semiFree(c: any) {\n' +
' const [s, setS] = useState(0)\n' +
' ob.paint()\n' +
' c[s] = 1\n' +
'}\n' +
'export function forEntries(c: any) {\n' +
' for (const [k, v] of Object.entries(ob)) {\n' +
' c[k] = v;\n' +
' ob.paint();\n' +
' }\n' +
'}\n',
'src/default-val.ts':
'import { defaultSize } from "./gauge";\n' +
'export function check(opts: any) {\n' +
' const { size = defaultSize() } = opts;\n' +
' return defaultSize();\n' +
'}\n',
'src/foo.ts': 'export function foo() { return 1; }\n',
'src/shadow.ts':
'import { foo } from "./foo";\n' +
'declare function make(): any;\n' +
'export function run() {\n' +
' let n = 0, foo = make();\n' +
' foo();\n' +
'}\n',
});

expect(methodCalls(graph, 'src/long-list.ts')).toEqual(['run -> Gauge::paint']);
expect(methodCalls(graph, 'src/for-of.ts')).toEqual([]);
expect(methodCalls(graph, 'src/non-declarator-commas.tsx')).toEqual([
'commaExpr -> Gauge::paint',
'generic -> Gauge::paint',
'jsx -> Gauge::paint',
'objType -> Gauge::paint',
]);
expect(methodCalls(graph, 'src/multiline-destruct.ts')).toEqual([
'forEntries -> Gauge::paint',
'semiFree -> Gauge::paint',
]);
expect(allCalls(graph, 'src/default-val.ts')).toEqual(['check -> defaultSize', 'check -> defaultSize']);
expect(allCalls(graph, 'src/shadow.ts')).toEqual(['run -> make']);
}, 120_000);
});
63 changes: 39 additions & 24 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13557,6 +13557,31 @@ function jsFunctionLocalScope(name: string, ref: UnresolvedRef, context: Resolut
*/
const JS_CODE_BINDS = new WeakMap<ResolutionContext, Map<string, boolean>>();

// The balanced groups a parameter's type or default can hold, two levels deep.
const PARAM_PAREN = '\\((?:[^()]|\\([^()]*\\))*\\)';
const PARAM_BRACE = '\\{(?:[^{}]|\\{[^{}]*\\})*\\}';
const PARAM_BRACKET = '\\[(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*\\]';
const PARAM_ANGLE = '<(?!\\s)(?:=>|=(?!>)|[^<>=]|<(?:=>|=(?!>)|[^<>=])*>)*>';
/**
* One piece of a parameter's type or default: a character other than a comma,
* or a balanced group, which may hold commas (`Map<K, V>`, `{ a: A, b: B }`,
* `(a: number, b: number) => number`). Every alternative starts with a
* character of its own — `=>` is the arrow of a function type, and a `<` or
* `>` spaced like an operator (`f.length > 0`) is no bracket — so a type has
* one parse.
*/
const PARAM_PART = `(?:=>|=(?!>)|[^,(){}\\[\\]<>=]|<(?=\\s)|>(?=[\\s=])|${PARAM_PAREN}|${PARAM_BRACE}|${PARAM_BRACKET}|${PARAM_ANGLE})`;
/** A TypeScript type annotation piece: balanced brackets/braces/angles or non-separator characters, allowing `=>` but never `=`. */
const TYPE_PART = `(?:=>|[^,(){}\\[\\]<>=]|<(?=\\s)|>(?=[\\s=])|${PARAM_PAREN}|${PARAM_BRACE}|${PARAM_BRACKET}|${PARAM_ANGLE})`;
/** A TypeScript parameter property's modifiers: `constructor(private readonly store: Store)`. */
const PARAM_MODIFIERS = '(?:(?:public|private|protected|readonly|override)\\s+)*';
/** A single declarator preceding the target variable: name or destructuring, optional type, optional initializer. */
const PREV_DECL_ITEM = `(?:[\\w$]+|${PARAM_BRACE}|${PARAM_BRACKET})(?:\\s*(?:\\?\\s*)?:${PARAM_PART}+|\\s*=${PARAM_PART}+|\\s*)`;
/** Earlier declarators before the target variable in a `const`/`let`/`var` list (#3293). */
const PREV_VAR_DECL = `(?:${PREV_DECL_ITEM},\\s*)*`;
/** Characters that may follow a declared variable name in valid JS/TS (not `.` or arbitrary text). */
const DECL_FOLLOW = '(?=\\s*(?:[=,;)]|\\bin\\b|\\bof\\b|$|\\r?\\n))';

/**
* Whether the function's code in `filePath`, from its first line through
* `line` (a reference's, or a JSX tag's), declares `name`, or names it in a
Expand All @@ -13574,7 +13599,7 @@ export function jsCodeBindsName(name: string, fn: Node, filePath: string, line:
// the same name — `const { t } = useI18n()`, `const { getLabel } =
// useProps(props)` — which is the same-named function more often than not.
const sites = jsNameSites(text, name);
const declared = sites.declaration && new RegExp(`\\b(?:const|let|var)\\s+${n}(?![\\w$])(?!\\s*[,\\]}])`).test(text);
const declared = sites.declaration && new RegExp(`\\b(?:const|let|var)\\s+${PREV_VAR_DECL}${n}(?![\\w$])(?!\\s*[,\\]}])`).test(text);
binds = declared || (sites.parameter && jsParameterListPattern(name, '').test(text));
memo.set(key, binds);
}
Expand Down Expand Up @@ -13658,7 +13683,7 @@ function jsBindingEnclosesReference(name: string, fn: Node, ref: UnresolvedRef,
const code = chars.join('');
const n = escapeRegExp(name);
const declaration = new RegExp(
`\\b(?:(?:const|let|var)\\s+${n}(?![\\w$])(?!\\s*[,\\]}])(\\s*=\\s*(?:await\\s+)?(?:require|import)\\s*\\()?|(?:function|class)\\s+${n}(?![\\w$]))`,
`\\b(?:(?:const|let|var)\\s+${PREV_VAR_DECL}${n}(?![\\w$])(?!\\s*[,\\]}])(\\s*=\\s*(?:await\\s+)?(?:require|import)\\s*\\()?|(?:function|class)\\s+${n}(?![\\w$]))`,
'g'
);
for (const m of code.matchAll(declaration)) {
Expand Down Expand Up @@ -13861,30 +13886,19 @@ const JS_BINDING_NAME = /^[\w$]+$/;
const ARROW_HEAD_CHAR = /[\w$.]/;
const IMPORT_BINDING_VALUE = /^\s*(?:await\s+)?(?:require|import)\s*\(/;

// The balanced groups a parameter's type or default can hold, two levels deep.
const PARAM_PAREN = '\\((?:[^()]|\\([^()]*\\))*\\)';
const PARAM_BRACE = '\\{(?:[^{}]|\\{[^{}]*\\})*\\}';
const PARAM_BRACKET = '\\[(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*\\]';
const PARAM_ANGLE = '<(?!\\s)(?:=>|=(?!>)|[^<>=]|<(?:=>|=(?!>)|[^<>=])*>)*>';
/**
* One piece of a parameter's type or default: a character other than a comma,
* or a balanced group, which may hold commas (`Map<K, V>`, `{ a: A, b: B }`,
* `(a: number, b: number) => number`). Every alternative starts with a
* character of its own — `=>` is the arrow of a function type, and a `<` or
* `>` spaced like an operator (`f.length > 0`) is no bracket — so a type has
* one parse.
*/
const PARAM_PART = `(?:=>|=(?!>)|[^,(){}\\[\\]<>=]|<(?=\\s)|>(?=[\\s=])|${PARAM_PAREN}|${PARAM_BRACE}|${PARAM_BRACKET}|${PARAM_ANGLE})`;
/** A TypeScript parameter property's modifiers: `constructor(private readonly store: Store)`. */
const PARAM_MODIFIERS = '(?:(?:public|private|protected|readonly|override)\\s+)*';

function localBindingPatterns(name: string, flags: string): LocalBindingPatterns {
const n = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const targetInPattern = `(?:(?<=[{,\\[])\\s*|(?<=[{,\\[])\\s*[\\w$]+\\s*:\\s*|(?<=[{,\\[])\\s*[\\w$]+\\s*:\\s*[{[\\]]\\s*|\\.\\.\\.\\s*)${n}(?![\\w$])`;
const bracketPattern = `\\[(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*?${targetInPattern}(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*?\\]`;
const bracePattern = `\\{(?:[^{}]|\\{[^{}]*\\})*?${targetInPattern}(?:[^{}]|\\{[^{}]*\\})*?\\}`;
const destructPattern = `(?:${bracketPattern}|${bracePattern})`;
return {
// `const { name } = require('./m')` / `= await import('./m')` binds an IMPORT,
// not a shadow: the symbol lives in the other file and the call means it.
decl: new RegExp(
'\\b(?:const|let|var)\\s+(?:' + n + '(?![\\w$])|[{\\[][^;=]*?\\b' + n + '(?![\\w$])[^;=]*?[}\\]])\\s*(?:=\\s*([^;\\n]*))?',
'\\b(?:const|let|var)\\s+' + PREV_VAR_DECL +
'(?:' + n + '(?![\\w$])(?:\\s*!?\\s*:' + TYPE_PART + '+)?' + DECL_FOLLOW + '(?:\\s*=\\s*([^;\\n]*))?|' +
destructPattern + '(?:\\s*!?\\s*:' + TYPE_PART + '+)?(?:\\s*(?:=|\\bin\\b|\\bof\\b)\\s*([^;\\n)]*))?)',
flags
),
fn: new RegExp('\\b(?:function|class)\\s+' + n + '(?![\\w$])', flags),
Expand Down Expand Up @@ -13944,7 +13958,7 @@ function isLocallyBoundJsName(name: string, filePath: string, context: Resolutio
function bindsAnywhere(source: string, name: string): boolean {
const { decl, fn, param } = localBindingPatterns(name, 'g');
for (const m of source.matchAll(decl)) {
if (!IMPORT_BINDING_VALUE.test(m[1] ?? '')) return true;
if (!IMPORT_BINDING_VALUE.test(m[1] ?? m[2] ?? '')) return true;
}
const n = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return fn.test(source) || param.test(source) || new RegExp('(?:^|[^\\w$.])' + n + '\\s*=>').test(source);
Expand Down Expand Up @@ -13985,7 +13999,7 @@ function bindsAtSites(source: string, name: string, sites: LocalBindingSites): b
const m = decl.exec(source);
if (!m) continue;
from = at + m[0].length;
if (!IMPORT_BINDING_VALUE.test(m[1] ?? '')) return true;
if (!IMPORT_BINDING_VALUE.test(m[1] ?? m[2] ?? '')) return true;
}
for (const at of sites.fnDecls) {
fn.lastIndex = at;
Expand Down Expand Up @@ -23868,7 +23882,8 @@ function jsBindingSites(name: string, file: JsScopeFile): JsBindingSite[] {
continue;
}
// `const x = require('./x')` binds an import, which the file's imports answer for.
const plain = !/^(?:const|let|var)\s+[{[]/.test(m[0]) && !IMPORT_BINDING_VALUE.test(m[1] ?? '');
const rhs = m[1] ?? m[2] ?? '';
const plain = m[2] === undefined && !IMPORT_BINDING_VALUE.test(rhs);
sites.push({ ...blockOf(at), at, kind: plain ? 'declaration' : 'other' });
}
for (const at of file.fnDecls) {
Expand Down Expand Up @@ -24024,7 +24039,7 @@ function jsParameterReading(name: string, site: JsBindingSite, file: JsScopeFile
*/
function jsDeclarationReading(name: string, site: JsBindingSite, file: JsScopeFile): JsBindingReading | null {
const { code } = file;
const head = new RegExp(`(?:const|let|var)\\s+${escapeRegExp(name)}(?![\\w$])\\s*(?:!?\\s*:\\s*${TS_ANNOTATED_TYPE})?`, 'y');
const head = new RegExp(`(?:const|let|var)\\s+${PREV_VAR_DECL}${escapeRegExp(name)}(?![\\w$])\\s*(?:!?\\s*:\\s*${TS_ANNOTATED_TYPE})?`, 'y');
head.lastIndex = site.at;
const m = head.exec(code);
if (!m) return null;
Expand Down