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 @@ -20,6 +20,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- 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 Python, a method called on a local bound from a call, like `made = make(q)` or `s = store.stage()`, now goes by the type the called function or method declares it returns: a `Path`, a `str` or another class from outside your project links nothing, where any project method that happened to share the name could, and one of your own classes links its own method even when other classes have one of that name. Thanks @inth3shadows for the reports and @johnhldiver-beep. (#3038, #3240)
- 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
231 changes: 231 additions & 0 deletions __tests__/python-call-result-locals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
/**
* A Python local bound from a call has the type the callee's `-> T` declares,
* for any method called on it: a function's (`made = make(q)`, #3038) or a
* method's on another local of a known class (`s = store.stage()`, #3240). A
* builtin or a class from outside the project (`-> Path`, `-> str`) has no
* project method, so a project method sharing the name is never the call; a
* project class (`-> Stager`) gives its own method, even where another class
* has one of that name.
*/
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-3038-'));
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`. */
function methodCallees(fn: string): string[] {
const from = cg!.getNodesByKind('function').find((n) => n.name === 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)
.sort();
}

const ARM = [
'class Arm:',
' def stat(self, field: str) -> float:',
' return 1.0',
'',
' def casefold(self):',
' return ""',
'',
' def removeprefix(self, p):',
' return ""',
'',
].join('\n');

describe("a local bound from a function's call (#3038)", () => {
it("the issue's repro: a `-> Path` result calls no project `stat`", async () => {
await index({
'arm.py': ARM,
'use.py': [
'from pathlib import Path',
'',
'',
'def make(p: Path) -> Path:',
' return p',
'',
'',
'def size(p: Path) -> int:',
' return p.stat().st_size',
'',
'',
'def size_of_made(q: Path) -> int:',
' made = make(q)',
' return made.stat().st_size',
'',
].join('\n'),
});
expect(methodCallees('size')).toEqual([]);
expect(methodCallees('size_of_made')).toEqual([]);
});

it('nor does a `-> pathlib.Path` or a `-> str` result, or a parameter annotated `str`', async () => {
await index({
'arm.py': ARM,
'use.py': [
'import pathlib',
'',
'',
'def make2(p) -> pathlib.Path:',
' return p',
'',
'',
'def name_of(p) -> str:',
' return str(p)',
'',
'',
'def via_qualified(q):',
' made = make2(q)',
' return made.stat().st_size',
'',
'',
'def via_str(q):',
' s = name_of(q)',
' return s.casefold() + s.removeprefix("x")',
'',
'',
'def param_str(s: str):',
' return s.removeprefix("x")',
'',
].join('\n'),
});
for (const fn of ['via_qualified', 'via_str', 'param_str']) expect(methodCallees(fn), fn).toEqual([]);
});

it("a project class's annotation gives its own method, though another class has one of the name", async () => {
await index({
'm.py': [
'class Stager:',
' def push(self, rows):',
' return rows',
'',
'class Decoy:',
' def push(self, rows):',
' return rows',
'',
'def make() -> Stager:',
' return Stager()',
'',
'def via_function():',
' s = make()',
' s.push([1])',
'',
].join('\n'),
});
expect(methodCallees('via_function')).toEqual(['Stager::push']);
});

it('reads a value wrapped in parentheses as the expression inside, not a tuple', async () => {
await index({
't.py': [
'class Timeout:',
' def as_dict(self):',
' return {}',
'',
'',
'def go(t):',
' timeout = (',
' Timeout(t)',
' if t',
' else Timeout(1)',
' )',
' return timeout.as_dict()',
'',
].join('\n'),
});
expect(methodCallees('go')).toEqual(['Timeout::as_dict']);
});

it('leaves a local whose factory says nothing readable to the strategies that guessed before', async () => {
await index({
'w.py': [
'import lib',
'',
'',
'class Widget:',
' def render(self):',
' return 1',
'',
'',
'def build():',
' return lib.make()',
'',
'',
'def use():',
' widget = build()',
' return widget.render()',
'',
].join('\n'),
});
expect(methodCallees('use')).toEqual(['Widget::render']);
});
});

describe("a local bound from another local's method call (#3240)", () => {
const STORE = [
'class Stager:',
' def add(self, rows):',
' return rows',
'',
' def push(self, rows):',
' return rows',
'',
'class Decoy:',
' def push(self, rows):',
' return rows',
'',
'class Store:',
' def stage(self) -> Stager:',
' return Stager()',
'',
].join('\n');

it("the issue's repro: the method's return annotation types the local", async () => {
await index({
'm.py': [
STORE,
'def via_method():',
' store = Store()',
' s = store.stage()',
' s.add([2])',
'',
'def via_param_method(store: Store):',
' s = store.stage()',
' s.add([3])',
'',
'def pushes(store: Store):',
' s = store.stage()',
' s.push([4])',
'',
].join('\n'),
});
expect(methodCallees('via_method')).toEqual(['Stager::add', 'Store::stage']);
expect(methodCallees('via_param_method')).toEqual(['Stager::add', 'Store::stage']);
expect(methodCallees('pushes')).toEqual(['Stager::push', 'Store::stage']);
});
});
12 changes: 7 additions & 5 deletions __tests__/sync-removed-competitor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,20 @@ describe('sync re-resolves a call whose competing candidate went away', () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-competitor-py-'));
write('a.py', 'class A:\n def go(self):\n return 1\n');
write('b.py', 'class B:\n def go(self):\n return 2\n');
write('t.py', 'from a import A\n\ndef make():\n return A()\n\ndef use():\n x = make()\n x.go()\n');
// `x` is a parameter nothing annotates, so its type is unknown. (Bound
// by `x = make()` from a `make` that returns `A()`, it would be an A.)
write('t.py', 'def use(x):\n x.go()\n');
cg = CodeGraph.initSync(dir);
await cg.indexAll();
// Two candidates: the call stays unresolved.
expect(callTargets('use')).toEqual(['make']);
expect(callTargets('use')).toEqual([]);
});

it('after the file holding the other candidate is deleted', async () => {
fs.unlinkSync(path.join(dir, 'b.py'));
const result = await cg.sync();
expect(result.filesRemoved).toBe(1);
expect(callTargets('use')).toEqual(['A::go', 'make']);
expect(callTargets('use')).toEqual(['A::go']);
const synced = graphOf(cg);
cg = await reindexFromScratch(cg);
expect(synced).toEqual(graphOf(cg));
Expand All @@ -79,7 +81,7 @@ describe('sync re-resolves a call whose competing candidate went away', () => {
it('after an edit renames the other candidate away', async () => {
write('b.py', 'class B:\n def stop(self):\n return 2\n');
await cg.sync();
expect(callTargets('use')).toEqual(['A::go', 'make']);
expect(callTargets('use')).toEqual(['A::go']);
const synced = graphOf(cg);
cg = await reindexFromScratch(cg);
expect(synced).toEqual(graphOf(cg));
Expand All @@ -90,7 +92,7 @@ describe('sync re-resolves a call whose competing candidate went away', () => {
await cg.sync();
fs.unlinkSync(path.join(dir, 'b.py'));
await cg.sync();
expect(callTargets('use')).toEqual(['make']);
expect(callTargets('use')).toEqual([]);
const synced = graphOf(cg);
cg = await reindexFromScratch(cg);
expect(synced).toEqual(graphOf(cg));
Expand Down
Loading