Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- In JavaScript and TypeScript, `this.findAll()` in a class that wraps an imported helper of the same name now links to the class's own method instead of the imported helper. Thanks @inth3shadows for the report. (#2954)
- In TypeScript, a call on a parameter or local named like an import, like `stream.write()` inside `stream(c, async (stream) => …)`, now goes by that parameter or local, and a method called on an imported function no longer links to the function itself; the same mistake through `require` was already fixed in 1.6.3. Thanks @inth3shadows for the report. (#2953)
- In JavaScript and TypeScript, a call to a name that a function around the caller declares for itself, like a helper an inner arrow function calls, now links to that local declaration instead of the file's import of the same name. Thanks @inth3shadows for the report. (#2949)
- In JavaScript and TypeScript, a call to a helper declared inside a `describe(…)` block, or any other callback, now links to the helper that block declares instead of a same-named one from another block that happens to sit nearer. Thanks @inth3shadows for the report. (#2944)
- In JavaScript and TypeScript, a call inside a spread, like `<input {...register('email')} />` with `register` taken from `useForm()`, no longer links to an unrelated project function that shares the name. Thanks @inth3shadows for the report. (#2962)

## [1.6.3] - 2026-11-17

Expand Down
165 changes: 165 additions & 0 deletions __tests__/js-bare-call-scope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/**
* A bare JS/TS call means the binding of its name in scope where it is
* written:
* - of two functions named alike in one file, each in its own `describe(…)`
* callback (which is no node), a call reaches the one its own block
* declares, however near the other is (#2944);
* - a call after a spread, `{...register('email')}`, is as bare as one
* without it, so a destructured local of the name shadows every other
* file's `register` (#2962).
*/

import { describe, it, expect, afterEach } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import CodeGraph from '../src/index';

let tempDir: string;
let cg: CodeGraph | null = null;

async function index(files: Record<string, string>): Promise<void> {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-bare-scope-'));
for (const [rel, content] of Object.entries(files)) {
const abs = path.join(tempDir, rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content);
}
cg = await CodeGraph.init(tempDir, { index: true });
}

/** Every `calls` edge out of `file`'s nodes, as `<line> -> <qualifiedName>@<file>:<line>`. */
function callsIn(file: string): string[] {
const out: string[] = [];
for (const n of cg!.getNodesInFile(file)) {
for (const e of cg!.getOutgoingEdges(n.id)) {
if (e.kind !== 'calls') continue;
const t = cg!.getNode(e.target)!;
out.push(`${e.line} -> ${t.qualifiedName}@${t.filePath}:${t.startLine}`);
}
}
return out.sort((a, b) => parseInt(a, 10) - parseInt(b, 10) || a.localeCompare(b));
}

afterEach(() => {
cg?.close();
cg = null;
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
});

const GLOBALS = 'declare function describe(name: string, fn: () => void): void;\ndeclare function it(name: string, fn: () => void): void;\n';
const PAD = Array.from({ length: 20 }, (_, i) => ` // pad ${i + 3}\n`).join('');

describe('same-named functions in two describe() callbacks (#2944)', () => {
it('links each call to the function its own block declares', async () => {
await index({
'globals.d.ts': GLOBALS,
'a.test.ts':
"describe('first', () => {\n" +
' function setup(): number { return 1; }\n' +
PAD +
" it('uses first', () => { setup(); });\n" +
'});\n' +
"describe('second', () => {\n" +
' function setup(): number { return 2; }\n' +
" it('uses second', () => { setup(); });\n" +
'});\n',
});
expect(callsIn('a.test.ts').filter((c) => c.includes('setup'))).toEqual([
'23 -> setup@a.test.ts:2',
'27 -> setup@a.test.ts:26',
]);
});

it('does the same for arrow-function helpers', async () => {
await index({
'globals.d.ts': GLOBALS,
'b.test.ts':
"describe('first', () => {\n" +
' const setup = (): number => 1;\n' +
PAD +
" it('uses first', () => { setup(); });\n" +
'});\n' +
"describe('second', () => {\n" +
' const setup = (): number => 2;\n' +
" it('uses second', () => { setup(); });\n" +
'});\n',
});
expect(callsIn('b.test.ts').filter((c) => c.includes('setup'))).toEqual([
'23 -> setup@b.test.ts:2',
'27 -> setup@b.test.ts:26',
]);
});

it('keeps a top-level function for a call outside the block that hides it', async () => {
await index({
'globals.d.ts': GLOBALS,
'c.test.ts':
'function setup(): number { return 0; }\n' +
"describe('inner', () => {\n" +
' function setup(): number { return 1; }\n' +
" it('uses inner', () => { setup(); });\n" +
'});\n' +
"describe('outer', () => {\n" +
" it('uses top', () => { setup(); });\n" +
'});\n',
});
expect(callsIn('c.test.ts').filter((c) => c.includes('setup'))).toEqual([
'4 -> setup@c.test.ts:3',
'7 -> setup@c.test.ts:1',
]);
});
});

describe('a call after a spread is a bare call (#2962)', () => {
it('links no other file\'s function to a destructured local called in a spread', async () => {
await index({
'auth.ts': "export function register(email: string): Promise<void> { return Promise.resolve(); }\n",
'use.tsx':
"import { useForm } from 'react-hook-form';\n" +
'declare function f(...a: unknown[]): void;\n' +
'export function objSpread() {\n' +
' const { register } = useForm();\n' +
" const props = { ...register('email') };\n" +
' return props;\n' +
'}\n' +
'export function jsxSpread() {\n' +
' const { register } = useForm();\n' +
" return <input {...register('email')} />;\n" +
'}\n' +
'export function jsxSpreadNested() {\n' +
' const { register } = useForm();\n' +
" return <form><input {...register('email')} /></form>;\n" +
'}\n' +
'export function aliased() {\n' +
' const { reg: register } = useForm();\n' +
" return <input {...register('email')} />;\n" +
'}\n' +
'export function arraySpread() {\n' +
' const { register } = useForm();\n' +
" return [...register('x')];\n" +
'}\n' +
'export function argSpread() {\n' +
' const { register } = useForm();\n' +
" f(...register('x'));\n" +
'}\n',
});
expect(callsIn('use.tsx').filter((c) => c.includes('auth.ts'))).toEqual([]);
});

it('still links a spread call of an imported or a local function', async () => {
await index({
'props.ts': 'export function makeProps(): object { return {}; }\n',
'use.ts':
"import { makeProps } from './props';\n" +
'function local(): object { return {}; }\n' +
'export function build() {\n' +
' return { ...makeProps(), ...local() };\n' +
'}\n',
});
expect(callsIn('use.ts')).toEqual([
'4 -> local@use.ts:2',
'4 -> makeProps@props.ts:1',
]);
});
});
43 changes: 42 additions & 1 deletion src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4624,6 +4624,9 @@ function isReceiverLessCall(ref: UnresolvedRef, context: ResolutionContext): boo
// closes a statement header — `if (open) setOpen()`, `for (…) f()`, a header
// that wraps lines or holds a `)` in a string — and the call is bare (#2585).
if (line[end - 1] === ')' && JS_FAMILY.has(ref.language)) return true;
// Nor is a spread's or a rest's `...`: `{...register('email')}` calls
// `register` as bare as `register('email')` does (#2962).
if (end >= 3 && line.startsWith('...', end - 3) && JS_FAMILY.has(ref.language)) return true;
let start = end;
while (start > 0 && WORD_CHAR.test(line[start - 1]!)) start--;
return BARE_CALL_KEYWORDS.has(line.slice(start, end));
Expand Down Expand Up @@ -14809,6 +14812,43 @@ function bindsAtSites(source: string, name: string, sites: LocalBindingSites): b
return false;
}

/**
* A bare JS/TS call's candidates without the calling file's declarations of
* the name that are out of scope where the call is written, when the file
* declares the name more than once: two `setup` helpers, each in its own
* `describe(…)` callback, which is no node, so neither has a container that
* isLexicallyReachable could read, and the nearer one took both blocks' calls
* (#2944). A declaration is the `function`, `class` or `const`/`let` of the
* name alone written on the node's first line (jsBindingSites), in scope
* through the block it is written in. A `var` (scoped to its function, not
* its block) or a declaration the reader doesn't find stays a candidate.
*/
function jsDeclarationsInScope(candidates: Node[], ref: UnresolvedRef, context: ResolutionContext): Node[] {
if (candidates.filter((n) => n.filePath === ref.filePath).length < 2) return candidates;
const file = jsScopeFile(ref.filePath, context);
if (!file) return candidates;
const sites = jsBindingSites(ref.referenceName, file);
const at = (file.lineStarts[ref.line - 1] ?? file.code.length) + ref.column;
return candidates.filter((n) => {
if (n.filePath !== ref.filePath) return true;
const site = sites.find((s) => (s.kind === 'function' || s.kind === 'declaration') && jsLineOf(file, s.at) === n.startLine);
if (!site || file.code.startsWith('var', site.at) || (site.kind === 'function' && isJsExpressionAt(file.code, site.at))) return true;
return site.from <= at && site.to >= at;
});
}

/**
* Whether the `function` or `class` keyword at `at` starts an expression, whose
* name binds only inside it: `readBinary = function readBinary(f) {…}`,
* `(function x() {…})`, `return class Y {…}` — an operand's place, after an
* operator, an opening bracket, a comma, a colon or a keyword that takes a value.
*/
function isJsExpressionAt(code: string, at: number): boolean {
let before = code.slice(Math.max(0, at - 64), at).replace(/\s+$/, '');
if (/(?:^|[^\w$])async$/.test(before)) before = before.slice(0, -5).replace(/\s+$/, '');
return /(?:[=(,:?[!&|+\-*/%<>~^]|=>|(?:^|[^\w$.])(?:return|yield|await|new|typeof|void|delete|in|of|case))$/.test(before);
}

/**
* The calling file's declarations of an out-of-repo imported name that sit
* inside a function or method — only those can shadow the import. A top-level
Expand Down Expand Up @@ -15330,7 +15370,8 @@ export function matchByExactName(
// file's symbol of that name, so a bare call has no cross-file candidate.
!(bareJs && n.filePath !== ref.filePath && (locallyBoundJsName ??= isLocallyBoundJsName(ref.referenceName, ref.filePath, context)))
);
const ranked = dartBare ? nearestDartMembers(preferOwnDartLibrary(filtered, ref, context), ref, context)
const ranked = bareJs ? jsDeclarationsInScope(filtered, ref, context)
: dartBare ? nearestDartMembers(preferOwnDartLibrary(filtered, ref, context), ref, context)
: dartTypeRef && dartPrefix === null ? preferOwnDartLibrary(filtered, ref, context)
: swiftShape && swiftShape.shape !== 'chained' ? nearestSwiftMembers(filtered, ref, context)
: kotlinBare ? lexicalKotlinMembers(filtered, ref, context)
Expand Down