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 @@ -21,6 +21,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- 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 Python, a `from x import name` written inside a function now applies to that function only, so calls of `name` in the rest of the file reach the file's own `def name` instead of the imported function, as a wrapper that imports the original it wraps expects. Thanks @inth3shadows for the report. (#3229)
- 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
123 changes: 123 additions & 0 deletions __tests__/python-function-local-from-import.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* A `from x import name` written inside a Python function binds `name` in that
* function only (#3229). Calls of `name` elsewhere in the file are not calls of
* the import: they run the file's own `def name`. The importing function's own
* call still reaches the import, and an import the module makes (at the top,
* under `try:`, or in a function that declares the name `global`) still binds
* every call in the file.
*/
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-3229-'));
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 the function with this qualified name in `file`, as `name@file`. */
function callees(file: string, qualified: string): string[] {
const from = cg!.getNodesByKind('function').find((n) => n.filePath === file && n.qualifiedName === qualified);
expect(from, `${qualified} should be indexed in ${file}`).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)
.map((n) => `${n.qualifiedName}@${n.filePath}`)
.sort();
}

const CORE = { 'pkg/__init__.py': '', 'pkg/core.py': 'def reverts(raw):\n return [raw]\n' };

describe('a from-import inside a Python function binds the name there only (#3229)', () => {
it("the issue's repro: the wrapper reaches the import, the file's other calls the wrapper", async () => {
await index({
...CORE,
't.py': [
'def reverts(raw):',
' from pkg.core import reverts # local to this function',
' return reverts(raw)',
'',
'def test_one():',
' return reverts(1) # t.py\'s own reverts',
'',
'def test_two():',
' return [reverts(x) for x in (1, 2)]',
'',
].join('\n'),
});
expect(callees('t.py', 'reverts')).toEqual(['reverts@pkg/core.py']);
expect(callees('t.py', 'test_one')).toEqual(['reverts@t.py']);
expect(callees('t.py', 'test_two')).toEqual(['reverts@t.py']);
});

it('keeps a module-level import binding every call in the file', async () => {
await index({
...CORE,
't.py': [
'from pkg.core import reverts',
'',
'',
'def helper():',
' from pkg.core import reverts',
' return reverts(0)',
'',
'',
'def test_one():',
' return reverts(1)',
'',
].join('\n'),
});
expect(callees('t.py', 'helper')).toEqual(['reverts@pkg/core.py']);
expect(callees('t.py', 'test_one')).toEqual(['reverts@pkg/core.py']);
});

it('keeps an import under a module-level try, and one a function makes global', async () => {
await index({
...CORE,
'a.py': [
'try:',
' from pkg.core import reverts',
'except ImportError:',
' reverts = None',
'',
'',
'def test_one():',
' return reverts(1)',
'',
].join('\n'),
'b.py': [
'reverts = None',
'',
'',
'def setup():',
' global reverts',
' from pkg.core import reverts',
'',
'',
'def test_one():',
' return reverts(1)',
'',
].join('\n'),
});
expect(callees('a.py', 'test_one')).toEqual(['reverts@pkg/core.py']);
expect(callees('b.py', 'test_one')).toEqual(['reverts@pkg/core.py']);
});
});
29 changes: 29 additions & 0 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
pythonFunctionModuleAlias,
pythonReceiverBinding,
pythonModuleImportKeys,
pythonFunctionImportKeys,
isPythonFromImportModule,
isPythonNameFromOutside,
tsGlobalScope,
Expand Down Expand Up @@ -3736,6 +3737,7 @@ export function reachesAmbientModule(ref: UnresolvedRef, specifier: string, decl
export function pythonImportsInScope(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext): ImportMapping[] {
if (ref.language !== 'python' || ref.referenceKind === 'imports') return imports;
const dot = ref.referenceName.indexOf('.');
if (dot < 0 && /^[A-Za-z_]\w*$/.test(ref.referenceName)) return pythonBareImportsInScope(ref, imports, context);
if (dot <= 0) return imports;
const receiver = ref.referenceName.slice(0, dot);
// `import pkg.mod` binds `pkg`, under a mapping named after `mod`.
Expand Down Expand Up @@ -3766,6 +3768,33 @@ export function pythonImportsInScope(ref: UnresolvedRef, imports: ImportMapping[
});
}

/**
* The file's import mappings as a bare Python name reads them (#3229). The
* mappings read from-imports at any depth, so `from pkg.core import reverts`
* written inside one function was the whole file's, and every other call of
* `reverts` linked the import, though the file's own `def reverts` is what
* those calls run. Such an import binds the name in its function only: a
* reference that no function around it binds the name for (nor a function
* declaring it `global`) drops the mappings only function-local imports
* make; one inside the importing function keeps that import's mapping. A
* binding other than an import, and the module's own imports, change nothing.
*/
function pythonBareImportsInScope(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext): ImportMapping[] {
const name = ref.referenceName;
const binds = (m: ImportMapping): boolean => m.localName === name;
if (!imports.some(binds)) return imports;
const local = pythonFunctionImportKeys(name, ref.filePath, context);
if (local.size === 0) return imports;
const keyOf = (m: ImportMapping): string => (m.isNamespace ? `${m.source}:*` : `${m.source}:${m.exportedName}`);
const binding = pythonReceiverBinding(name, ref, context);
if (binding === 'module') {
const moduleLevel = pythonModuleImportKeys(name, ref.filePath, context);
return imports.filter((m) => !binds(m) || moduleLevel.has(keyOf(m)) || !local.has(keyOf(m)));
}
if (binding === 'local' || 'module' in binding) return imports;
return imports.filter((m) => !binds(m) || (!m.isNamespace && m.source === binding.source && m.exportedName === binding.exportedName));
}

/**
* Resolve a Python qualified reference whose receiver is an imported MODULE:
* `certs.where()` after `from . import certs`, `mod.func()` after `import mod`
Expand Down
33 changes: 33 additions & 0 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,39 @@ export function pythonModuleImportKeys(name: string, filePath: string, context:
return new Set(pythonGlobalBindings(name, filePath, context).flatMap((b) => (b.kind === 'import' ? [b.key] : [])));
}

/**
* The imports binding `name` inside a function or method of `filePath`, keyed
* as pythonLineBindings keys them: `def reverts(raw): from pkg.core import
* reverts` → `pkg.core:reverts`. Such an import binds the name in that
* function only (#3229).
*/
export function pythonFunctionImportKeys(name: string, filePath: string, context: ResolutionContext): Set<string> {
return pythonNameScan(context, `fnimports\0${filePath}\0${name}`, () => {
const lines = pythonMemberLines(filePath, context);
const statements = pythonStatementStarts(filePath, context);
const keys = new Set<string>();
for (const i of pythonFunctionImportLines(filePath, context)) {
for (const b of pythonLineBindings(lines, i, statements, name)) if (b.kind === 'import') keys.add(b.key);
}
return keys;
});
}

/** The statement lines of a Python file that import something inside a function or method, read once per file. */
function pythonFunctionImportLines(filePath: string, context: ResolutionContext): number[] {
return pythonNameScan(context, `fnimportlines\0${filePath}`, () => {
const lines = pythonMemberLines(filePath, context);
const statements = pythonStatementStarts(filePath, context);
const inDef = new Uint8Array(lines.length + 1);
for (const def of context.getNodesInFile(filePath)) {
if (def.kind === 'function' || def.kind === 'method') inDef.fill(1, def.startLine, Math.min(def.endLine, lines.length));
}
const out: number[] = [];
for (let i = 0; i < lines.length; i++) if (inDef[i] && statements[i] && /\bimport\b/.test(lines[i]!)) out.push(i);
return out;
});
}

/** Distinct sources a file imports `name` from, at any scope (`from a import x` → `a:x`). */
function pythonImportKeys(name: string, filePath: string, context: ResolutionContext): Set<string> {
return pythonNameScan(context, `imports\0${filePath}\0${name}`, () => scanPythonImportKeys(name, filePath, context));
Expand Down