fix(extract): resolve Python module instance method calls
Recognize direct constructor bindings at module scope while rejecting shadowed, rebound and uncertain receivers. Preserve inferred provenance and invalidate old AST cache entries.
Fixes #4970
Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 9ebe3d91fb)
This commit is contained in:
1 parent
874173c583
commit
dce3af740e
4 files changed
+177
-7
No files matched your search
@@ -167,6 +167,15 @@ ambiguous return references emit no inferred call. Resulting call edges remain
|
||||
as resolver context. Changes to a producer's return annotation require a full
|
||||
rebuild to recompute unchanged callers' inferred relationships.
|
||||
|
||||
Python direct module-level constructor assignments (`g = Service()`) retain the
|
||||
class for member-call resolution inside functions, including an imported alias
|
||||
or a lowercase class rebound to its instance. The constructor must be declared
|
||||
or imported before the assignment and resolve to a unique visible class by exact
|
||||
spelling. Local shadowing, other module bindings, conditional assignments and
|
||||
dynamic namespace mutation leave these calls unresolved. Qualified constructors
|
||||
and decorated classes are not inferred by this pass. Edges remain `INFERRED`;
|
||||
AST cache schema 37 retires Python entries without the instance marker.
|
||||
|
||||
C# partial types merge across files by their path inside the namespace,
|
||||
enclosing types first and each with its arity (`` Outer`1.Inner ``), within one
|
||||
assembly. Nested halves merge only under the same enclosing chain, and `Foo` and
|
||||
|
||||
+4
-1
@@ -5310,7 +5310,7 @@ def _resolve_python_member_calls(
|
||||
_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():
|
||||
if receiver_type and (not receiver[:1].isupper() or rc.get("_python_module_instance")):
|
||||
# Typed-receiver arm: `request.read()` where the extractor typed the
|
||||
# local or parameter `request` from an annotation (`request: Request`)
|
||||
# or a constructor binding (`client = Client(...)`, `with Client() as
|
||||
@@ -5320,6 +5320,9 @@ def _resolve_python_member_calls(
|
||||
# otherwise emit nothing. The method must be the class's own. A typed
|
||||
# local is never an imported module, so the module arm is skipped.
|
||||
class_nids = class_def_nids.get(_key(receiver_type), [])
|
||||
if rc.get("_python_module_instance"):
|
||||
class_nids = [nid for nid in class_nids
|
||||
if node_by_id[nid].get("label") == receiver_type]
|
||||
caller_file = _file_node(caller)
|
||||
if len(class_nids) == 1 and caller_file is not None:
|
||||
cls = class_nids[0]
|
||||
|
||||
@@ -16,6 +16,10 @@ from graphify.extractors.models import LanguageConfig
|
||||
from graphify.extractors.resolution import _resolve_js_import_target
|
||||
from graphify.security import sanitize_metadata
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from tree_sitter import Node
|
||||
|
||||
|
||||
def _csharp_namespace_id(dotted_name: str) -> str:
|
||||
@@ -2431,8 +2435,8 @@ def _python_module_bound_names(root, source: bytes) -> set[str]:
|
||||
return bound
|
||||
|
||||
|
||||
def _python_receiver_shadow_checker(root, source: bytes):
|
||||
"""Conservative lexical guard for a plain external module receiver.
|
||||
def _python_receiver_shadow_checker(root, source: bytes, *, module_bindings=None):
|
||||
"""Conservative lexical guard for a module or proved module-instance receiver.
|
||||
|
||||
A module-root plain import is the only eligible binding. Other bindings in
|
||||
any enclosing scope make the receiver unsafe, regardless of statement order.
|
||||
@@ -2500,6 +2504,14 @@ def _python_receiver_shadow_checker(root, source: bytes):
|
||||
if scope.type in {"function_definition", "lambda"}:
|
||||
bound.update(_python_param_names(scope.child_by_field_name("parameters"), source))
|
||||
|
||||
def bind_names(node, names) -> None:
|
||||
# A module-instance query supplies the exact declaration/assignment
|
||||
# nodes it has proved. Every other binding still shadows the name.
|
||||
bound.update(name for name in names if not (
|
||||
scope.type == "module" and module_bindings is not None
|
||||
and node.id in module_bindings.get(name, ())
|
||||
))
|
||||
|
||||
def walk(node) -> None:
|
||||
nonlocal unsafe
|
||||
for child in node.named_children:
|
||||
@@ -2509,7 +2521,7 @@ def _python_receiver_shadow_checker(root, source: bytes):
|
||||
if name is None:
|
||||
unsafe = True
|
||||
else:
|
||||
bound.add(_read_text(name, source))
|
||||
bind_names(child, [_read_text(name, source)])
|
||||
continue
|
||||
if kind == "lambda":
|
||||
continue
|
||||
@@ -2524,11 +2536,13 @@ def _python_receiver_shadow_checker(root, source: bytes):
|
||||
for name in names:
|
||||
plain_imports[name] = plain_imports.get(name, 0) + 1
|
||||
else:
|
||||
bound.update(names)
|
||||
bind_names(child, names)
|
||||
continue
|
||||
if kind in {"assignment", "augmented_assignment", "for_statement", "for_in_clause"}:
|
||||
if not target_names(child.child_by_field_name("left"), bound):
|
||||
assigned_names: set[str] = set()
|
||||
if not target_names(child.child_by_field_name("left"), assigned_names):
|
||||
unsafe = True
|
||||
bind_names(child, assigned_names)
|
||||
elif kind == "type_alias_statement":
|
||||
left = child.child_by_field_name("left")
|
||||
name = _read_text(left, source).split("[", 1)[0].strip() if left is not None else ""
|
||||
@@ -2573,13 +2587,64 @@ def _python_receiver_shadow_checker(root, source: bytes):
|
||||
return True
|
||||
if node.type == "module":
|
||||
found_module = True
|
||||
if plain_imports.get(receiver) != 1:
|
||||
if module_bindings is not None:
|
||||
if receiver not in module_bindings or plain_imports.get(receiver):
|
||||
return True
|
||||
elif plain_imports.get(receiver) != 1:
|
||||
return True
|
||||
node = node.parent
|
||||
return not found_module
|
||||
|
||||
return is_shadowed
|
||||
|
||||
|
||||
def _python_module_instance_types(root, source: bytes):
|
||||
"""Direct module constructor bindings, guarded by the existing lexical scan.
|
||||
|
||||
A constructor must be declared or imported once before the assignment. The
|
||||
corpus resolver still has to prove it names a unique visible class. Imports
|
||||
under aliases retain the original class name. Conditional bindings, dynamic
|
||||
namespace mutation and any other rebindings deliberately stay unresolved.
|
||||
"""
|
||||
declarations: dict[str, list[tuple[str, Node]]] = {}
|
||||
assignments = []
|
||||
for statement in root.named_children:
|
||||
if statement.type == "class_definition":
|
||||
name = _read_text(statement.child_by_field_name("name"), source)
|
||||
declarations.setdefault(name, []).append((name, statement))
|
||||
elif statement.type == "import_from_statement":
|
||||
for item in statement.children_by_field_name("name"):
|
||||
if item.type == "aliased_import":
|
||||
name = _read_text(item.child_by_field_name("name"), source)
|
||||
local = _read_text(item.child_by_field_name("alias"), source)
|
||||
else:
|
||||
name = local = _read_text(item, source)
|
||||
if name.isidentifier() and local.isidentifier():
|
||||
declarations.setdefault(local, []).append((name, statement))
|
||||
elif statement.type == "expression_statement":
|
||||
assignments.extend(c for c in statement.named_children if c.type == "assignment")
|
||||
|
||||
instances = {}
|
||||
for assignment in assignments:
|
||||
left = assignment.child_by_field_name("left")
|
||||
right = assignment.child_by_field_name("right")
|
||||
if left is None or left.type != "identifier" or right is None or right.type != "call":
|
||||
continue
|
||||
function = right.child_by_field_name("function")
|
||||
if function is None or function.type != "identifier":
|
||||
continue
|
||||
receiver, constructor = _read_text(left, source), _read_text(function, source)
|
||||
origins = declarations.get(constructor, [])
|
||||
if len(origins) != 1 or origins[0][1].start_byte >= assignment.start_byte:
|
||||
continue
|
||||
class_name, declaration = origins[0]
|
||||
allowed = {constructor: {declaration.id}}
|
||||
allowed.setdefault(receiver, set()).add(assignment.id)
|
||||
shadowed = _python_receiver_shadow_checker(root, source, module_bindings=allowed)
|
||||
if not shadowed(assignment, constructor) and not shadowed(assignment, receiver):
|
||||
instances[receiver] = (class_name, shadowed)
|
||||
return instances
|
||||
|
||||
_PYTHON_PROPERTY_DECORATORS = frozenset({"property", "cached_property", "functools.cached_property"})
|
||||
|
||||
|
||||
@@ -6385,6 +6450,10 @@ def _extract_generic(
|
||||
_python_receiver_shadow_checker(root, source)
|
||||
if config.ts_module == "tree_sitter_python" else None
|
||||
)
|
||||
python_module_instances = (
|
||||
_python_module_instance_types(root, source)
|
||||
if config.ts_module == "tree_sitter_python" else {}
|
||||
)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
@@ -10387,6 +10456,11 @@ def _extract_generic(
|
||||
# A fixture parameter: typed by the resolver from the
|
||||
# fixture pytest would pick for it.
|
||||
rc_entry["_python_fixture_param"] = True
|
||||
elif member_receiver in python_module_instances:
|
||||
class_name, shadowed = python_module_instances[member_receiver]
|
||||
if not shadowed(node, member_receiver):
|
||||
rc_entry["receiver_type"] = class_name
|
||||
rc_entry["_python_module_instance"] = True
|
||||
if config.ts_module == "tree_sitter_python":
|
||||
rc_entry["_python_call_site"] = [node.start_byte, node.end_byte]
|
||||
# `super(Cls, obj).m()` starts the MRO after Cls, not after the
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Module singletons must resolve without inventing edges for shadowed names."""
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
|
||||
|
||||
def _extract(tmp_path, source, service="Svc"):
|
||||
package = tmp_path / "pkg"
|
||||
package.mkdir(exist_ok=True)
|
||||
(package / "__init__.py").write_text("", encoding="utf-8")
|
||||
(package / "service.py").write_text(
|
||||
f"class {service}:\n def create(self): return 1\n", encoding="utf-8"
|
||||
)
|
||||
(package / "caller.py").write_text(source, encoding="utf-8")
|
||||
result = extract(sorted(package.glob("*.py")), root=tmp_path,
|
||||
cache_root=tmp_path / "graphify-out", parallel=False)
|
||||
nodes = {node["id"]: node for node in result["nodes"]}
|
||||
return [edge for edge in result["edges"]
|
||||
if edge["relation"] == "calls"
|
||||
and nodes[edge["source"]]["label"] == "run()"
|
||||
and nodes[edge["target"]]["label"] == ".create()"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("service,instance", [("Svc", "g"), ("lower_svc", "lower_svc"),
|
||||
("Svc", "GLOBAL")])
|
||||
def test_module_constructor_instance(tmp_path, service, instance):
|
||||
source = (f"from .service import {service}\n{instance} = {service}()\n"
|
||||
f"def run(): return {instance}.create()\n")
|
||||
cold = _extract(tmp_path, source, service)
|
||||
warm = _extract(tmp_path, source, service)
|
||||
assert len(cold) == 1
|
||||
assert cold[0]["confidence"] == "INFERRED"
|
||||
assert warm == cold
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [
|
||||
"def run(g): return g.create()\n",
|
||||
"def run():\n g = other()\n return g.create()\n",
|
||||
"def outer(g):\n def run(): return g.create()\n",
|
||||
"def run():\n for g in []: g.create()\n",
|
||||
"def run():\n del g\n return g.create()\n",
|
||||
])
|
||||
def test_local_binding_shadows_module_instance(tmp_path, body):
|
||||
assert not _extract(tmp_path, "from .service import Svc\ng = Svc()\n" + body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra", [
|
||||
"g = other()\n", "del g\n", "for g in []: pass\n",
|
||||
"def g(): pass\n", "import g\n",
|
||||
"def replace():\n global g\n g = other()\n",
|
||||
])
|
||||
def test_rebound_module_instance_is_unresolved(tmp_path, extra):
|
||||
assert not _extract(tmp_path, "from .service import Svc\ng = Svc()\n" + extra
|
||||
+ "def run(): return g.create()\n")
|
||||
|
||||
|
||||
def test_rebound_constructor_is_unresolved(tmp_path):
|
||||
assert not _extract(tmp_path, "from .service import Svc\nSvc = other\ng = Svc()\n"
|
||||
"def run(): return g.create()\n")
|
||||
|
||||
|
||||
def test_imported_class_alias(tmp_path):
|
||||
assert len(_extract(tmp_path, "from .service import Svc as Alias\ng = Alias()\n"
|
||||
"def run(): return g.create()\n")) == 1
|
||||
|
||||
|
||||
def test_same_file_lowercase_class(tmp_path):
|
||||
assert len(_extract(tmp_path, "class local_svc:\n def create(self): return 2\n"
|
||||
"local_svc = local_svc()\ndef run(): return local_svc.create()\n")) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", [
|
||||
"from .service import Svc\nif flag: g = Svc()\ndef run(): return g.create()\n",
|
||||
"from .service import Svc\ng = Svc()\nglobals()['g'] = other\n"
|
||||
"def run(): return g.create()\n",
|
||||
"from .service import Svc\ng = Svc()\nfrom .other import *\n"
|
||||
"def run(): return g.create()\n",
|
||||
"from .service import Svc\ng = Svc()\nwith other() as g: pass\n"
|
||||
"def run(): return g.create()\n",
|
||||
"from .service import Svc\ng = Svc()\n"
|
||||
"def run():\n try: pass\n except Exception as g: g.create()\n",
|
||||
])
|
||||
def test_uncertain_module_bindings_are_unresolved(tmp_path, source):
|
||||
assert not _extract(tmp_path, source)
|
||||
Reference in new issue
Block a user