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 like `self.create_app()` or `cls.factory()` on an attribute holding a callable no longer links to a same-named module-level function or variable in another file, or to a variable in its own file, unless the class binds the attribute to that name (`x = staticmethod(x)`, `self.x = mod.x`, `Cls.x = x`). (#2958)
- 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
281 changes: 281 additions & 0 deletions __tests__/python-self-call-foreign-function.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
/**
* `self.x()` names a member of the instance. When the class has no such method,
* `x` is an attribute holding a callable, and nothing in the file says which.
* The bare name then matched a module-level `x` in any other file: flask's
* `ScriptInfo.load_app` called `self.create_app()`, the callable it was handed,
* and that linked to an example app's `create_app`.
*
* A function of the caller's own file stays. attrs defines `_is_comparable_to`
* at module level in `_cmp.py` and puts it in the class it builds there, so
* `self._is_comparable_to(other)` really runs it: a test run records that call.
*/
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';

describe('a Python call on self or cls', () => {
let root: string;
let cg: CodeGraph;

const index = async (files: Record<string, string[]>): Promise<void> => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-self-'));
for (const [file, lines] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
fs.writeFileSync(path.join(root, file), lines.join('\n') + '\n');
}
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 callees = (caller: string): string[] => cg.getCallees(named(caller)[0]!.id)
.map((c) => `${c.node.filePath}:${c.node.name}`).sort();

it('does not reach a function of another file through an attribute holding a callable', async () => {
await index({
'pkg/cli.py': [
'class ScriptInfo:',
' def __init__(self, create_app=None):',
' self.create_app = create_app',
'',
' def load_app(self):',
' return self.create_app()',
],
'examples/factory.py': ['def create_app():', ' return object()'],
});
expect(callees('load_app')).toEqual([]);
});

it('does not reach one through an attribute a tuple binds', async () => {
await index({
'tests/test_repo.py': [
'class TestRepo:',
' def setUp(self):',
' self.repo, self.run = make_repo()',
'',
' def test_add(self):',
' self.run("git", "add")',
],
'harness/shell.py': ['def run(*args):', ' return args'],
});
expect(callees('test_add')).toEqual([]);
});

it('does not reach one on cls', async () => {
await index({
'pkg/model.py': [
'class Model:',
' @classmethod',
' def build(cls):',
' return cls.factory()',
],
'other/factories.py': ['def factory():', ' return object()'],
});
expect(callees('build')).toEqual([]);
});

it('does not reach one that the file imports', async () => {
await index({
'pkg/worker.py': [
'from other.tasks import run',
'',
'class Worker:',
' def __init__(self, run):',
' self.run = run',
'',
' def go(self):',
' return self.run()',
'',
' def plain(self):',
' return run()',
],
'other/tasks.py': ['def run():', ' return 1'],
});
expect(callees('go')).toEqual([]);
expect(callees('plain')).toEqual(['other/tasks.py:run']);
});

it('keeps a function of its own file, which the file can put on the class', async () => {
await index({
'pkg/cmp.py': [
'def _is_comparable_to(self, other):',
' return True',
'',
'def make_class():',
' return type("Made", (), {"_is_comparable_to": _is_comparable_to, "__eq__": eq})',
'',
'def eq(self, other):',
' return self._is_comparable_to(other)',
],
});
expect(callees('eq')).toEqual(['pkg/cmp.py:_is_comparable_to']);
});

it('keeps a class of another file, which an attribute holds under its own name', async () => {
await index({
'pkg/graph.py': ['class Graph:', ' pass'],
'tests/test_graph.py': [
'import pkg.graph as nx',
'',
'class TestGraph:',
' def setup_method(self):',
' self.Graph = nx.Graph',
'',
' def test_empty(self):',
' return self.Graph()',
],
});
expect(cg.getCallees(named('test_empty')[0]!.id).map((c) => c.node.name)).toEqual(['Graph']);
});

it('does not reach a module-level variable of another file', async () => {
await index({
'lab/model.py': [
'class Layer:',
' def __call__(self, x):',
' return x',
'',
'class MLP:',
' def __init__(self):',
' self.out = Layer()',
'',
' def forward(self, x):',
' return self.out(x)',
],
'scripts/export.py': ['out = (1, 2)'],
});
expect(cg.getCallees(named('forward')[0]!.id).filter((c) => c.node.name === 'out')).toEqual([]);
});

it('does not reach a module-level variable of its own file', async () => {
await index({
'lab/model.py': [
'out = (1, 2)',
'',
'def make():',
' return 1',
'',
'class MLP:',
' def __init__(self):',
' self.out = make()',
'',
' def go(self, x):',
' return self.out(x)',
],
});
expect(callees('go')).toEqual([]);
});

it('keeps an imported function the class body binds under its own name', async () => {
await index({
'other/helpers.py': ['def validate():', ' return 1'],
'pkg/m.py': [
'from other.helpers import validate',
'',
'class M:',
' validate = staticmethod(validate)',
'',
' def go(self):',
' return self.validate()',
],
});
expect(callees('go')).toEqual(['other/helpers.py:validate']);
});

it('keeps an imported function self is bound to, but not a parameter of the same name', async () => {
await index({
'other/helpers.py': ['def validate():', ' return 1', '', 'def check():', ' return 2'],
'pkg/m.py': [
'from other.helpers import validate, check',
'',
'class M:',
' def __init__(self, check):',
' self.validate = validate',
' self.check = check',
'',
' def go(self):',
' return self.validate()',
'',
' def other(self):',
' return self.check()',
],
});
expect(callees('go')).toEqual(['other/helpers.py:validate']);
expect(callees('other')).toEqual([]);
});

it('keeps a module-level alias self is bound to through its module', async () => {
await index({
'pkg/db.py': ['class _Session:', ' pass', '', 'Session = _Session'],
'pkg/repo.py': [
'from pkg import db',
'',
'class Repo:',
' def __init__(self):',
' self.Session = db.Session',
'',
' def go(self):',
' return self.Session()',
],
});
expect(cg.getCallees(named('go')[0]!.id).map((c) => c.node.filePath)).toEqual(['pkg/db.py']);
});

it('keeps a function another file puts on the class', async () => {
await index({
'pkg/c.py': ['class C:', ' def go(self):', ' return self.extra()'],
'pkg/ext.py': ['from pkg.c import C', '', 'def extra(self):', ' return 1', '', 'C.extra = extra'],
});
expect(callees('go')).toEqual(['pkg/ext.py:extra']);
});

it('takes cls.x() for the class method, not a function the file imports', async () => {
await index({
'other/factories.py': ['def create():', ' return object()'],
'pkg/model.py': [
'from other.factories import create',
'',
'class Model:',
' @classmethod',
' def create(cls):',
' return cls()',
'',
' @classmethod',
' def make(cls):',
' return cls.create()',
],
});
expect(callees('make')).toEqual(['pkg/model.py:create']);
});

it('keeps a method it inherits from a class in another file', async () => {
await index({
'pkg/base.py': ['class Base:', ' def setup(self):', ' return 1'],
'pkg/child.py': [
'from pkg.base import Base',
'',
'class Child(Base):',
' def go(self):',
' return self.setup()',
],
'other/setup.py': ['def setup():', ' return 2'],
});
expect(callees('go')).toEqual(['pkg/base.py:setup']);
});

it('leaves a bare call of the same name alone', async () => {
await index({
'pkg/use.py': ['def go():', ' return helper()'],
'other/helpers.py': ['def helper():', ' return 1'],
});
expect(callees('go')).toEqual(['other/helpers.py:helper']);
});
});
7 changes: 6 additions & 1 deletion src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
isImportableKind,
CPP_DEFINE_SIGNATURE,
} 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 { cargoManifestFields, isPythonSelfCall, isSelfCallOnForeignName, 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 { isVisibleCppMacro, clearCppMacroVisibility } from './cpp-macro-visibility';
import { isCppConstructorRef, matchCppConstructor } from './cpp-constructor';
Expand Down Expand Up @@ -1633,6 +1633,11 @@ export class ReferenceResolver {
const module = this.nodeById(resolved.targetNodeId);
if (module && module.kind !== 'file' && module.kind !== 'module') return null;
}
// `self.x()` with no method `x` is an attribute holding a callable (see isSelfCallOnForeignName).
if (resolved && ref.language === 'python' && ref.referenceKind === 'calls' && resolved.resolvedBy !== 'import') {
const target = this.nodeById(resolved.targetNodeId);
if (target && isSelfCallOnForeignName(target, ref, this.context)) return null;
}
if (resolved && (resolved.byName || resolved.resolvedBy === 'exact-match' || resolved.resolvedBy === 'fuzzy') &&
isGuessedRecordAccessor(resolved, ref, this.context)) return null;
// A guess by name stops at a monorepo's own edge. (Asked of the winner: taking
Expand Down
70 changes: 66 additions & 4 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4468,12 +4468,74 @@ function isJsGlobalSelf(head: string, ref: UnresolvedRef, context: ResolutionCon
}

/**
* Whether a Python call recorded by its bare name was written on the instance,
* `self.get_ip(request)`. The extractor drops the `self.`, so a same-named name
* the file imports would otherwise claim the method call (#2074 follow-up).
* Whether a Python call recorded by its bare name was written on the instance
* or its class, `self.get_ip(request)` or `cls.build()`. The extractor drops the
* receiver, so a same-named name the file imports would otherwise claim the
* method call (#2074 follow-up).
*/
export function isPythonSelfCall(ref: UnresolvedRef, context: ResolutionContext): boolean {
return ref.language === 'python' && bareCallReceiver(ref, context)?.receiver === 'self';
if (ref.language !== 'python') return false;
const receiver = bareCallReceiver(ref, context)?.receiver;
return receiver === 'self' || (receiver !== undefined && /(?:^|[^\w.])cls$/.test(receiver));
}

/**
* Whether a Python `self.x()` or `cls.x()` landed on a module-level name it
* doesn't run. That call names a member, and with no method of the name it's an
* attribute holding a callable, so nothing says which: flask's `self.create_app()`
* is the callable `ScriptInfo` was handed, not an example app's `create_app`.
* A function of the caller's own file stays, since the file can put its
* functions on a class: attrs' `_cmp.py` builds `_is_comparable_to` into the
* classes it makes. So does a class, which an attribute usually holds under its
* own name: networkx's `self.Graph()` after `self.Graph = nx.Graph`. And so does
* a name the attribute is bound to (see pythonBindsAttributeTo).
*/
export function isSelfCallOnForeignName(target: Node, ref: UnresolvedRef, context: ResolutionContext): boolean {
if (target.kind === 'class' || target.qualifiedName.includes('::')) return false;
if (target.filePath === ref.filePath && target.kind === 'function') return false;
return isPythonSelfCall(ref, context) && !pythonBindsAttributeTo(target, ref, context);
}

/**
* Whether the attribute `self.x()` calls is bound to the module-level name
* `target`, under its own name: `x = staticmethod(x)` in a class body,
* `self.x = x` or `self.x = mod.x` in the caller's file, or `Cls.x = x` in the
* caller's file or `target`'s, with `Cls` a class around the caller. A bare `x`
* that is a parameter of the function it's in is that parameter, not `target`.
*/
function pythonBindsAttributeTo(target: Node, ref: UnresolvedRef, context: ResolutionContext): boolean {
const attr = escapeRegExp(ref.referenceName);
const caller = context.getNodeById?.(ref.fromNodeId);
const owners = (caller?.qualifiedName.split('::').slice(0, -1) ?? []).filter(s => /^\w+$/.test(s)).map(escapeRegExp);
const owner = ['self', 'cls', ...owners].join('|');
const value = `(?:(?:static|class)method\\(\\s*)?(?!(?:self|cls)\\.)((?:[A-Za-z_]\\w*\\.)*)${escapeRegExp(target.name)}\\s*\\)?\\s*$`;
const own = new RegExp(`^(\\s*)((?:${owner})\\.)?${attr}\\s*=\\s*${value}`);
const lines = pythonMemberLines(ref.filePath, context);
const bound = lines.some((line, i) => {
const m = own.exec(line);
if (!m) return false;
const fn = pythonFunctionAt(ref.filePath, i + 1, context);
// Without an owner it's a class attribute only in a class body, not a module's or a function's local.
if (!m[2]) return !!m[1] && !fn;
return m[3] !== '' || !fn || !isPythonParameterOf(target.name, fn, context);
});
if (bound || target.filePath === ref.filePath || !owners.length) return bound;
const outside = new RegExp(`^\\s*(?:[A-Za-z_]\\w*\\.)*(?:${owners.join('|')})\\.${attr}\\s*=\\s*${value}`);
return pythonMemberLines(target.filePath, context).some(line => outside.test(line));
}

/** The innermost Python function or method whose body has `line` of `filePath`. */
function pythonFunctionAt(filePath: string, line: number, context: ResolutionContext): Node | undefined {
return context.getNodesInFile(filePath)
.filter(n => (n.kind === 'function' || n.kind === 'method') && n.startLine < line && line <= n.endLine)
.sort((a, b) => b.startLine - a.startLine)[0];
}

/** Whether `name` is a parameter of the Python function `fn`. */
function isPythonParameterOf(name: string, fn: Node, context: ResolutionContext): boolean {
const head = pythonMemberLines(fn.filePath, context).slice(fn.startLine - 1, fn.startLine + 15).join('\n');
const params = /\bdef\s+\w+\s*(?:\[[^\]]*\])?\s*\(([^]*?)\)\s*(?:->[^:]*)?:/.exec(head)?.[1] ?? '';
return new RegExp(`(?:^|[(,*\\s])${escapeRegExp(name)}\\s*(?:[:=,)]|$)`).test(params);
}

/** Whether a call recorded by its bare name is written on something other than the caller's own object. */
Expand Down