Repository navigation
fix(python): a call to an overloaded name reaches the def that runs #3216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
nilotpal-n7
wants to merge
6
commits into
colbymchenry:main
from
nilotpal-n7:fix/python-overload-implementation
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ec165c5
fix(python): a call to an overloaded name reaches the def that runs
nilotpal-n7 a6dfeba
fix(python): read overload under the name the file imported it as
nilotpal-n7 c634668
fix(python): read an overload decorator across a blank line
nilotpal-n7 cbc33a0
Merge remote-tracking branch 'origin/main' into fix/python-overload-i…
nilotpal-n7 600a5dd
fix(python): only typing's overload declares stubs, and sync moves th…
nilotpal-n7 ad4d257
Merge remote-tracking branch 'origin/main' into fix/python-overload-i…
nilotpal-n7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,307 @@ | ||
| /** | ||
| * A Python name declared with `typing.overload` runs one function: the `def` | ||
| * below its stubs. The stubs are indexed as separate nodes, and a call by name | ||
| * landed on the first of them, whose body is `...`. So the implementation had no | ||
| * callers, a call path broke at the stub, and click's `command`, called hundreds | ||
| * of times, looked unreferenced. | ||
| */ | ||
| 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'; | ||
|
|
||
| const DECO = [ | ||
| 'import typing as t', // 1 | ||
| 'from typing import overload', // 2 | ||
| '', // 3 | ||
| '@t.overload', // 4 | ||
| 'def command(name: t.Callable) -> int: ...', // 5 | ||
| '', // 6 | ||
| '@overload # a comment on the decorator', // 7 | ||
| '# and one between it and the def', // 8 | ||
| 'def command(name: str | None = None) -> str: ...', // 9 | ||
| '', // 10 | ||
| 'def command(name=None):', // 11 | ||
| ' return real_work(name)', // 12 | ||
| '', // 13 | ||
| 'def real_work(n):', // 14 | ||
| ' return n', // 15 | ||
| '', // 16 | ||
| 'class Prompt:', // 17 | ||
| ' @t.overload', // 18 | ||
| ' @classmethod', // 19 | ||
| ' def ask(cls, p: str) -> str: ...', // 20 | ||
| '', // 21 | ||
| ' @classmethod', // 22 | ||
| ' @t.overload', // 23 | ||
| ' def ask(cls, p: str, d: int) -> int: ...', // 24 | ||
| '', // 25 | ||
| ' @classmethod', // 26 | ||
| ' def ask(cls, p, d=None):', // 27 | ||
| ' return real_work(p)', // 28 | ||
| '', | ||
| ].join('\n'); | ||
|
|
||
| const USE = [ | ||
| 'import pkg', | ||
| 'from pkg import command, Prompt', | ||
| '', | ||
| 'def run():', | ||
| ' command("x")', | ||
| ' Prompt.ask("y")', | ||
| '', | ||
| 'def through_module():', | ||
| ' pkg.command("x")', | ||
| '', | ||
| ].join('\n'); | ||
|
|
||
| const PACKAGE = { 'pkg/deco.py': DECO, 'pkg/__init__.py': 'from .deco import command, Prompt\n', 'use.py': USE }; | ||
|
|
||
| describe('a call to a Python name declared with typing.overload', () => { | ||
| let root: string; | ||
| let cg: CodeGraph; | ||
|
|
||
| const index = async (files: Record<string, string>): Promise<void> => { | ||
| root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-overload-')); | ||
| for (const [file, source] of Object.entries(files)) { | ||
| fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); | ||
| fs.writeFileSync(path.join(root, file), source); | ||
| } | ||
| 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 fn = (name: string): Node => named(name)[0]!; | ||
| const calleeLines = (caller: string, name: string): number[] => cg.getCallees(fn(caller).id) | ||
| .filter((c) => c.node.name === name).map((c) => c.node.startLine).sort((a, b) => a - b); | ||
|
|
||
| it('links the implementation, not the first stub', async () => { | ||
| await index(PACKAGE); | ||
| expect(calleeLines('run', 'command')).toEqual([11]); | ||
| expect(calleeLines('through_module', 'command')).toEqual([11]); | ||
| }); | ||
|
|
||
| it('links the implementation of a classmethod, wherever overload stands among the decorators', async () => { | ||
| await index(PACKAGE); | ||
| expect(calleeLines('run', 'ask')).toEqual([27]); | ||
| }); | ||
|
|
||
| it('gives the implementation the callers, and leaves the stubs without any', async () => { | ||
| await index(PACKAGE); | ||
| const impl = named('command').find((n) => n.startLine === 11)!; | ||
| expect(cg.getCallers(impl.id).map((c) => c.node.name)).toEqual(expect.arrayContaining(['run', 'through_module'])); | ||
| for (const stub of named('command').filter((n) => n.startLine !== 11)) { | ||
| expect(cg.getCallers(stub.id)).toEqual([]); | ||
| } | ||
| }); | ||
|
|
||
| it('reads the decorator under the name the file imported it as', async () => { | ||
| await index({ | ||
| 'aliased.py': [ | ||
| 'from typing import overload as ov', | ||
| '', | ||
| '@ov', | ||
| 'def pick(a: int) -> int: ...', // 4 | ||
| '', | ||
| '@ov', | ||
| 'def pick(a: str) -> str: ...', // 7 | ||
| '', | ||
| 'def pick(a):', // 9 | ||
| ' return a', | ||
| '', | ||
| ].join('\n'), | ||
| 'use.py': [ | ||
| 'from aliased import pick', | ||
| '', | ||
| 'def caller():', | ||
| ' return pick(1)', | ||
| '', | ||
| ].join('\n'), | ||
| }); | ||
| expect(calleeLines('caller', 'pick')).toEqual([9]); | ||
| }); | ||
|
|
||
| it('reads a decorator with a blank line between it and the def', async () => { | ||
| await index({ | ||
| 'spaced.py': [ | ||
| 'from typing import overload', | ||
| '', | ||
| '@overload', | ||
| '', | ||
| 'def pick(a: int) -> int: ...', // 5 | ||
| '', | ||
| 'def pick(a):', // 7 | ||
| ' return a', | ||
| '', | ||
| ].join('\n'), | ||
| 'use.py': [ | ||
| 'from spaced import pick', | ||
| '', | ||
| 'def caller():', | ||
| ' return pick(1)', | ||
| '', | ||
| ].join('\n'), | ||
| }); | ||
| expect(calleeLines('caller', 'pick')).toEqual([7]); | ||
| }); | ||
|
|
||
| it('takes the implementation below the stub it reached, when a file has two sets', async () => { | ||
| await index({ | ||
| 'twice.py': [ | ||
| 'import sys', | ||
| 'from typing import overload', | ||
| '', | ||
| 'if sys.version_info >= (3, 11):', | ||
| ' @overload', | ||
| ' def pick(a: int) -> int: ...', // 6 | ||
| ' def pick(a):', // 7 | ||
| ' return a', | ||
| 'else:', | ||
| ' @overload', | ||
| ' def pick(a: str) -> str: ...', // 11 | ||
| ' def pick(a):', // 12 | ||
| ' return a', | ||
| '', | ||
| 'def caller():', | ||
| ' return pick(1)', | ||
| '', | ||
| ].join('\n'), | ||
| }); | ||
| const lines = calleeLines('caller', 'pick'); | ||
| expect(lines.length).toBe(1); | ||
| expect([7, 12]).toContain(lines[0]); | ||
| }); | ||
|
|
||
| it('keeps the stub when no implementation follows it', async () => { | ||
| await index({ | ||
| 'proto.py': [ | ||
| 'from typing import Protocol, overload', | ||
| '', | ||
| 'class Reader(Protocol):', | ||
| ' @overload', | ||
| ' def read(self, n: int) -> bytes: ...', // 5 | ||
| ' @overload', | ||
| ' def read(self) -> str: ...', // 7 | ||
| '', | ||
| 'def use(r: Reader):', | ||
| ' return r.read()', | ||
| '', | ||
| ].join('\n'), | ||
| }); | ||
| expect(calleeLines('use', 'read').length).toBe(1); | ||
| expect([5, 7]).toContain(calleeLines('use', 'read')[0]); | ||
| }); | ||
|
|
||
| it('leaves a same-named method of another class alone', async () => { | ||
| await index({ | ||
| 'two.py': [ | ||
| 'from typing import overload', | ||
| '', | ||
| 'class A:', | ||
| ' @overload', | ||
| ' def go(self, x: int) -> int: ...', // 5 | ||
| ' def go(self, x):', // 6 | ||
| ' return x', | ||
| '', | ||
| 'class B:', | ||
| ' def go(self, x):', // 10 | ||
| ' return x', | ||
| '', | ||
| 'def use():', | ||
| ' A().go(1)', | ||
| ' B().go(1)', | ||
| '', | ||
| ].join('\n'), | ||
| }); | ||
| expect(calleeLines('use', 'go')).toEqual([6, 10]); | ||
| }); | ||
| }); | ||
|
|
||
| describe('a Python overload a sync or another library changes', () => { | ||
| let root: string; | ||
| let cg: CodeGraph; | ||
|
|
||
| const write = (file: string, lines: string[]): void => { | ||
| fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); | ||
| fs.writeFileSync(path.join(root, file), lines.join('\n') + '\n'); | ||
| }; | ||
|
|
||
| afterEach(() => { | ||
| cg.destroy(); | ||
| fs.rmSync(root, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| const calleeLines = (caller: string, name: string): number[] => { | ||
| const from = cg.getNodesByKind('function').find((n) => n.name === caller)!; | ||
| return cg.getCallees(from.id).filter((c) => c.node.name === name).map((c) => c.node.startLine).sort((a, b) => a - b); | ||
| }; | ||
|
|
||
| const STUBS = [ | ||
| 'import typing as t', | ||
| '', | ||
| '', | ||
| '@t.overload', | ||
| 'def command(name: str) -> str: ...', // 5 | ||
| '', | ||
| '', | ||
| '@t.overload', | ||
| 'def command(name: int) -> int: ...', // 9 | ||
| ]; | ||
|
|
||
| it('moves the call to an implementation a sync adds below the stubs, and back when it goes', async () => { | ||
| root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-overload-sync-')); | ||
| write('pkg/deco.py', STUBS); | ||
| write('use.py', ['from pkg.deco import command', '', '', 'def go():', ' return command("x")']); | ||
| cg = await CodeGraph.init(root, { index: true }); | ||
| expect(calleeLines('go', 'command')).toEqual([5]); | ||
|
|
||
| write('pkg/deco.py', [...STUBS, '', '', 'def command(name=None):', ' return name']); | ||
| await cg.sync(); | ||
| expect(calleeLines('go', 'command')).toEqual([12]); | ||
|
|
||
| write('pkg/deco.py', STUBS); | ||
| await cg.sync(); | ||
| expect(calleeLines('go', 'command')).toEqual([5]); | ||
| }); | ||
|
|
||
| it("leaves another library's overload alone: its bodies run", async () => { | ||
| root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-py-overload-plum-')); | ||
| write('multi/g.py', [ | ||
| 'from plum import dispatch, overload', | ||
| '', | ||
| '@overload', | ||
| 'def g(x: int):', // 4 | ||
| ' return x + 1', | ||
| '', | ||
| '@overload', | ||
| 'def g(x: str):', // 8 | ||
| ' return x', | ||
| '', | ||
| '@dispatch', | ||
| 'def g(x):', // 12 | ||
| ' pass', | ||
| ]); | ||
| write('multi/h.py', [ | ||
| 'import plum', | ||
| '', | ||
| '@plum.overload', | ||
| 'def h(x: int):', // 4 | ||
| ' return x', | ||
| '', | ||
| 'def h(x):', // 7 | ||
| ' pass', | ||
| ]); | ||
| write('use.py', ['from multi.g import g', 'from multi.h import h', '', '', 'def go():', ' return g(1), h(1)']); | ||
| cg = await CodeGraph.init(root, { index: true }); | ||
| expect(calleeLines('go', 'g')).toEqual([4]); | ||
| expect(calleeLines('go', 'h')).toEqual([4]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an edit changes whether a same-name Python
defis a typing stub without changing the number offunction/methodnodes—for example, switching its overload import fromtypingto Plum—the function still produces the samefile\0name\0countkey.definitionDeltatherefore omits that function name, soresurrectStaleResolutionEdges()does not reopen callers in unchanged files and their persisted edges keep the old target; include overload binding or decorator state in the delta.AGENTS.md reference: AGENTS.md:L182-L182
Useful? React with 👍 / 👎.