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 @@ -15,6 +15,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
### Fixes

- In Python, `import time` no longer links the importing file to a project function that happens to be named `time`, so such a function stops listing every file that imports the standard library module among its callers and in its impact. The same goes for `json`, `copy`, `random`, `logging` and any other module, and for a fallback variable like `brotli = None` beside a guarded `import brotli`. Thanks @inth3shadows for the report. (#3239)
- In Python, a call to a function or method declared with `typing.overload` now links to the `def` that runs instead of the first `@overload` stub, so the implementation shows its callers and a call path goes on through it, while a stub with no implementation below it, as in a `Protocol`, stays the target. Only `typing`'s and `typing_extensions`' `overload` counts, not another library's like plum's, whose bodies run, and `codegraph sync` moves the call when an implementation is added or removed. Re-index Python projects after upgrading, since an existing index keeps the stub link. (#2963)
- In Rust, a call through a module that a glob `use` brings in, like `gzip::write()` in a test module with `use super::*`, or that a `use` inside the function names, now links to that module's function again. Thanks @Egrn for the report and @mohitdixit02. (#3253)

## [1.6.3] - 2026-11-17
Expand Down
307 changes: 307 additions & 0 deletions __tests__/python-overload-implementation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
/**
* A Python name declared with `typing.overload` runs one function: the `def`
* below its stubs. The stubs are indexed as separate nodes, and a call by name
* landed on the first of them, whose body is `...`. So the implementation had no
* callers, a call path broke at the stub, and click's `command`, called hundreds
* of times, looked unreferenced.
*/
import { afterEach, describe, expect, it } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';
import type { Node } from '../src/types';

const DECO = [
'import typing as t', // 1
'from typing import overload', // 2
'', // 3
'@t.overload', // 4
'def command(name: t.Callable) -> int: ...', // 5
'', // 6
'@overload # a comment on the decorator', // 7
'# and one between it and the def', // 8
'def command(name: str | None = None) -> str: ...', // 9
'', // 10
'def command(name=None):', // 11
' return real_work(name)', // 12
'', // 13
'def real_work(n):', // 14
' return n', // 15
'', // 16
'class Prompt:', // 17
' @t.overload', // 18
' @classmethod', // 19
' def ask(cls, p: str) -> str: ...', // 20
'', // 21
' @classmethod', // 22
' @t.overload', // 23
' def ask(cls, p: str, d: int) -> int: ...', // 24
'', // 25
' @classmethod', // 26
' def ask(cls, p, d=None):', // 27
' return real_work(p)', // 28
'',
].join('\n');

const USE = [
'import pkg',
'from pkg import command, Prompt',
'',
'def run():',
' command("x")',
' Prompt.ask("y")',
'',
'def through_module():',
' pkg.command("x")',
'',
].join('\n');

const PACKAGE = { 'pkg/deco.py': DECO, 'pkg/__init__.py': 'from .deco import command, Prompt\n', 'use.py': USE };

describe('a call to a Python name declared with typing.overload', () => {
let root: string;
let cg: CodeGraph;

const index = async (files: Record<string, string>): Promise<void> => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-overload-'));
for (const [file, source] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
fs.writeFileSync(path.join(root, file), source);
}
cg = await CodeGraph.init(root, { index: true });
};

afterEach(() => {
cg.destroy();
fs.rmSync(root, { recursive: true, force: true });
});

const named = (name: string): Node[] => [...cg.getNodesByKind('function'), ...cg.getNodesByKind('method')]
.filter((n) => n.name === name);
const fn = (name: string): Node => named(name)[0]!;
const calleeLines = (caller: string, name: string): number[] => cg.getCallees(fn(caller).id)
.filter((c) => c.node.name === name).map((c) => c.node.startLine).sort((a, b) => a - b);

it('links the implementation, not the first stub', async () => {
await index(PACKAGE);
expect(calleeLines('run', 'command')).toEqual([11]);
expect(calleeLines('through_module', 'command')).toEqual([11]);
});

it('links the implementation of a classmethod, wherever overload stands among the decorators', async () => {
await index(PACKAGE);
expect(calleeLines('run', 'ask')).toEqual([27]);
});

it('gives the implementation the callers, and leaves the stubs without any', async () => {
await index(PACKAGE);
const impl = named('command').find((n) => n.startLine === 11)!;
expect(cg.getCallers(impl.id).map((c) => c.node.name)).toEqual(expect.arrayContaining(['run', 'through_module']));
for (const stub of named('command').filter((n) => n.startLine !== 11)) {
expect(cg.getCallers(stub.id)).toEqual([]);
}
});

it('reads the decorator under the name the file imported it as', async () => {
await index({
'aliased.py': [
'from typing import overload as ov',
'',
'@ov',
'def pick(a: int) -> int: ...', // 4
'',
'@ov',
'def pick(a: str) -> str: ...', // 7
'',
'def pick(a):', // 9
' return a',
'',
].join('\n'),
'use.py': [
'from aliased import pick',
'',
'def caller():',
' return pick(1)',
'',
].join('\n'),
});
expect(calleeLines('caller', 'pick')).toEqual([9]);
});

it('reads a decorator with a blank line between it and the def', async () => {
await index({
'spaced.py': [
'from typing import overload',
'',
'@overload',
'',
'def pick(a: int) -> int: ...', // 5
'',
'def pick(a):', // 7
' return a',
'',
].join('\n'),
'use.py': [
'from spaced import pick',
'',
'def caller():',
' return pick(1)',
'',
].join('\n'),
});
expect(calleeLines('caller', 'pick')).toEqual([7]);
});

it('takes the implementation below the stub it reached, when a file has two sets', async () => {
await index({
'twice.py': [
'import sys',
'from typing import overload',
'',
'if sys.version_info >= (3, 11):',
' @overload',
' def pick(a: int) -> int: ...', // 6
' def pick(a):', // 7
' return a',
'else:',
' @overload',
' def pick(a: str) -> str: ...', // 11
' def pick(a):', // 12
' return a',
'',
'def caller():',
' return pick(1)',
'',
].join('\n'),
});
const lines = calleeLines('caller', 'pick');
expect(lines.length).toBe(1);
expect([7, 12]).toContain(lines[0]);
});

it('keeps the stub when no implementation follows it', async () => {
await index({
'proto.py': [
'from typing import Protocol, overload',
'',
'class Reader(Protocol):',
' @overload',
' def read(self, n: int) -> bytes: ...', // 5
' @overload',
' def read(self) -> str: ...', // 7
'',
'def use(r: Reader):',
' return r.read()',
'',
].join('\n'),
});
expect(calleeLines('use', 'read').length).toBe(1);
expect([5, 7]).toContain(calleeLines('use', 'read')[0]);
});

it('leaves a same-named method of another class alone', async () => {
await index({
'two.py': [
'from typing import overload',
'',
'class A:',
' @overload',
' def go(self, x: int) -> int: ...', // 5
' def go(self, x):', // 6
' return x',
'',
'class B:',
' def go(self, x):', // 10
' return x',
'',
'def use():',
' A().go(1)',
' B().go(1)',
'',
].join('\n'),
});
expect(calleeLines('use', 'go')).toEqual([6, 10]);
});
});

describe('a Python overload a sync or another library changes', () => {
let root: string;
let cg: CodeGraph;

const write = (file: string, lines: string[]): void => {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
fs.writeFileSync(path.join(root, file), lines.join('\n') + '\n');
};

afterEach(() => {
cg.destroy();
fs.rmSync(root, { recursive: true, force: true });
});

const calleeLines = (caller: string, name: string): number[] => {
const from = cg.getNodesByKind('function').find((n) => n.name === caller)!;
return cg.getCallees(from.id).filter((c) => c.node.name === name).map((c) => c.node.startLine).sort((a, b) => a - b);
};

const STUBS = [
'import typing as t',
'',
'',
'@t.overload',
'def command(name: str) -> str: ...', // 5
'',
'',
'@t.overload',
'def command(name: int) -> int: ...', // 9
];

it('moves the call to an implementation a sync adds below the stubs, and back when it goes', async () => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-overload-sync-'));
write('pkg/deco.py', STUBS);
write('use.py', ['from pkg.deco import command', '', '', 'def go():', ' return command("x")']);
cg = await CodeGraph.init(root, { index: true });
expect(calleeLines('go', 'command')).toEqual([5]);

write('pkg/deco.py', [...STUBS, '', '', 'def command(name=None):', ' return name']);
await cg.sync();
expect(calleeLines('go', 'command')).toEqual([12]);

write('pkg/deco.py', STUBS);
await cg.sync();
expect(calleeLines('go', 'command')).toEqual([5]);
});

it("leaves another library's overload alone: its bodies run", async () => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-overload-plum-'));
write('multi/g.py', [
'from plum import dispatch, overload',
'',
'@overload',
'def g(x: int):', // 4
' return x + 1',
'',
'@overload',
'def g(x: str):', // 8
' return x',
'',
'@dispatch',
'def g(x):', // 12
' pass',
]);
write('multi/h.py', [
'import plum',
'',
'@plum.overload',
'def h(x: int):', // 4
' return x',
'',
'def h(x):', // 7
' pass',
]);
write('use.py', ['from multi.g import g', 'from multi.h import h', '', '', 'def go():', ' return g(1), h(1)']);
cg = await CodeGraph.init(root, { index: true });
expect(calleeLines('go', 'g')).toEqual([4]);
expect(calleeLines('go', 'h')).toEqual([4]);
});
});
14 changes: 10 additions & 4 deletions src/db/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5727,7 +5727,8 @@ export class QueryBuilder {

/**
* Distinct `file\0name` pairs defined by the given files — the shape sync's
* definition delta needs (CG-33).
* definition delta needs (CG-33), with `\0count` after a Python name that
* is defined more than once in its file.
*
* Deliberately NOT `getNodeNamesByFiles`: a bare name set is taken over the
* WHOLE changed batch, so a name that moves between two files in one commit
Expand All @@ -5744,10 +5745,15 @@ export class QueryBuilder {
const chunk = filePaths.slice(i, i + SQLITE_PARAM_CHUNK_SIZE);
const placeholders = chunk.map(() => '?').join(',');
const rows = this.db
.prepare(`SELECT DISTINCT file_path, name FROM nodes WHERE file_path IN (${placeholders})`)
.all(...chunk) as Array<{ file_path: string; name: string }>;
.prepare(`SELECT file_path, name,
SUM(CASE WHEN language = 'python' AND kind IN ('function', 'method') THEN 1 ELSE 0 END) AS defs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include overload classification in the sync delta

When an edit changes whether a same-name Python def is a typing stub without changing the number of function/method nodes—for example, switching its overload import from typing to Plum—the function still produces the same file\0name\0count key. definitionDelta therefore omits that function name, so resurrectStaleResolutionEdges() does not reopen callers in unchanged files and their persisted edges keep the old target; include overload binding or decorator state in the delta.

AGENTS.md reference: AGENTS.md:L182-L182

Useful? React with 👍 / 👎.

FROM nodes WHERE file_path IN (${placeholders}) GROUP BY file_path, name`)
.all(...chunk) as Array<{ file_path: string; name: string; defs: number }>;
// NUL-joined: a path or a symbol name can contain a space, never a NUL.
for (const row of rows) pairs.add(`${row.file_path}\0${row.name}`);
// A Python name defined more than once in a file carries how many times:
// the `def` below a name's `@overload` stubs is the one that runs, so
// adding or removing one moves a call no other name change records.
for (const row of rows) pairs.add(row.defs > 1 ? `${row.file_path}\0${row.name}\0${row.defs}` : `${row.file_path}\0${row.name}`);
}
return pairs;
}
Expand Down
2 changes: 1 addition & 1 deletion src/extraction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4144,7 +4144,7 @@ export class ExtractionOrchestrator {
// first measurement of this fix.
const pairsAfter = this.queries.getNodeNamePairsByFiles(filesToIndex);
const deltaNames = new Set<string>();
const nameOf = (pair: string) => pair.slice(pair.indexOf('\0') + 1);
const nameOf = (pair: string) => pair.split('\0')[1]!;
for (const pair of pairsBefore) if (!pairsAfter.has(pair)) deltaNames.add(nameOf(pair));
for (const pair of pairsAfter) if (!pairsBefore.has(pair)) deltaNames.add(nameOf(pair));
const definitionDelta = [...deltaNames];
Expand Down
6 changes: 6 additions & 0 deletions src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
} from './pascal-scope';
import { gateTypeParameter, clearTypeParameterMemos } from './type-parameters';
import { gateDartLocal, clearDartLocalScopeMemos } from './dart-local-scope';
import { preferPythonImplementation, clearPythonOverloadMemos } from './python-overloads';
import { clearCppTypeAliasMemos } from './cpp-type-aliases';
import { adoptProjectScans, readProjectScans, type ProjectScans } from './project-scans';
import { clearCppIncluderMemos } from './cpp-includers';
Expand Down Expand Up @@ -770,6 +771,7 @@ export class ReferenceResolver {
clearPascalScopeMemos(this.context);
clearTypeParameterMemos(this.context);
clearDartLocalScopeMemos(this.context);
clearPythonOverloadMemos(this.context);
clearCppTypeAliasMemos(this.context);
clearCppSupertypeMemos(this.context);
clearCppIncluderMemos(this.context);
Expand Down Expand Up @@ -1654,6 +1656,10 @@ export class ReferenceResolver {
if (declaringFile !== undefined && declaringFile !== ref.filePath &&
!reachesAmbientModule(ref, specifier!, declaringFile, this.context)) return null;
}
if (resolved && ref.language === 'python') {
const implemented = preferPythonImplementation(resolved, this.nodeById(resolved.targetNodeId), this.context);
if (implemented !== resolved) return implemented;
}
if (!resolved || ref.referenceKind !== 'calls') return resolved;
// A Pascal call to data runs only a routine the data holds, in scope, and
// one to a routine nested in another comes only from inside that one (see
Expand Down
Loading