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 @@ -17,6 +17,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- 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 Python, a call like `self.create_app()` on an attribute that holds a callable no longer links to a same-named function or variable in another file, nor, when the class sets that attribute itself, to another class's method of that name, so flask's app loading stops showing an example app as its callee. A method the class has, inherits or a subclass overrides still links, as does a function the class stores under that name. Thanks @inth3shadows for the report and @nilotpal-n7. (#2958)
- In Python, a builtin written bare, like `raise TimeoutError(…)`, `class Bad(ValueError)` or `sorted(rows)`, no longer links to a project class or function of that name in a file the code doesn't import, so a project's own `TimeoutError` stops collecting every file that raises the builtin. A name the file defines or imports itself still links. Thanks @inth3shadows for the report. (#3232)
- 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
119 changes: 119 additions & 0 deletions __tests__/python-builtin-names.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* A Python builtin written bare — `raise TimeoutError(…)`, `sorted(xs)`,
* `class Bad(ValueError)` — in a file that neither defines nor imports the
* name, nor star-imports a module that might, can only be the builtin (#3232).
* It must not link a project class or function of that name in a file it
* doesn't import. Where the file does define or import the name, or calls a
* method of that name on something, the name is resolved as before.
*/
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<void> {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-3232-'));
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);
}
cg = await CodeGraph.init(tempDir, { index: true });
}

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

/** Every edge out of the nodes of `file`, but `contains`, as `kind target@file`. */
function edgesFrom(file: string): string[] {
return [...cg!.getNodesByKind('file'), ...cg!.getNodesByKind('function'), ...cg!.getNodesByKind('method'), ...cg!.getNodesByKind('class')]
.filter((n) => n.filePath === file)
.flatMap((n) => cg!.getOutgoingEdges(n.id))
.filter((e) => e.kind !== 'contains')
.map((e) => {
const t = cg!.getNode(e.target);
return `${e.kind} ${t?.qualifiedName}@${t?.filePath}`;
})
.sort();
}

const FAR = 'class TimeoutError(Exception):\n pass\n\n\nclass ValueError(Exception):\n pass\n\n\nclass KeyError(Exception):\n pass\n';

describe('a Python builtin written bare (#3232)', () => {
it("the issue's repro: raising or returning a builtin exception links no project class", async () => {
await index({
'other/far.py': FAR,
't.py': [
'def run():',
' raise TimeoutError("late")',
'',
'',
'def run2():',
' raise ValueError("bad")',
'',
'',
'def run3():',
' raise KeyError("k")',
'',
'',
'def run4():',
' return TimeoutError("late")',
'',
'',
'class Bad(ValueError):',
' pass',
'',
].join('\n'),
});
expect(edgesFrom('t.py').filter((e) => e.includes('other/far.py'))).toEqual([]);
});

it('nor does a builtin function call link a project function of its name', async () => {
await index({
'other/tools.py': 'def filter(rows, pred):\n return rows\n\n\ndef compile(src):\n return src\n\n\ndef sorted(rows):\n return rows\n\n\ndef format(x):\n return x\n',
't.py': 'def go(rows):\n a = list(filter(None, rows))\n b = compile("1", "<s>", "eval")\n c = sorted(rows)\n return format(a, "")\n',
});
expect(edgesFrom('t.py').filter((e) => e.includes('other/tools.py'))).toEqual([]);
});

it('still links the name a file imports', async () => {
await index({
'other/__init__.py': '',
'other/far.py': FAR,
't.py': 'from other.far import TimeoutError\n\n\ndef run():\n raise TimeoutError("late")\n',
});
expect(edgesFrom('t.py')).toContain('instantiates TimeoutError@other/far.py');
});

it('still links the class a file defines itself', async () => {
await index({
'other/far.py': FAR,
't.py': 'class TimeoutError(Exception):\n pass\n\n\ndef run():\n raise TimeoutError("late")\n',
});
expect(edgesFrom('t.py')).toContain('instantiates TimeoutError@t.py');
expect(edgesFrom('t.py').filter((e) => e.includes('other/far.py'))).toEqual([]);
});

it('leaves a name a star import may bring as it was', async () => {
await index({
'other/__init__.py': '',
'other/far.py': FAR,
't.py': 'from other.far import *\n\n\ndef run():\n raise TimeoutError("late")\n',
});
expect(edgesFrom('t.py')).toContain('instantiates TimeoutError@other/far.py');
});

it('still links a method of that name called on self', async () => {
await index({
't.py': 'class Report:\n def format(self):\n return ""\n\n def render(self):\n return self.format()\n',
});
expect(edgesFrom('t.py')).toContain('calls Report::format@t.py');
});
});
66 changes: 66 additions & 0 deletions src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,38 @@ const PYTHON_BUILT_INS = new Set([
'super', 'self', 'cls', 'None', 'True', 'False',
]);

/**
* The rest of Python's builtins: functions, types, constants and the exception
* and warning classes. Unlike PYTHON_BUILT_INS, a name here is the builtin only
* where the file can't mean anything else by it (isUnboundPythonBuiltin):
* projects define their own `TimeoutError`, `ConnectionError`, `format` or
* `filter` all the time.
*/
const PYTHON_BUILTIN_NAMES = new Set([
'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes',
'callable', 'chr', 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate',
'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help',
'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max',
'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr',
'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip', '__import__', 'Ellipsis', 'NotImplemented', 'exit', 'quit', 'copyright', 'credits',
'license',
'BaseException', 'BaseExceptionGroup', 'Exception', 'ExceptionGroup', 'GeneratorExit', 'KeyboardInterrupt',
'SystemExit', 'ArithmeticError', 'FloatingPointError', 'OverflowError', 'ZeroDivisionError', 'AssertionError',
'AttributeError', 'BufferError', 'EOFError', 'ImportError', 'ModuleNotFoundError', 'LookupError', 'IndexError',
'KeyError', 'MemoryError', 'NameError', 'UnboundLocalError', 'OSError', 'EnvironmentError', 'IOError',
'WindowsError', 'BlockingIOError', 'ChildProcessError', 'ConnectionError', 'BrokenPipeError',
'ConnectionAbortedError', 'ConnectionRefusedError', 'ConnectionResetError', 'FileExistsError',
'FileNotFoundError', 'InterruptedError', 'IsADirectoryError', 'NotADirectoryError', 'PermissionError',
'ProcessLookupError', 'TimeoutError', 'ReferenceError', 'RuntimeError', 'NotImplementedError',
'PythonFinalizationError', 'RecursionError', 'StopAsyncIteration', 'StopIteration', 'SyntaxError',
'IndentationError', 'TabError', 'SystemError', 'TypeError', 'ValueError', 'UnicodeError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeTranslateError',
'Warning', 'BytesWarning', 'DeprecationWarning', 'EncodingWarning', 'FutureWarning', 'ImportWarning',
'PendingDeprecationWarning', 'ResourceWarning', 'RuntimeWarning', 'SyntaxWarning', 'UnicodeWarning',
'UserWarning',
]);

const PYTHON_BUILT_IN_TYPES = new Set([
'list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'bool',
'bytes', 'bytearray', 'frozenset', 'object', 'super',
Expand Down Expand Up @@ -764,6 +796,7 @@ export class ReferenceResolver {
this.goModules = null;
this.goPackageDirs.clear();
this.cachesWarmed = false;
this.pythonFileBindings = null;
// The import-resolver's and name-matcher's per-context memos assume the
// same stable window as the caches above — drop them together.
if (this.context) {
Expand Down Expand Up @@ -3744,6 +3777,32 @@ export class ReferenceResolver {
!PYTHON_BUILT_IN_TYPES.has(ref.referenceName.slice(0, dot));
}

/**
* The file isUnboundPythonBuiltin read last: every name its nodes have and
* its imports bind, and whether it star-imports a module. References arrive
* grouped by file, so one slot serves them all.
*/
private pythonFileBindings: { filePath: string; names: Set<string>; star: boolean } | null = null;

/**
* Whether a Python reference to a builtin's name (PYTHON_BUILTIN_NAMES) can
* only mean the builtin: written bare (`self.format()` and `errors.Timeout`
* name a member), in a file that defines nothing of that name, imports
* nothing under it and star-imports no module that might export it.
*/
private isUnboundPythonBuiltin(ref: UnresolvedRef): boolean {
const line = (this.context.getFileLines?.(ref.filePath) ?? this.context.readFile(ref.filePath)?.split(/\r?\n/))?.[ref.line - 1];
if (line === undefined || !line.startsWith(ref.referenceName, ref.column) || /\.\s*$/.test(line.slice(0, ref.column))) return false;
let file = this.pythonFileBindings;
if (file?.filePath !== ref.filePath) {
const names = new Set(this.context.getNodesInFile(ref.filePath).map((n) => n.name));
for (const m of this.context.getImportMappings(ref.filePath, 'python')) names.add(m.localName);
const star = /^[ \t]*from[ \t]+[\w.]+[ \t]+import[ \t(]*\*/m.test(this.context.readFile(ref.filePath) ?? '');
this.pythonFileBindings = file = { filePath: ref.filePath, names, star };
}
return !file.star && !file.names.has(ref.referenceName);
}

/**
* True when the Go file imports `qualifier` — by its last path segment or
* an alias — from a package of one of the project's own modules.
Expand Down Expand Up @@ -3792,6 +3851,13 @@ export class ReferenceResolver {
if (ref.language === 'python' && PYTHON_BUILT_INS.has(name)) {
return true;
}
// The rest of them, `raise TimeoutError(…)` or `sorted(xs)`, written bare in
// a file that neither defines nor imports the name, nor star-imports a module
// that could: there it can only be the builtin, never a project class or
// function of that name in a file it doesn't import (#3232).
if (ref.language === 'python' && PYTHON_BUILTIN_NAMES.has(name) && this.isUnboundPythonBuiltin(ref)) {
return true;
}

// Python built-in method calls (e.g., list.extend, dict.update)
if (ref.language === 'python') {
Expand Down