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 @@ -19,6 +19,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- 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 Python, a call of a name the code around it binds itself, like a local `flat = lambda …`, a parameter, a loop or comprehension variable, a lambda's parameter, or a local or parameter of an enclosing function, no longer links to a module-level function or variable of that name, whether it is in the same file or in one the code never imports. Thanks @inth3shadows for the reports and @johnhldiver-beep. (#3037, #3230, #3231)
- In Python, a local built from a class through its module, like `client = httpx.AsyncClient()`, or bound by `with` or `async with … as client`, now has that class, so `client.get()` links to `AsyncClient.get` instead of the method of a class named like the variable, such as `Client.get`. A `with` whose class hands out something else from `__enter__`, and a class from a module outside your project, still give the local no type. Thanks @inth3shadows for the report and @nilotpal-n7. (#2957)
- 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
186 changes: 186 additions & 0 deletions __tests__/python-module-attribute-local.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/**
* A Python local built from a class through its module — `client =
* pkg.AsyncClient()` — or bound by `with … as client` / `async with … as
* client` holds an instance of that class (#2957). Its method calls link the
* class's methods, never those of a class named like the variable (`Client`).
* A module path picks the class it names among namesakes; an outside module's
* class, and a `with` whose `__enter__` hands out something else, type nothing.
*/
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-2957-'));
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 methods a function calls, as `Class::method@file`. */
function methodCallees(fn: string): string[] {
const from = cg!.getNodesByKind('function').find((n) => n.qualifiedName === fn);
expect(from, `${fn} should be indexed`).toBeDefined();
return cg!
.getOutgoingEdges(from!.id)
.filter((e) => e.kind === 'calls')
.map((e) => cg!.getNode(e.target))
.filter((n): n is NonNullable<typeof n> => !!n && n.kind === 'method')
.map((n) => `${n.qualifiedName}@${n.filePath}`)
.sort();
}

const CLIENT = [
'class Client:',
' def fetch(self, url):',
' return url',
'',
'',
'class AsyncClient:',
' async def fetch(self, url):',
' return url',
'',
].join('\n');

const ENTERING = [
'class Client:',
' def __enter__(self):',
' return self',
'',
' def __exit__(self, *a):',
' return None',
'',
' def fetch(self, url):',
' return url',
'',
'',
'class AsyncClient:',
' async def __aenter__(self):',
' return self',
'',
' async def __aexit__(self, *a):',
' return None',
'',
' async def fetch(self, url):',
' return url',
'',
].join('\n');

const USE = [
'import pkg',
'from pkg import AsyncClient',
'',
'',
'async def attr_named_client():',
' client = pkg.AsyncClient()',
' await client.fetch("u")',
'',
'',
'async def attr_named_c():',
' c = pkg.AsyncClient()',
' await c.fetch("u")',
'',
'',
'async def from_named_client():',
' client = AsyncClient()',
' await client.fetch("u")',
'',
'',
'async def with_named_client():',
' async with pkg.AsyncClient() as client:',
' await client.fetch("u")',
'',
'',
'async def with_direct_named_client():',
' async with AsyncClient() as client:',
' await client.fetch("u")',
'',
'',
'async def with_second_item():',
' async with pkg.AsyncClient() as first, pkg.AsyncClient() as client:',
' await client.fetch("u")',
'',
].join('\n');

const FNS = ['attr_named_client', 'attr_named_c', 'from_named_client', 'with_named_client', 'with_direct_named_client', 'with_second_item'];

describe('a Python local of a class built through its module or bound by with (#2957)', () => {
it("the issue's repro: every form reaches AsyncClient.fetch, none Client.fetch", async () => {
await index({ 'pkg/_client.py': CLIENT, 'pkg/__init__.py': 'from ._client import Client, AsyncClient\n', 'use.py': USE });
for (const fn of FNS) expect(methodCallees(fn), fn).toEqual(['AsyncClient::fetch@pkg/_client.py']);
});

it('and so with a class whose __aenter__ returns itself, as httpx writes it', async () => {
await index({ 'pkg/_client.py': ENTERING, 'pkg/__init__.py': 'from ._client import Client, AsyncClient\n', 'use.py': USE });
for (const fn of FNS) expect(methodCallees(fn), fn).toEqual(['AsyncClient::fetch@pkg/_client.py']);
});

it('reads that __aenter__ in a file with Windows line endings', async () => {
await index({
'pkg/_client.py': ENTERING.replace(/\n/g, '\r\n'),
'pkg/__init__.py': 'from ._client import Client, AsyncClient\r\n',
'use.py': USE.replace(/\n/g, '\r\n'),
});
for (const fn of FNS) expect(methodCallees(fn), fn).toEqual(['AsyncClient::fetch@pkg/_client.py']);
});

it('takes the class the module path names among namesakes', async () => {
await index({
'pkg/__init__.py': '',
'pkg/a.py': 'class Runner:\n def run(self):\n return 1\n',
'pkg/b.py': 'class Runner:\n def run(self):\n return 2\n',
'use.py': 'import pkg.b\n\n\ndef go():\n r = pkg.b.Runner()\n return r.run()\n',
});
expect(methodCallees('go')).toEqual(['Runner::run@pkg/b.py']);
});

it('does not type a with target by a class whose __enter__ hands out something else', async () => {
await index({
'db.py': [
'class Conn:',
' def execute(self):',
' return 1',
'',
'',
'class Pool:',
' def __enter__(self):',
' return Conn()',
'',
' def __exit__(self, *a):',
' return None',
'',
' def execute(self):',
' return 2',
'',
'',
'def use():',
' with Pool() as conn:',
' return conn.execute()',
'',
].join('\n'),
});
expect(methodCallees('use')).not.toContain('Pool::execute@db.py');
});

it("does not type a local by a project class sharing an outside module's class name", async () => {
await index({
'session.py': 'class Session:\n def get(self, url):\n return url\n',
'use.py': 'import requests\n\n\ndef go():\n s = requests.Session()\n return s.get("u")\n',
});
expect(methodCallees('go')).toEqual([]);
});
});
66 changes: 64 additions & 2 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,53 @@ function pythonRefClass(name: string, ref: UnresolvedRef, context: ResolutionCon
return classes.length === 1 ? classes[0]! : null;
}

/**
* Whether a Python local the receiver patterns typed holds an instance of the
* class they read (#2957). Built through its module, `client =
* pkg.AsyncClient()`, the path must name a project class: an outside module's
* class says nothing of a project class sharing its last name. Bound by `with
* … as client` (or `async with`), the local holds what the class's `__enter__`
* (`__aenter__`) returns: the instance, unless the project's own method, the
* class's or a base's, returns anything but `self` (`with Pool() as conn`
* hands out a connection). An outside class's `with` says nothing either.
*/
function pythonPatternTypeHolds(match: string, raw: string, ref: UnresolvedRef, context: ResolutionContext): boolean {
const withItem = /(?:^|[\s;:\0])(async\s+)?with\s[\s\S]*\sas\s+\w+$/.exec(match);
const throughModule = /^[a-z_]\w*\./.test(raw);
if (!withItem && !throughModule) return true;
const cls = pythonRefClass(raw, ref, context);
if (!cls) return false;
if (!withItem) return true;
const enter = pythonClassMethod(cls, withItem[1] ? '__aenter__' : '__enter__', ref, context);
return !enter || pythonReturnsOnlySelf(enter, context);
}

/** A Python class's own method of that name, or else the nearest project base's. */
function pythonClassMethod(cls: Node, name: string, ref: UnresolvedRef, context: ResolutionContext): Node | null {
const queue: Node[] = [cls];
const seen = new Set<string>();
while (queue.length > 0 && seen.size < 16) {
const c = queue.shift()!;
if (seen.has(c.id)) continue;
seen.add(c.id);
const own = context.getNodesByQualifiedName(`${c.qualifiedName}::${name}`).find(n => n.kind === 'method' && n.filePath === c.filePath);
if (own) return own;
queue.push(...pythonBases(c, ref, context));
}
return null;
}

/** Whether a Python method returns, and every `return` in it gives `self` (a body on the `def` line too). */
function pythonReturnsOnlySelf(method: Node, context: ResolutionContext): boolean {
const body = pythonMemberLines(method.filePath, context).slice(method.startLine - 1, method.endLine);
const values = body.flatMap(l => {
// `\s*$`, not `.*$`: a line of a CRLF file ends in `\r`, which `.` doesn't match.
const m = /(?:^|[:;])\s*return\b(.*?)\s*$/.exec(pythonBlankStrings(l));
return m ? [m[1]!.trim()] : [];
});
return values.length > 0 && values.every(v => v === 'self');
}

/**
* Whether every import binding a Python name in `filePath` is of a module
* Python's search doesn't find in the project: `class Color(Enum)` after `from
Expand Down Expand Up @@ -23965,8 +24012,14 @@ function buildLocalReceiverTypePatterns(language: Language, r: string): RegExp[]
// returns one instance of the model (not `filter`/`all`, a QuerySet).
new RegExp(`(?:^|;)\\s*${r}\\s*=(?!=)\\s*([A-Z]\\w*)\\.objects\\.(?:create|get|first|last|latest|earliest|get_by_natural_key)\\s*\\(`),
// lg = Logger(...) — a statement of its own: `prefix=IPNetwork(…),`
// inside a call's arguments is a keyword argument, not a binding.
new RegExp(`(?:^|;)\\s*${r}\\s*=(?!=)\\s*([A-Z][\\w.]*)\\s*\\((?![^\\n]*,\\s*$)`),
// inside a call's arguments is a keyword argument, not a binding. The
// class may be reached through its module (`lg = log.Logger(…)`), when
// that path names a project class (pythonPatternTypeHolds, #2957).
new RegExp(`(?:^|;)\\s*${r}\\s*=(?!=)\\s*((?:[a-z_]\\w*\\.)*[A-Z][\\w.]*)\\s*\\((?![^\\n]*,\\s*$)`),
// with Logger(…) as lg: / async with log.Logger(…) as lg: — one item of
// several too. The local holds what `__enter__` / `__aenter__` returns,
// the instance unless the project's own says otherwise (#2957).
new RegExp(`(?:^|;)\\s*(?:async\\s+)?with\\s+(?:[^#]*?,\\s*)?((?:[a-z_]\\w*\\.)*[A-Z]\\w*)\\s*\\((?:[^()]|\\([^()]*\\))*\\)\\s+as\\s+${r}\\b`),
// A quoted forward reference (`lg: "Logger"`, `lg: 'pkg.Logger'`) is the
// same annotation — and what every file under `from __future__ import
// annotations` or with a not-yet-defined class writes. The unquoted
Expand Down Expand Up @@ -24812,6 +24865,7 @@ export function inferLocalReceiverType(
for (const re of i >= ownFrom ? withListed : patterns) {
const m = re.exec(input);
if (m && m[2]) {
if (ref.language === 'python' && !pythonPatternTypeHolds(m[0], m[2], ref, context)) continue;
let type = ref.language === 'java' ? javaTypeName(m[2]) : normalizeInferredTypeName(m[2]);
// Delphi dereferences a pointer for a member (`P.Method` is
// `P^.Method`), and a class reference reaches its class's methods.
Expand Down Expand Up @@ -26989,6 +27043,14 @@ function matchMethodCallOn(
ref.language === 'cpp'
? inferCppReceiverType(objectOrClass!, ref, context, 0, cppDecl)
: inferLocalReceiverType(objectOrClass!, ref, context, decl));
// A Python local built through a module (`client = pkg.b.AsyncClient()`) is
// of the class that path names, which its last name alone doesn't pick: the
// project may have another `AsyncClient` in another module (#2957).
if (ref.language === 'python' && dotMatch && inferredType && decl.raw && /^[a-z_]\w*\./.test(decl.raw)) {
const cls = pythonRefClass(decl.raw, ref, context);
const method = cls ? pythonClassMethod(cls, methodName!, ref, context) : null;
if (method) return { original: ref, targetNodeId: method.id, confidence: 0.9, resolvedBy: 'instance-method' };
}
// Read on another line than the binding the call sees, it is another
// binding's type: the strategies below guess, unless no project type has
// that name — as before the binding was read.
Expand Down