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 @@ -16,6 +16,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 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
239 changes: 239 additions & 0 deletions __tests__/python-self-attribute-call.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
/**
* A Python `self.x()` or `cls.x()` names a member of the instance or the
* class: a method the class has or inherits, or an attribute holding a
* callable (#2958). It never means a module-level function or variable of
* another file, and when the class binds the attribute itself it means what
* that binding holds: a parameter (`self.create_app = create_app`), an
* instance (`self.out = Layer()`), a tuple's element, not a same-named symbol
* somewhere else, another class's method included. What the binding names
* under its own name, the class's own and inherited methods, a mixin's call
* into the class it is mixed into, and a function of the caller's own file
* still link.
*/
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-2958-'));
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;
});

/** The `calls` edges out of a function or method named `caller`, as `name@file`. */
function callees(caller: string): string[] {
const from = [...cg!.getNodesByKind('function'), ...cg!.getNodesByKind('method')].filter((n) => n.name === caller);
expect(from.length, `${caller} should be indexed`).toBeGreaterThan(0);
return from
.flatMap((n) => cg!.getOutgoingEdges(n.id))
.filter((e) => e.kind === 'calls')
.map((e) => cg!.getNode(e.target))
.filter((n): n is NonNullable<typeof n> => !!n)
.map((n) => `${n.qualifiedName}@${n.filePath}`)
.sort();
}

describe('a Python call on self or cls (#2958)', () => {
it("the issue's repro: an attribute set from a parameter is not another file's function", async () => {
await index({
'pkg/cli.py': [
'class ScriptInfo:',
' def __init__(self, create_app=None):',
' self.create_app = create_app',
'',
' def load_app(self):',
' if self.create_app is not None:',
' return self.create_app()',
' return None',
'',
].join('\n'),
'examples/factory.py': 'def create_app():\n return object()\n',
});
expect(callees('load_app')).toEqual([]);
});

it('nor is an attribute holding an instance a function or a variable of that name elsewhere', async () => {
await index({
'other/features.py': 'def out(x):\n return x\n',
'scripts/export.py': 'games = []\nout = (games.copy())\n',
'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)',
'',
].join('\n'),
});
expect(callees('forward')).toEqual([]);
});

it('nor is an attribute a tuple binds', async () => {
await index({
'harness/runner.py': 'def run(*args):\n return args\n',
'tests/test_git.py': [
'import unittest',
'',
'',
'def _git_repo(path):',
' return path, print',
'',
'',
'class GitTest(unittest.TestCase):',
' def setUp(self):',
' self.repo, self.run = _git_repo("x")',
'',
' def test_add(self):',
' self.run("git", "add", "-A")',
'',
].join('\n'),
});
expect(callees('test_add')).toEqual([]);
});

it("nor another class's method of that name, when the class binds the attribute", async () => {
await index({
'a/handlers.py': 'class Other:\n def callback(self):\n pass\n',
'b/svc.py': [
'class Svc:',
' def __init__(self, callback):',
' self.callback = callback',
'',
' def fire(self):',
' self.callback()',
'',
].join('\n'),
});
expect(callees('fire')).toEqual([]);
});

it('nor, on cls, a class attribute', async () => {
await index({
'other/hooks.py': 'def factory():\n return 1\n',
'app.py': [
'class Builder:',
' factory = None',
'',
' @classmethod',
' def build(cls):',
' return cls.factory()',
'',
].join('\n'),
});
expect(callees('build')).toEqual([]);
});

it("keeps the class's own and inherited methods", async () => {
await index({
'base.py': 'class Base:\n def helper(self):\n return 1\n',
'child.py': [
'from base import Base',
'',
'',
'class Child(Base):',
' def save(self):',
' return 1',
'',
' def run(self):',
' self.save()',
' return self.helper()',
'',
].join('\n'),
'other.py': 'def helper():\n return 2\n\n\ndef save():\n return 3\n',
});
expect(callees('run')).toEqual(['Base::helper@base.py', 'Child::save@child.py']);
});

it("keeps a subclass's override even when the class binds a fallback for it", async () => {
await index({
'mixin.py': [
'class ListMixin:',
' def __init__(self):',
' if not hasattr(self, "_set_single"):',
' self._set_single = self._set_single_rebuild',
'',
' def _set_single_rebuild(self, i, v):',
' return None',
'',
' def __setitem__(self, i, v):',
' self._set_single(i, v)',
'',
].join('\n'),
'line.py': 'from mixin import ListMixin\n\n\nclass LineString(ListMixin):\n def _set_single(self, i, v):\n return None\n',
});
expect(callees('__setitem__')).toEqual(['LineString::_set_single@line.py']);
});

it("keeps a mixin's call into the class it is mixed into", async () => {
await index({
'views.py': 'class ListView:\n def get_queryset(self):\n return []\n',
'mixins.py': 'class FilterMixin:\n def filtered(self):\n return self.get_queryset()\n',
});
expect(callees('filtered')).toEqual(['ListView::get_queryset@views.py']);
});

it('keeps what a binding names under its own name', async () => {
await index({
'tools.py': 'def helper():\n return 1\n\n\ndef _cmp(a, b):\n return a == b\n',
'svc.py': [
'from tools import helper, _cmp',
'',
'',
'class Svc:',
' _cmp = staticmethod(_cmp)',
'',
' def __init__(self):',
' self.helper = helper',
'',
' def go(self):',
' self.helper()',
' return self._cmp(1, 2)',
'',
].join('\n'),
});
expect(callees('go')).toEqual(['_cmp@tools.py', 'helper@tools.py']);
});

it("keeps a function of the caller's own file, and a class an attribute holds", async () => {
await index({
'graphs.py': 'class Graph:\n pass\n',
'cmp.py': [
'import graphs',
'',
'',
'def _is_comparable_to(a, b):',
' return True',
'',
'',
'class Holder:',
' def __init__(self):',
' self.Graph = graphs.Graph',
'',
' def eq(self, other):',
' self.Graph()',
' return self._is_comparable_to(other)',
'',
].join('\n'),
});
expect(callees('eq')).toEqual(['_is_comparable_to@cmp.py']);
});
});
8 changes: 8 additions & 0 deletions src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { adoptProjectScans, readProjectScans, type ProjectScans } from './projec
import { clearCppIncluderMemos } from './cpp-includers';
import { clearCMacroRenames } from './c-macro-renames';
import { isObjcDeclaredTypeRef, matchByExactName } from './name-matcher';
import { pythonSelfCallReaches } from './name-matcher';
import { clearCFeatureVariantMemos } from './c-feature-variants';
import { clearAmbientModuleMemos, ambientModuleDeclarations } from './ambient-modules';
import { matchShopifyThemeFile } from './shopify-themes';
Expand Down Expand Up @@ -1668,6 +1669,13 @@ export class ReferenceResolver {
if (declaringFile !== undefined && declaringFile !== ref.filePath &&
!reachesAmbientModule(ref, specifier!, declaringFile, this.context)) return null;
}
// A Python `self.x()` / `cls.x()` names a member of the instance or the class:
// never a module-level function of another file, nor what a binding of the
// attribute doesn't name (#2958).
if (resolved && ref.language === 'python' && ref.referenceKind === 'calls' && resolved.resolvedBy !== 'framework') {
const target = this.nodeById(resolved.targetNodeId);
if (target && !pythonSelfCallReaches(target, ref, this.context)) return null;
}
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
108 changes: 108 additions & 0 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4541,6 +4541,114 @@ export function isJsThisCall(ref: UnresolvedRef, context: ResolutionContext): bo
return JS_FAMILY.has(ref.language) && bareCallReceiver(ref, context)?.receiver === 'self';
}

/**
* Whether a Python `self.x()` or `cls.x()` call, recorded by its bare name,
* can mean `target`, the answer a strategy gave by that name (#2958). The call
* names a member of the instance or the class: a method the class has or
* inherits, or an attribute holding a callable. So:
* - a method of the class, of a project base or of a subclass is the call;
* - when the class or a base binds `x` itself (`self.x = …`, `cls.x = …`, `x =
* …` in its body), the call is that value, and `target` only when the value
* names it under its own name: `self.x = x` with a module-level `x`, `x =
* staticmethod(x)`, `self.Graph = nx.Graph`. flask's `self.create_app = create_app`
* takes the parameter, and `self.out = Layer()` an instance: neither is a
* function named `create_app` or `out` elsewhere;
* - otherwise a module-level function or variable is out of reach, but for a
* function of the caller's own file, which the file can put on the class;
* - a class stays (an attribute holds one under its own name), and so does
* another class's method when nothing binds `x`: a mixin calls one of the
* class it is mixed into.
*/
export function pythonSelfCallReaches(target: Node, ref: UnresolvedRef, context: ResolutionContext): boolean {
if (ref.language !== 'python' || ref.referenceKind !== 'calls' || target.kind === 'class') return true;
if (!/^[A-Za-z_]\w*$/.test(ref.referenceName)) return true;
const receiver = bareCallReceiver(ref, context)?.receiver;
if (receiver !== 'self' && receiver !== 'cls') return true;
const owner = context.getNodesInFile(ref.filePath)
.filter((n) => n.kind === 'class' && n.startLine <= ref.line && n.endLine >= ref.line)
.sort((a, b) => b.startLine - a.startLine)[0];
if (!owner) return true;
if (target.kind === 'method') {
const cut = target.qualifiedName.lastIndexOf('::');
const holderName = cut > 0 ? target.qualifiedName.slice(0, cut) : '';
if (holderName && pythonClassLineage(owner, ref, context).has(`${target.filePath}\0${holderName}`)) return true;
// A subclass's override is what the call runs on its instances: django's
// ListMixin calls `self._set_single()`, which LineString defines.
const holder = holderName ? context.getNodesByQualifiedName(holderName).find((n) => n.kind === 'class' && n.filePath === target.filePath) : undefined;
if (holder && pythonDerivesFrom(holder, owner, ref, context)) return true;
}
const member = ref.referenceName;
const values = pythonNameScan(context, `attribute\0${owner.id}\0${member}`, () => pythonAttributeValues(owner, member, ref, context));
if (values.length > 0) return values.some((v) => pythonValueNames(v, target, ref, context));
if (target.qualifiedName.includes('::')) return true;
return target.kind === 'function' && target.filePath === ref.filePath;
}

/** `file\0qualifiedName` of a Python class and of each project class it derives from. */
function pythonClassLineage(cls: Node, ref: UnresolvedRef, context: ResolutionContext): Set<string> {
return pythonNameScan(context, `lineage\0${cls.id}`, () =>
new Set([cls, ...pythonClassLineageNodes(cls, ref, context)].map((c) => `${c.filePath}\0${c.qualifiedName}`)));
}

/**
* The values a Python class, or a project base of it, binds to its attribute
* `member`: `self.member = value` / `cls.member = value` in any method, or
* `member = value` in the class body. A tuple target (`self.repo, self.run =
* f()`) gives each name a value nothing can name: ''.
*/
function pythonAttributeValues(cls: Node, member: string, ref: UnresolvedRef, context: ResolutionContext): Array<{ value: string; filePath: string; line: number }> {
const out: Array<{ value: string; filePath: string; line: number }> = [];
const attr = new RegExp(`^\\(?\\s*(?:self|cls)\\s*\\.\\s*${escapeRegExp(member)}\\s*\\)?$`);
for (const c of [cls, ...pythonClassLineageNodes(cls, ref, context)]) {
const lines = pythonMemberLines(c.filePath, context);
const starts = pythonStatementStarts(c.filePath, context);
const own = new Set(pythonOwnLines(c, c.filePath, context));
for (let i = c.startLine; i < Math.min(c.endLine, lines.length); i++) {
if (!starts[i] || !lines[i]!.includes(member)) continue;
const assignment = pythonAssignment(pythonBlankStrings(lines[i]!));
if (!assignment || assignment.augmented) continue;
for (const target of assignment.targets) {
const t = target.split(':')[0]!.trim();
const parts = pythonTopLevelParts(t.replace(/^\((.*)\)$/, '$1')).map((p) => p.trim());
const binds = parts.some((p) => attr.test(p)) || (own.has(i) && parts.includes(member));
if (binds) out.push({ value: parts.length === 1 ? assignment.value.trim() : '', filePath: c.filePath, line: i + 1 });
}
}
}
return out;
}

/** The project classes a Python class derives from, nearest first, without the class itself. */
function pythonClassLineageNodes(cls: Node, ref: UnresolvedRef, context: ResolutionContext): Node[] {
return pythonNameScan(context, `bases\0${cls.id}`, () => {
const out: Node[] = [];
const queue = pythonBases(cls, ref, context);
const seen = new Set<string>([cls.id]);
while (queue.length > 0 && seen.size < 32) {
const c = queue.shift()!;
if (seen.has(c.id)) continue;
seen.add(c.id);
out.push(c);
queue.push(...pythonBases(c, ref, context));
}
return out;
});
}

/**
* Whether an attribute's value names `target` under the target's own name:
* `create_app`, `mod.create_app`, `staticmethod(create_app)`. A bare name the
* function around the binding binds itself (a parameter, a local) is that
* value, not the module-level one.
*/
function pythonValueNames(bound: { value: string; filePath: string; line: number }, target: Node, ref: UnresolvedRef, context: ResolutionContext): boolean {
const value = bound.value.replace(/^(?:static|class)method\s*\(\s*([\s\S]*?)\s*\)$/, '$1');
const m = /^((?:[A-Za-z_]\w*\s*\.\s*)*)([A-Za-z_]\w*)$/.exec(value);
if (!m || m[2] !== target.name) return false;
if (m[1]) return true;
return pythonReceiverBinding(target.name, { ...ref, filePath: bound.filePath, line: bound.line, column: 0 }, context) !== 'local';
}

/** Whether a call recorded by its bare name is written on something other than the caller's own object. */
function isCollapsedNonRecursion(ref: UnresolvedRef, context: ResolutionContext): boolean {
const written = bareCallReceiver(ref, context);
Expand Down