fix(python): bind a member call to the method it spells, not a folded twin
`run` and `_run` are two methods of one class (#3302 gave them separate
ids), but _resolve_python_member_calls indexed methods through _key,
which strips `_` and folds case. Both landed on one entry, the later
`method` edge won, and `Worker.run()`, `w.run()` on a typed receiver and
an inherited `self.run()` all drew a calls edge to `_run`. Keep every
method under the folded key and, when several share it, pick the one
named exactly as the call, as the module arm already does (#4577). A
call that matches none of them exactly is not guessed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 3c97842421)
This commit is contained in:
1 parent
91c8954345
commit
6e75b42147
2 files changed
+130
-7
No files matched your search
+23
-7
@@ -4790,7 +4790,7 @@ def _resolve_python_member_calls(
|
||||
# class label -> owning class node ids (len != 1 is the god-node guard), and
|
||||
# (class_node_id, method_key) -> method_node_id.
|
||||
class_def_nids: dict[str, list[str]] = {}
|
||||
method_index: dict[tuple[str, str], str] = {}
|
||||
method_index: dict[tuple[str, str], list[str]] = {}
|
||||
owner_of: dict[str, str] = {}
|
||||
for e in all_edges:
|
||||
if e.get("relation") != "method":
|
||||
@@ -4803,7 +4803,23 @@ def _resolve_python_member_calls(
|
||||
class_def_nids.setdefault(_key(cnode.get("label", "")), []).append(src)
|
||||
tnode = node_by_id.get(tgt)
|
||||
if tnode is not None:
|
||||
method_index[(src, _key(tnode.get("label", "")))] = tgt
|
||||
slot = method_index.setdefault((src, _key(tnode.get("label", ""))), [])
|
||||
if tgt not in slot:
|
||||
slot.append(tgt)
|
||||
|
||||
def _method_of(cls: str, callee: str) -> "str | None":
|
||||
# The key folds case and drops `_`, so `run()` and `_run()` of one class
|
||||
# share it; Python names are exact. Among several, the one named exactly
|
||||
# `callee` is the call's target, and none or two of them is no edge, as
|
||||
# in the module arm below (#4577).
|
||||
hits = method_index.get((cls, _key(callee)), [])
|
||||
if len(hits) > 1:
|
||||
hits = [
|
||||
m for m in hits
|
||||
if str(node_by_id.get(m, {}).get("label", "")).strip().lstrip(".").removesuffix("()") == callee
|
||||
]
|
||||
return hits[0] if len(hits) == 1 else None
|
||||
|
||||
# A class with N methods produced N entries; collapse to a unique set. (No
|
||||
# early return when there are no classes: the module arm below resolves
|
||||
# `module.func()` where the callable is a plain function, not a method.)
|
||||
@@ -4985,7 +5001,7 @@ def _resolve_python_member_calls(
|
||||
while cls and cls not in seen:
|
||||
seen.add(cls)
|
||||
if not skip_own:
|
||||
hit = method_index.get((cls, _key(callee)))
|
||||
hit = _method_of(cls, callee)
|
||||
if hit:
|
||||
return hit
|
||||
skip_own = False
|
||||
@@ -5029,7 +5045,7 @@ def _resolve_python_member_calls(
|
||||
if len(class_nids) == 1 and caller_file is not None and (
|
||||
file_of_node.get(class_nids[0]) == caller_file
|
||||
or class_nids[0] in imported_by_filenode.get(caller_file, ())):
|
||||
method_nid = method_index.get((class_nids[0], _key(callee)))
|
||||
method_nid = _method_of(class_nids[0], callee)
|
||||
_emit_call(caller, method_nid, rc, inferred=True)
|
||||
continue
|
||||
if not receiver or not callee or not caller:
|
||||
@@ -5063,7 +5079,7 @@ def _resolve_python_member_calls(
|
||||
imported = imported_by_filenode.get(fixture_file, set())
|
||||
cls_file = _file_node(cls)
|
||||
if cls_file == fixture_file or cls in imported or (cls_file is not None and cls_file in imported):
|
||||
_emit_call(caller, method_index.get((cls, _key(callee))), rc, inferred=True)
|
||||
_emit_call(caller, _method_of(cls, callee), rc, inferred=True)
|
||||
continue
|
||||
receiver_type = rc.get("receiver_type")
|
||||
if receiver_type and not receiver[:1].isupper():
|
||||
@@ -5082,7 +5098,7 @@ def _resolve_python_member_calls(
|
||||
imported = imported_by_filenode.get(caller_file, set())
|
||||
cls_file = _file_node(cls)
|
||||
if cls_file == caller_file or cls in imported or (cls_file is not None and cls_file in imported):
|
||||
_emit_call(caller, method_index.get((cls, _key(callee))), rc, inferred=True)
|
||||
_emit_call(caller, _method_of(cls, callee), rc, inferred=True)
|
||||
continue
|
||||
if receiver[:1].isupper():
|
||||
# Class arm (#1446): a capitalized receiver is a class reference; an
|
||||
@@ -5090,7 +5106,7 @@ def _resolve_python_member_calls(
|
||||
class_nids = class_def_nids.get(_key(receiver), [])
|
||||
if len(class_nids) != 1: # absent or ambiguous -> bail (god-node guard)
|
||||
continue
|
||||
_emit_call(caller, method_index.get((class_nids[0], _key(callee))), rc)
|
||||
_emit_call(caller, _method_of(class_nids[0], callee), rc)
|
||||
else:
|
||||
# Module arm (#1883): a lowercase receiver may be an imported module.
|
||||
# Resolve it against the modules imported into the caller's own file
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Python member calls must bind to the method the call spells.
|
||||
|
||||
`run` and `_run` are two methods of one class (#3302 gave them separate ids), but
|
||||
`_resolve_python_member_calls` keys its method index through `_key`, which strips
|
||||
`_` and folds case — so both methods landed on one entry and the later one won.
|
||||
The module arm already resolves by the exact name (#4577); the method arms must
|
||||
too, the same rule C# (#4415) and TypeScript (review on #4479) already apply.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
|
||||
|
||||
def _extract(tmp_path: Path, files: dict[str, str]) -> dict:
|
||||
for name, src in files.items():
|
||||
(tmp_path / name).write_text(src, encoding="utf-8")
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
return extract(
|
||||
[tmp_path / n for n in files],
|
||||
root=tmp_path,
|
||||
cache_root=tmp_path,
|
||||
parallel=False,
|
||||
)
|
||||
|
||||
|
||||
def _calls(r: dict) -> set[tuple[str, str]]:
|
||||
label = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
return {
|
||||
(label.get(e["source"]), label.get(e["target"]))
|
||||
for e in r["edges"]
|
||||
if e["relation"] == "calls"
|
||||
}
|
||||
|
||||
|
||||
_WORKER = (
|
||||
"class Worker:\n"
|
||||
" def run(self):\n"
|
||||
" return 1\n"
|
||||
"\n"
|
||||
" def _run(self):\n"
|
||||
" return 2\n"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("call,caller,target", [
|
||||
("Worker.run(None)", "viaclass()", ".run()"),
|
||||
("Worker._run(None)", "viaclass()", "._run()"),
|
||||
])
|
||||
def test_class_qualified_call_hits_the_spelled_method(tmp_path, call, caller, target):
|
||||
r = _extract(tmp_path, {
|
||||
"worker.py": _WORKER,
|
||||
"main.py": f"from worker import Worker\n\n\ndef viaclass():\n return {call}\n",
|
||||
})
|
||||
hits = {t for s, t in _calls(r) if s == caller and t and t.startswith(".")}
|
||||
assert hits == {target}, _calls(r)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("call,target", [("w.run()", ".run()"), ("w._run()", "._run()")])
|
||||
def test_typed_receiver_call_hits_the_spelled_method(tmp_path, call, target):
|
||||
r = _extract(tmp_path, {
|
||||
"worker.py": _WORKER,
|
||||
"main.py": (
|
||||
"from worker import Worker\n\n\n"
|
||||
f"def typed(w: Worker):\n return {call}\n"
|
||||
),
|
||||
})
|
||||
hits = {t for s, t in _calls(r) if s == "typed()" and t and t.startswith(".")}
|
||||
assert hits == {target}, _calls(r)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("call,target", [("self.run()", ".run()"), ("self._run()", "._run()")])
|
||||
def test_inherited_self_call_hits_the_spelled_method(tmp_path, call, target):
|
||||
r = _extract(tmp_path, {
|
||||
"base.py": _WORKER.replace("Worker", "Base"),
|
||||
"child.py": (
|
||||
"from base import Base\n\n\n"
|
||||
f"class Child(Base):\n def start(self):\n return {call}\n"
|
||||
),
|
||||
})
|
||||
hits = {t for s, t in _calls(r) if s == ".start()" and t and t.startswith(".")}
|
||||
assert hits == {target}, _calls(r)
|
||||
|
||||
|
||||
def test_call_matching_no_method_exactly_is_not_guessed(tmp_path):
|
||||
# `Run` is neither `run` nor `_run`, and the folded key fits both, so picking
|
||||
# one would be a guess (it was whichever `method` edge registered last).
|
||||
r = _extract(tmp_path, {
|
||||
"worker.py": _WORKER,
|
||||
"main.py": "from worker import Worker\n\n\ndef viaclass():\n return Worker.Run(None)\n",
|
||||
})
|
||||
assert not [t for s, t in _calls(r) if s == "viaclass()" and t and t.startswith(".")], _calls(r)
|
||||
|
||||
|
||||
def test_uncolliding_method_still_resolves(tmp_path):
|
||||
# Control: with no collision the loose key is the only lookup that can fire
|
||||
# for a class-qualified call, and it must keep firing.
|
||||
r = _extract(tmp_path, {
|
||||
"worker.py": "class Worker:\n def run(self):\n return 1\n",
|
||||
"main.py": "from worker import Worker\n\n\ndef viaclass():\n return Worker.run(None)\n",
|
||||
})
|
||||
assert ("viaclass()", ".run()") in _calls(r)
|
||||
Reference in new issue
Block a user