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
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`, like click's `command` and `prompt`, 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. A stub with no implementation below it, as in a `Protocol`, stays the target, and another library's `overload` whose bodies all run is left alone. Thanks @inth3shadows for the report and @nilotpal-n7. (#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)
- In Rust, `codegraph_explore`'s blast radius now recognizes unit tests in a `#[cfg(test)]` module or a `tests.rs` file, instead of reporting "no tests found" for the functions they test. Thanks @moogiemode for the report and @maxmilian. (#3265)
- In Rust, a function or method passed as a value through its path, like `g.map(Graph::counts)` or `.map(Self::helper)`, now counts in its callers and impact the way a function passed by name already did, linked only when the path names it for certain: never another type's method of the same name, and never a method of a trait implementation, since which one Rust uses there depends on the type of the argument. Thanks @Egrn for the report and @inth3shadows. (#3254)
Expand Down
200 changes: 200 additions & 0 deletions __tests__/python-overload-stubs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/**
* A Python name declared with `typing.overload` is a run of `def`s: stubs whose
* bodies are `...`, then the `def` without `@overload` that every call runs.
* A reference to the name links to that implementation, not to the first stub
* (#2963), whether it is a call, an import, a decorator use or a method call,
* and a stub with nothing below it (a Protocol) stays the target. Another
* library's `overload` (plum's), whose bodies all run, is left alone, and a
* sync moves the callers when an implementation is added or removed.
*/
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 | undefined;
let cg: CodeGraph | null = null;

async function index(files: Record<string, string>): Promise<CodeGraph> {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-2963-'));
write(files);
cg = await CodeGraph.init(tempDir, { index: true });
return cg;
}

function write(files: Record<string, string>): void {
for (const [rel, source] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(tempDir!, rel)), { recursive: true });
fs.writeFileSync(path.join(tempDir!, rel), source);
}
}

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

/** Every edge into a def named `name`, as `kind from-name -> def line`. */
function into(name: string): string[] {
return [...cg!.getNodesByKind('function'), ...cg!.getNodesByKind('method')]
.filter((n) => n.name === name)
.flatMap((n) => cg!.getIncomingEdges(n.id)
.filter((e) => e.kind !== 'contains')
.map((e) => `${e.kind} ${cg!.getNode(e.source)?.name} -> ${n.startLine}`))
.sort();
}

const DECO = [
'import typing as t',
'',
'',
'@t.overload',
'def command(name: t.Callable) -> int: ...',
'',
'',
'@t.overload',
'def command(name: str | None = None) -> str: ...',
'',
'',
'def command(name=None):',
' return real_work(name)',
'',
'',
'def real_work(n):',
' return n',
'',
'',
'class Prompt:',
' @t.overload',
' @classmethod',
' def ask(cls, p: str) -> str: ...',
'',
' @t.overload',
' @classmethod',
' def ask(cls, p: str, d: int) -> int: ...',
'',
' @classmethod',
' def ask(cls, p, d=None):',
' return real_work(p)',
'',
].join('\n');

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

describe('a reference to a Python name declared with typing.overload (#2963)', () => {
it("the issue's repro: calls, the decorator use and the imports reach the implementation", async () => {
await index({ 'pkg/deco.py': DECO, 'pkg/__init__.py': 'from .deco import command, Prompt\n', 'use.py': USE });
const command = into('command');
expect(command.filter((e) => !e.endsWith('-> 12'))).toEqual([]);
expect(command).toContain('calls run -> 12');
expect(command.some((e) => e.startsWith('imports '))).toBe(true);
expect(into('ask')).toEqual(['calls run -> 30']);
// The path from run reaches real_work through the implementation.
const impl = cg!.getNodesByKind('function').find((n) => n.name === 'command' && n.startLine === 12)!;
expect(cg!.getOutgoingEdges(impl.id).filter((e) => e.kind === 'calls').map((e) => cg!.getNode(e.target)?.name)).toEqual(['real_work']);
});

it.each([
['bare, imported from typing', 'from typing import overload\n', '@overload'],
['under an alias', 'from typing import overload as ov\n', '@ov'],
['through the typing module', 'import typing\n', '@typing.overload'],
['from typing_extensions', 'from typing_extensions import overload\n', '@overload'],
['with a blank line and a comment before the def', 'from typing import overload\n', '@overload\n\n# int in, int out'],
])('reads the decorator written %s', async (_label, header, decorator) => {
await index({
'lib.py': `${header}\n\n${decorator}\ndef go(x: int) -> int: ...\n\n\n${decorator}\ndef go(x: str) -> str: ...\n\n\ndef go(x):\n return x\n`,
'use.py': 'from lib import go\n\n\ndef main():\n return go(1)\n',
});
const implLine = fs.readFileSync(path.join(tempDir!, 'lib.py'), 'utf8').split('\n').indexOf('def go(x):') + 1;
expect(into('go').filter((e) => e.startsWith('calls '))).toEqual([`calls main -> ${implLine}`]);
});

it('reaches the implementation of an overloaded method called on an instance', async () => {
await index({
'store.py': [
'from typing import overload',
'',
'',
'class Store:',
' @overload',
' def get(self, key: int) -> int: ...',
' @overload',
' def get(self, key: str) -> str: ...',
' def get(self, key):',
' return key',
'',
'',
'def use():',
' s = Store()',
' return s.get(1)',
'',
].join('\n'),
});
expect(into('get')).toEqual(['calls use -> 9']);
});

it('keeps the stub when no implementation follows it, as in a Protocol', async () => {
await index({
'proto.py': [
'from typing import Protocol, overload',
'',
'',
'class Reader(Protocol):',
' @overload',
' def read(self, n: int) -> bytes: ...',
' @overload',
' def read(self) -> bytes: ...',
'',
'',
'def use(r: Reader):',
' return r.read(1)',
'',
].join('\n'),
});
expect(into('read')).toEqual(['calls use -> 6']);
});

it("leaves another library's overload alone: its bodies all run", async () => {
await index({
'lib.py': 'from plum import overload\n\n\n@overload\ndef go(x: int):\n return x\n\n\n@overload\ndef go(x: str):\n return x\n\n\ndef go(x):\n return x\n',
'use.py': 'from lib import go\n\n\ndef main():\n return go(1)\n',
});
expect(into('go').filter((e) => e.startsWith('calls '))).toEqual(['calls main -> 5']);
});
});

describe('a sync of a Python overload set (#2963)', () => {
const STUBS = 'from typing import overload\n\n\n@overload\ndef go(x: int) -> int: ...\n\n\n@overload\ndef go(x: str) -> str: ...\n';
const IMPL = '\n\ndef go(x):\n return x\n';
const USER = 'from lib import go\n\n\ndef main():\n return go(1)\n';

it('moves the callers to an implementation added below the stubs, and back when it goes', async () => {
await index({ 'lib.py': STUBS, 'use.py': USER });
expect(into('go').filter((e) => e.startsWith('calls '))).toEqual(['calls main -> 5']);

write({ 'lib.py': STUBS + IMPL });
await cg!.sync();
expect(into('go').filter((e) => e.startsWith('calls '))).toEqual(['calls main -> 12']);

write({ 'lib.py': STUBS });
await cg!.sync();
expect(into('go').filter((e) => e.startsWith('calls '))).toEqual(['calls main -> 5']);
});
});
14 changes: 11 additions & 3 deletions src/db/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5763,10 +5763,18 @@ 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(language = 'python' AND kind IN ('function', 'method')) AS python_defs
FROM nodes WHERE file_path IN (${placeholders}) GROUP BY file_path, name`)
.all(...chunk) as Array<{ file_path: string; name: string; python_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 a file defines more than once (typing.overload stubs and
// the def below them) also counts its defs, behind a \u0001 in the file's
// half: adding or removing the implementation moves every call to the
// name (#2963) while the set of names stays the same.
for (const row of rows) {
const file = row.python_defs > 1 ? `${row.file_path}\u0001${row.python_defs}` : row.file_path;
pairs.add(`${file}\0${row.name}`);
}
}
return pairs;
}
Expand Down
7 changes: 5 additions & 2 deletions src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,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 @@ -781,6 +782,7 @@ export class ReferenceResolver {
clearCMacroRenames(this.context);
clearCFeatureVariantMemos(this.context);
clearAmbientModuleMemos(this.context);
clearPythonOverloadMemos(this.context);
clearDeclaredDependencies(this.context);
}
}
Expand Down Expand Up @@ -1628,10 +1630,11 @@ export class ReferenceResolver {
const scoped = this.gateRustScope(candidate, ref);
// A Go name its package defines once per build target is the definition
// the reference's file builds with (see preferGoBuildTwin).
const resolved = preferGoBuildTwin(this.gateSuperSelfCall(
// A Python name declared with typing.overload runs the def below its stubs (#2963).
const resolved = preferPythonImplementation(preferGoBuildTwin(this.gateSuperSelfCall(
scoped?.resolvedBy === 'framework' ? this.gateFrameworkLanguage(scoped, ref) : this.gateLanguage(scoped, ref),
ref,
), ref, this.context);
), ref, this.context), ref, this.context);
// A Dart class whose field holds its own type (`class Node { Node? next; }`)
// names itself: a self-edge that says nothing (#2327).
if (resolved && ref.language === 'dart' && ref.referenceKind === 'references' &&
Expand Down
109 changes: 109 additions & 0 deletions src/resolution/python-overloads.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* Python's `typing.overload` (#2963). A name declared with overloads is a run
* of `def`s of one name in one scope: `@overload` stubs, whose bodies are
* `...` and never run, and below them the `def` without the decorator, which
* every call runs. Each `def` is its own node, so a reference resolved by name
* landed on the first stub: click's `command` has four stubs above it, and its
* callers all stopped there, while the implementation, whose body holds the
* real callees, looked unreferenced.
*
* A resolved reference whose target is a stub moves to the implementation
* below it, at the one place every strategy's answer passes through, so a
* call, an import and a function handed on as a value agree. A stub with no
* implementation below it (a `Protocol`, a `.pyi` stub file) stays the target.
*
* Python nodes keep no decorators, so they are read from the lines above each
* `def`. Only typing's `overload` declares stubs: plum's or multipledispatch's
* overloads are real implementations, which the decorator dispatches between.
*/
import type { Node } from '../types';
import type { ResolutionContext, ResolvedRef } from './types';

/** Per context: a def's id → the id of the def a call to it runs, or null when that is the def itself. */
const RUNS_INSTEAD = new WeakMap<ResolutionContext, Map<string, string | null>>();

export function clearPythonOverloadMemos(context: ResolutionContext): void {
RUNS_INSTEAD.delete(context);
}

/** The modules whose `overload` marks a stub. */
const TYPING = new Set(['typing', 'typing_extensions']);

/** How many lines above a `def` its decorators may reach (a decorator's arguments can span lines). */
const DECORATOR_REACH = 24;

/**
* `resolved`, moved to the implementation when its target is a Python
* `@overload` stub that has one below it in its scope.
*/
export function preferPythonImplementation(
resolved: ResolvedRef | null,
ref: { language: string },
context: ResolutionContext,
): ResolvedRef | null {
if (!resolved || ref.language !== 'python') return resolved;
let memo = RUNS_INSTEAD.get(context);
if (!memo) RUNS_INSTEAD.set(context, (memo = new Map()));
let runs = memo.get(resolved.targetNodeId);
if (runs === undefined) {
const target = context.getNodeById?.(resolved.targetNodeId) ?? null;
runs = target ? implementationOf(target, context) : null;
memo.set(resolved.targetNodeId, runs);
}
return runs === null ? resolved : { ...resolved, targetNodeId: runs };
}

/** The implementation a stub stands for: the first `def` of its scope and name below it that is no stub. */
function implementationOf(def: Node, context: ResolutionContext): string | null {
if (def.language !== 'python' || (def.kind !== 'function' && def.kind !== 'method')) return null;
const named = context.getNodesInFileNamed?.(def.filePath, def.name) ??
context.getNodesInFile(def.filePath).filter((n) => n.name === def.name);
const scope = named.filter((n) => n.kind === def.kind && n.qualifiedName === def.qualifiedName);
// The one def of its name in its scope: the common case, decided without reading the file.
if (scope.length < 2) return null;
const overload = overloadSpellings(def.filePath, context);
const lines = context.getFileLines?.(def.filePath) ?? context.readFile(def.filePath)?.split(/\r?\n/) ?? [];
if (!isOverloadStub(def, lines, overload)) return null;
const below = scope.filter((n) => n.startLine > def.startLine).sort((a, b) => a.startLine - b.startLine);
return below.find((n) => !isOverloadStub(n, lines, overload))?.id ?? null;
}

/**
* How a file can write typing's `overload` as a decorator: bare names (`overload`,
* or the alias of `from typing import overload as ov`) and the names a typing
* module goes by (`typing`, or `t` after `import typing as t`). A bare
* `overload` the file imports from another module is that module's.
*/
function overloadSpellings(filePath: string, context: ResolutionContext): { bare: Set<string>; modules: Set<string> } {
const imports = context.getImportMappings(filePath, 'python');
const bare = new Set<string>();
const modules = new Set(TYPING);
for (const m of imports) {
if (m.isNamespace && TYPING.has(m.source)) modules.add(m.localName);
else if (!m.isNamespace && m.exportedName === 'overload' && TYPING.has(m.source)) bare.add(m.localName);
}
// Not imported by name at all (`from typing import *`): the bare name is typing's.
if (!imports.some((m) => m.localName === 'overload')) bare.add('overload');
return { bare, modules };
}

/** Whether the decorators above a `def` hold typing's `overload`. */
function isOverloadStub(def: Node, lines: string[], overload: { bare: Set<string>; modules: Set<string> }): boolean {
// Upward from the line above the `def`: decorators, and inside a decorator's
// parentheses the lines of its arguments. A `)` read going up opens such a
// span, which its `(` closes.
let open = 0;
for (let i = def.startLine - 2; i >= 0 && i >= def.startLine - 1 - DECORATOR_REACH; i--) {
const text = (lines[i] ?? '').trim();
open += (text.match(/\)/g)?.length ?? 0) - (text.match(/\(/g)?.length ?? 0);
if (open > 0) continue;
open = 0;
if (text === '' || text.startsWith('#')) continue;
if (!text.startsWith('@')) return false;
const m = /^@\s*((?:\w+\s*\.\s*)*)(\w+)/.exec(text);
if (!m) continue;
const via = m[1]!.replace(/\s/g, '').replace(/\.$/, '');
if (via ? m[2] === 'overload' && overload.modules.has(via) : overload.bare.has(m[2]!)) return true;
}
return false;
}