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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- When the CodeGraph server's catch-up sync on a large project is stopped because the tool calls it is serving keep its write-ahead log from shrinking, it now waits before trying again, a little longer each time, instead of starting over every second while you keep working. Thanks @kiliman for the report. (#3273)
- A CodeGraph MCP server started in a folder with no index no longer starts its separate hang-watchdog process until the session first calls a tool or opens a project, so sessions that only list the tools, as many hosts open them, use less memory. Thanks @AiurArtanis for the report and @johnhldiver-beep for #3257. (#3250)
- A CodeGraph server whose project folder is deleted, like a removed git worktree, now exits within about half a minute, closing its file watcher and dropping its entry from `codegraph list`, instead of running until its last session ends and it times out. On Windows it also stops keeping that folder's index files from being deleted. Thanks @deniskern for the report and @johnhldiver-beep for #3259. (#3245)
- 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)

## [1.6.3] - 2026-11-17

Expand Down
178 changes: 178 additions & 0 deletions __tests__/js-import-binding-scope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/**
* A JS/TS file's import binds a name for the whole module, but a call means
* the binding in scope where it is written:
* - `this.findAll()` names a member of the instance, never the file's
* `import { findAll }`, however the class wraps it (#2954);
* - `stream.onAbort()` reads `stream` where it is written: a parameter or a
* local of that name is the receiver, and a member of an imported FUNCTION
* is no call of the function itself (#2953);
* - a local, a nested function or a parameter in a function AROUND the
* calling one shadows the import as one in the calling function does, and
* the call is that local declaration's (#2949).
*/

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-import-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 });
}

/** The calls made by the function or method with this qualified name, as `kind qualifiedName (file:line)`. */
function callsFrom(qualifiedName: string): string[] {
const from = [...cg!.getNodesByKind('function'), ...cg!.getNodesByKind('method')].find((n) => n.qualifiedName === qualifiedName);
expect(from, `${qualifiedName} should be indexed`).toBeDefined();
return cg!.getOutgoingEdges(from!.id).filter((e) => e.kind === 'calls')
.map((e) => { const t = cg!.getNode(e.target)!; return `${t.kind} ${t.qualifiedName} (${t.filePath}:${t.startLine})`; })
.sort();
}

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

describe('this.m() is the instance member, not the file import of m (#2954)', () => {
it('links a wrapper class method and an arrow field to their own class', async () => {
await index({
'lib.ts':
"export function findAll(q: string): string[] { return [q]; }\n" +
"export const getFactor = (w: number): number => w;\n",
'tools.ts':
"import { findAll, getFactor } from './lib';\n" +
"export class Tools {\n" +
" run(q: string) { return this.findAll(q); }\n" +
" private findAll(q: string): string[] { return findAll(q).concat('own'); }\n" +
" size(w: number) { return this.getFactor(w); }\n" +
" private getFactor = (w: number): number => getFactor(w) * 2;\n" +
"}\n",
});
expect(callsFrom('Tools::run')).toEqual(['method Tools::findAll (tools.ts:4)']);
expect(callsFrom('Tools::size')).toEqual(['method Tools::getFactor (tools.ts:6)']);
// The wrappers' own bare calls still mean the import.
expect(callsFrom('Tools::findAll')).toEqual(['function findAll (lib.ts:1)']);
});
});

const STREAMING =
"export interface StreamApi { onAbort(f: () => void): void; write(s: string): void; }\n" +
"export function stream(c: unknown, cb: (s: StreamApi) => Promise<void>): Response { return null as any; }\n";

describe('x.m() reads x where it is written (#2953)', () => {
it('takes a callback parameter named like the import for the parameter', async () => {
await index({
'streaming.ts': STREAMING,
'app.ts':
"import { stream } from './streaming';\n" +
"export function handlerA(c: unknown) {\n" +
" return stream(c, async (stream) => {\n" +
" stream.onAbort(() => {});\n" +
" stream.write('x');\n" +
" });\n" +
"}\n",
});
expect(callsFrom('handlerA')).toEqual([
'function stream (streaming.ts:2)',
'method StreamApi::onAbort (streaming.ts:1)',
'method StreamApi::write (streaming.ts:1)',
]);
});

it('never links a parameter or a local named like the import to the imported function', async () => {
await index({
'streaming.ts': STREAMING,
'app.ts':
"import { stream } from './streaming';\n" +
"export function handlerC(stream: { onAbort(f: () => void): void }) {\n" +
" stream.onAbort(() => {});\n" +
"}\n" +
"export function localConst() {\n" +
" const stream = { onAbort(f: () => void) {} };\n" +
" stream.onAbort(() => {});\n" +
"}\n",
});
// (What a parameter written with an object type calls is no import's.)
expect(callsFrom('handlerC')).not.toContain('function stream (streaming.ts:2)');
expect(callsFrom('localConst').filter((t) => t.includes('streaming.ts'))).toEqual([]);
});

it('links no member of an imported function to the function, but call and apply still call it', async () => {
await index({
'streaming.ts': STREAMING,
'app.ts':
"import { stream } from './streaming';\n" +
"export function asAny() {\n" +
" (stream as any).onAbort();\n" +
"}\n" +
"export function viaCall(c: unknown) {\n" +
" return stream.call(undefined, c, async () => {});\n" +
"}\n" +
"export function direct(c: unknown) {\n" +
" return stream(c, async () => {});\n" +
"}\n",
});
expect(callsFrom('asAny')).toEqual([]);
expect(callsFrom('viaCall')).toEqual(['function stream (streaming.ts:2)']);
expect(callsFrom('direct')).toEqual(['function stream (streaming.ts:2)']);
});
});

describe('a local shadows a project import in the functions around the call too (#2949)', () => {
it('links each call to the binding in scope where it is written', async () => {
await index({
'lib.ts': "export function skipString(j: number): number { return j + 1; }\n",
'use.ts':
"import { skipString } from './lib';\n" +
"export function scanA(s: string) {\n" +
" const skipString = (j: number): number => j + 2;\n" +
" return skipString(0);\n" +
"}\n" +
"export function scanB(s: string) {\n" +
" function skipString(j: number): number { return j + 3; }\n" +
" return skipString(0);\n" +
"}\n" +
"export function scanC(s: string) { return skipString(0); }\n" +
"export function scanD(s: string) {\n" +
" const skipString = (j: number): number => j + 2;\n" +
" const skipValue = (j: number): number => skipString(j);\n" +
" return skipValue(0);\n" +
"}\n" +
"export function scanE(s: string) {\n" +
" function skipString(j: number): number { return j + 3; }\n" +
" const skipValue = (j: number): number => skipString(j);\n" +
" return skipValue(0);\n" +
"}\n",
});
expect(callsFrom('scanA')).toEqual(['function scanA::skipString (use.ts:3)']);
expect(callsFrom('scanB')).toEqual(['function scanB::skipString (use.ts:7)']);
expect(callsFrom('scanC')).toEqual(['function skipString (lib.ts:1)']);
expect(callsFrom('scanD::skipValue')).toEqual(['function scanD::skipString (use.ts:12)']);
expect(callsFrom('scanE::skipValue')).toEqual(['function scanE::skipString (use.ts:17)']);
});

it('keeps the import for a call outside the shadowing function', async () => {
await index({
'lib.ts': "export function skipString(j: number): number { return j + 1; }\n",
'use.ts':
"import { skipString } from './lib';\n" +
"export function outer() {\n" +
" function inner() { const skipString = (j: number) => j; return skipString(1); }\n" +
" return skipString(0) + inner();\n" +
"}\n",
});
expect(callsFrom('outer').filter((t) => t.includes('skipString'))).toEqual(['function skipString (lib.ts:1)']);
});
});
14 changes: 14 additions & 0 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3498,6 +3498,20 @@ export function resolveViaImport(
// A member of the guess at a module's first export is no member of
// the module: the receiver isn't known, so there is nothing to name.
if (guessed) continue;

// Nor is a member of a FUNCTION imported by name a call of the
// function: `stream.onAbort()` after `import { stream } from
// './streaming'` reads a property of the function object (#2953),
// which a namespace merged with the function may declare (vscode's
// `observableFromEvent.batchEventsGlobally()`). `fn.call(…)` and
// `fn.apply(…)` run it, and `fn.bind(…)` hands it on.
const member = ref.referenceName.slice(imp.localName.length + 1);
if (targetNode.kind === 'function' && !imp.isDefault && ESM_IMPORT_LANGUAGES.has(ref.language) && !/^(?:call|apply|bind)$/.test(member)) {
const merged = hasNamespace(targetNode.filePath, targetNode.name, context)
? typeMemberIn(targetNode.filePath, [targetNode.name], member.split('.'), context) : undefined;
if (merged) return { original: ref, targetNodeId: merged.id, confidence: 0.9, resolvedBy: 'import' };
continue;
}
}

return {
Expand Down
22 changes: 17 additions & 5 deletions src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from './types';
import { cargoManifestFields, isPythonSelfCall, matchJsStoreBindingCall, isUnresolvedJsMemberCall, matchObjectPathCall, thisScopeCaller, isVisibleAcrossFiles, matchReference, matchByFilePath, matchFunctionRef, matchDottedCallChain, matchScopedCallChain, matchMethodCall, sameLanguageFamily, crossesCodeBoundary, gateLanguageMatch, dumpNameMatcherProfile, clearNameMatcherMemos, isRustNameInScope, isRustForeignImplCallable, isRustPathCallReachable, rustChainedCallByName, matchRustUseBoundName, CASE_INSENSITIVE_LANGUAGES, isDartMemberRead, matchDartMemberRead, isDartChainLink, matchDartChainLink, isDartAnnotation, matchDartAnnotation, isStdMethodName, isGoUnknownQualified, isGoProjectLocalCall, GO_STDLIB_PACKAGES, isGoBareName, goTypePositionTarget, goDotImportedSupertype, GO_TYPE_KINDS, matchGoAssertedCall, matchGoIndexedCall, matchGoChainedCall, preferGoBuildTwin, isGoAssertedLocal, isGoLocallyBound, isPythonFromImportModule, pythonFunctionModuleAlias, pythonAttrRefResolves, matchPythonTypedLocalCall, isImportShadowedByJsBinding, crossesWorkspaceRoot, isManualMockPath, isTestSuitePath, matchNewReceiverCall, newReceiverClass, NEW_RECEIVER_SHAPE, isGuessedRecordAccessor, matchKotlinReceiverChain } from './name-matcher';
import { isPythonImportStatementModule } from './name-matcher';
import { isJsThisCall } from './name-matcher';
import { isVisibleCppMacro, clearCppMacroVisibility } from './cpp-macro-visibility';
import { isCppConstructorRef, matchCppConstructor } from './cpp-constructor';
import { isCppDeclaredTypeRef, isCppSupertypeRef, matchCppDeclaredType, matchCppSupertype, clearCppSupertypeMemos } from './cpp-supertypes';
Expand Down Expand Up @@ -99,6 +100,9 @@ const RESOLUTION_READ_EDGE_KINDS: Edge['kind'][] = ['implements', 'extends'];
const CHAIN_LANGUAGES = new Set(['java', 'kotlin', 'csharp', 'swift', 'rust', 'go', 'scala', 'dart', 'objc', 'pascal']);
const SCOPED_CHAIN_LANGUAGES = new Set(['rust']);

/** Languages whose `this.m()` the extractor records by the bare method name (isJsThisCall). */
const JS_SELF_CALL_LANGUAGES = new Set(['typescript', 'tsx', 'javascript', 'jsx', 'vue', 'svelte', 'astro']);

/** The extractor's chained-receiver encoding: `<inner>().<method>`. */
const CHAIN_SHAPE = /^(.+)\(\)\.(\w+)$/;

Expand Down Expand Up @@ -1908,7 +1912,8 @@ export class ReferenceResolver {
return this.gateLanguage(matchFunctionRef(ref, this.context), ref);
}
const viaImport = this.gateLanguage(resolveViaImport(ref, this.context), ref);
if (viaImport) {
// A local of the name in scope is the value handed on, which matchFunctionRef finds (#2949).
if (viaImport && !isImportShadowedByJsBinding(viaImport, ref, this.context)) {
const target = this.nodeById(viaImport.targetNodeId);
if (
target &&
Expand Down Expand Up @@ -2025,11 +2030,18 @@ export class ReferenceResolver {

const tImp = this.profileStages ? process.hrtime.bigint() : 0n;
// `self.get_ip()` is a method call on the instance even when the file
// also imports a function named `get_ip`: the import never names it.
const selfCall = ref.language === 'python' && ref.referenceKind === 'calls' &&
// also imports a function named `get_ip`: the import never names it. Nor
// does TS/JS's `this.findAll()` name the file's `import { findAll }` (#2954).
const selfCall = ref.referenceKind === 'calls' &&
(ref.language === 'python' || JS_SELF_CALL_LANGUAGES.has(ref.language)) &&
this.context.getImportMappings(ref.filePath, ref.language).some((m) => m.localName === ref.referenceName) &&
isPythonSelfCall(ref, this.context);
const importResult = selfCall ? null : this.gateLanguage(resolveViaImport(ref, this.context), ref);
(isPythonSelfCall(ref, this.context) || isJsThisCall(ref, this.context));
let importResult = selfCall ? null : this.gateLanguage(resolveViaImport(ref, this.context), ref);
// A name the calling code binds in scope at the reference — a parameter, a
// local, a nested function, in the calling function or one around it — is
// that binding, which the name match below finds (#2949), and so is the
// receiver of `stream.onAbort()` (#2953).
if (importResult && isImportShadowedByJsBinding(importResult, ref, this.context)) importResult = null;
if (this.profileStages) this.stageAdd('viaImport', ref, !!importResult, tImp);
if (importResult) {
if (importResult.confidence >= 0.9) return importResult;
Expand Down
Loading