fix(engine): resolve fields declared on a superclass for receivers in a subclass (#3151)
A method call through a field whose type is declared on an ancestor class, used from a subclass, did not resolve (the field-type table only held the class's own fields). Walk the inheritance chain (per-file for Java/C#, cross-file for Java/ObjC) to type the receiver, BFS with a seen-set so an inheritance cycle terminates. Target selection is unchanged (the single-definition guards stand), so this only widens receiver typing and never fabricates an edge; this.-only, and the binder refuses to guess on ambiguity.
This commit is contained in:
1 parent
208d0c1dcc
commit
b5162dc2e5
4 files changed
+367
-6
No files matched your search
+103
-2
@@ -3566,6 +3566,57 @@ def _resolve_csharp_member_calls(
|
||||
})
|
||||
|
||||
|
||||
def _bind_member_field_tables(
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
*,
|
||||
lang: str,
|
||||
) -> dict[str, dict[str, str]]:
|
||||
"""Bind the exported per-file field tables (#3151) to class node ids.
|
||||
|
||||
Entries are keyed by class label + source_file so they survive every id
|
||||
remap; here they are matched back to the one class node carrying that
|
||||
label (disambiguated by source_file basename when several share it).
|
||||
An entry that stays ambiguous binds nothing - guessing would attach a
|
||||
field table to the wrong class.
|
||||
"""
|
||||
by_label: dict[str, list[dict]] = {}
|
||||
for n in all_nodes:
|
||||
if n.get("label") and n.get("source_file"):
|
||||
by_label.setdefault(str(n["label"]), []).append(n)
|
||||
bound: dict[str, dict[str, str]] = {}
|
||||
for result in per_file:
|
||||
for entry in (result.get("member_field_tables") or []):
|
||||
if not isinstance(entry, dict) or entry.get("lang") != lang:
|
||||
continue
|
||||
label, fields = entry.get("class_label"), entry.get("fields")
|
||||
if not label or not isinstance(fields, dict):
|
||||
continue
|
||||
candidates = by_label.get(str(label), [])
|
||||
if len(candidates) > 1:
|
||||
sf = str(entry.get("source_file") or "")
|
||||
exact = [n for n in candidates if str(n.get("source_file")) == sf]
|
||||
if len(exact) == 1:
|
||||
candidates = exact
|
||||
else:
|
||||
# the node's source_file may have been relativized since
|
||||
# the entry was written; the basename still identifies it
|
||||
base = os.path.basename(sf)
|
||||
candidates = [
|
||||
n for n in candidates
|
||||
if os.path.basename(str(n.get("source_file"))) == base
|
||||
]
|
||||
if len(candidates) != 1:
|
||||
continue
|
||||
merged = bound.setdefault(candidates[0]["id"], {})
|
||||
for fname, tname in fields.items():
|
||||
if merged.get(fname) not in (None, tname):
|
||||
merged.pop(fname, None) # cross-shard conflict: no guess
|
||||
else:
|
||||
merged[fname] = tname
|
||||
return bound
|
||||
|
||||
|
||||
def _resolve_java_member_calls(
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
@@ -3607,6 +3658,31 @@ def _resolve_java_member_calls(
|
||||
method_index.setdefault((owner, key(method_node.get("label", ""))), set()).add(method)
|
||||
|
||||
existing_pairs = {(edge.get("source"), edge.get("target")) for edge in all_edges}
|
||||
# Inherited fields (#3151): a field declared on a superclass - possibly in
|
||||
# another file - types a `this.<field>` receiver in the subclass. Safe
|
||||
# because `this.` names a field by construction; no local can shadow it.
|
||||
# The per-file tables ride the results keyed by class label + source_file
|
||||
# (never node id, see #3150); bind each to its class node, ambiguity skips.
|
||||
inherits_bases: dict[str, list[str]] = {}
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") == "inherits":
|
||||
inherits_bases.setdefault(edge["source"], []).append(edge["target"])
|
||||
class_fields = _bind_member_field_tables(per_file, all_nodes, lang="java")
|
||||
|
||||
def _inherited_field_type(class_nid, field: str):
|
||||
seen: set = set()
|
||||
queue = [class_nid]
|
||||
while queue:
|
||||
cls = queue.pop(0)
|
||||
if not cls or cls in seen:
|
||||
continue
|
||||
seen.add(cls)
|
||||
hit = class_fields.get(cls, {}).get(field)
|
||||
if hit:
|
||||
return hit
|
||||
queue.extend(inherits_bases.get(cls, []))
|
||||
return None
|
||||
|
||||
for result in per_file:
|
||||
for raw_call in result.get("raw_calls", []):
|
||||
if raw_call.get("lang") != "java" or not raw_call.get("is_member_call"):
|
||||
@@ -3628,6 +3704,10 @@ def _resolve_java_member_calls(
|
||||
if not type_name and receiver[:1].isupper():
|
||||
type_name = receiver
|
||||
exact = True
|
||||
if not type_name and receiver.startswith("this."):
|
||||
type_name = _inherited_field_type(
|
||||
enclosing_type.get(caller), receiver[len("this."):]
|
||||
)
|
||||
if not type_name:
|
||||
continue
|
||||
type_defs = type_def_nids.get(key(type_name), [])
|
||||
@@ -3757,6 +3837,27 @@ def _resolve_objc_member_calls(
|
||||
all_raw_calls.extend(result.get("raw_calls", []))
|
||||
|
||||
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
|
||||
# A @property declared on a superclass types [self.<field> ...] in the
|
||||
# subclass too (#3151): walk the inherits chain, nearest table first.
|
||||
_objc_bases: dict[str, list[str]] = {}
|
||||
for e in all_edges:
|
||||
if e.get("relation") == "inherits":
|
||||
_objc_bases.setdefault(e["source"], []).append(e["target"])
|
||||
|
||||
def _field_type_up_chain(cls, receiver):
|
||||
seen: set = set()
|
||||
queue = [cls]
|
||||
while queue:
|
||||
c = queue.pop(0)
|
||||
if not c or c in seen:
|
||||
continue
|
||||
seen.add(c)
|
||||
hit = field_types_by_class.get(c, {}).get(receiver)
|
||||
if hit:
|
||||
return hit
|
||||
queue.extend(_objc_bases.get(c, []))
|
||||
return None
|
||||
|
||||
for rc in all_raw_calls:
|
||||
if not rc.get("is_member_call"):
|
||||
continue
|
||||
@@ -3773,7 +3874,7 @@ def _resolve_objc_member_calls(
|
||||
# via the caller's own class's @property/ivar table. Checked before the
|
||||
# capitalized arm so a capitalized field never reads as a class name.
|
||||
cls = enclosing_type.get(caller)
|
||||
type_name = field_types_by_class.get(cls, {}).get(receiver) if cls else None
|
||||
type_name = _field_type_up_chain(cls, receiver) if cls else None
|
||||
if not type_name:
|
||||
continue
|
||||
type_defs = type_def_nids.get(_key(type_name), [])
|
||||
@@ -3798,7 +3899,7 @@ def _resolve_objc_member_calls(
|
||||
type_name = type_table_by_file.get(src_file, {}).get(receiver)
|
||||
if not type_name:
|
||||
cls = enclosing_type.get(caller)
|
||||
type_name = field_types_by_class.get(cls, {}).get(receiver) if cls else None
|
||||
type_name = _field_type_up_chain(cls, receiver) if cls else None
|
||||
if not type_name:
|
||||
continue
|
||||
type_defs = type_def_nids.get(_key(type_name), [])
|
||||
|
||||
@@ -4853,11 +4853,36 @@ def _extract_generic(
|
||||
# populated before walk_calls runs. Lets member-call raw_calls carry a
|
||||
# receiver_type so the cross-file pass resolves `var.method` by type (#ruby).
|
||||
ruby_var_types: dict[str, dict[str, str | None]] = {}
|
||||
# Fields declared on a SUPERCLASS type receivers in a subclass too (#3151):
|
||||
# fold each class's table with its ancestors', nearest declaration winning.
|
||||
# Local `inherits` edges only - the cross-file half lives in the corpus
|
||||
# member-call resolvers, which see the whole graph.
|
||||
_local_bases: dict[str, list[str]] = {}
|
||||
for _e in edges:
|
||||
if _e.get("relation") == "inherits":
|
||||
_local_bases.setdefault(_e["source"], []).append(_e["target"])
|
||||
|
||||
def _fields_up_chain(tables: dict, class_nid) -> dict:
|
||||
if not class_nid:
|
||||
return {}
|
||||
merged: dict = {}
|
||||
seen: set = set()
|
||||
queue = [class_nid]
|
||||
while queue:
|
||||
cls = queue.pop(0)
|
||||
if cls in seen:
|
||||
continue
|
||||
seen.add(cls)
|
||||
for _name, _tname in tables.get(cls, {}).items():
|
||||
merged.setdefault(_name, _tname)
|
||||
queue.extend(_local_bases.get(cls, []))
|
||||
return merged
|
||||
|
||||
java_receiver_types = {
|
||||
body_id: _java_method_receiver_types(
|
||||
method_node,
|
||||
source,
|
||||
java_field_types.get(class_nid, {}),
|
||||
_fields_up_chain(java_field_types, class_nid),
|
||||
)
|
||||
for body_id, (method_node, class_nid) in java_method_scopes.items()
|
||||
}
|
||||
@@ -4865,7 +4890,7 @@ def _extract_generic(
|
||||
body_id: _csharp_method_receiver_types(
|
||||
method_node,
|
||||
source,
|
||||
csharp_field_types.get(class_nid, {}),
|
||||
_fields_up_chain(csharp_field_types, class_nid),
|
||||
)
|
||||
for body_id, (method_node, class_nid) in csharp_method_scopes.items()
|
||||
}
|
||||
@@ -5911,6 +5936,23 @@ def _extract_generic(
|
||||
if _ruby_mixin_calls:
|
||||
raw_calls.extend(_ruby_mixin_calls)
|
||||
result = {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
|
||||
# Export the per-file field->type tables for the corpus member-call
|
||||
# resolvers (#3151): a field declared on a superclass in ANOTHER file can
|
||||
# only be typed once the whole graph is visible. Keyed by class label +
|
||||
# source_file, never by node id - ids are rewritten by the #1529 remap
|
||||
# passes and the cache portability rewrite, which is exactly how the
|
||||
# id-keyed ObjC table went stale (#3150).
|
||||
_field_table_export = [
|
||||
{"lang": _lang, "class_label": _n.get("label"),
|
||||
"source_file": _n.get("source_file"), "fields": dict(_tbl)}
|
||||
for _lang, _tables in (("java", java_field_types), ("csharp", csharp_field_types))
|
||||
for _cls, _tbl in _tables.items()
|
||||
if _tbl
|
||||
for _n in (next((x for x in nodes if x["id"] == _cls), None),)
|
||||
if _n is not None and _n.get("label")
|
||||
]
|
||||
if _field_table_export:
|
||||
result["member_field_tables"] = _field_table_export
|
||||
# #2551: the parser recovered from syntax errors, so extraction may be
|
||||
# partial (in the worst case, nothing but the file node). Record the first
|
||||
# error's line so extract() can warn instead of reporting silent success.
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Fields declared on a superclass type receivers in a subclass (#3151).
|
||||
|
||||
The `field -> TypeName` tables that type a `this.<field>` / `[self.<field> …]`
|
||||
receiver were looked up by the declaring class only, with no walk up the
|
||||
`inherits` chain — so a field declared on a superclass typed nothing in a
|
||||
subclass and every member call through it was dropped, even though the
|
||||
`inherits` edge sat in the same graph. Java failed even with parent and child
|
||||
in one file; cross-file needed the tables at corpus level, which is why they
|
||||
now ride the per-file results keyed by class label + source_file (never node
|
||||
id — the id-keyed ObjC table is how #3150 happened).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import tempfile
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
|
||||
try:
|
||||
from graphify.extract import _bind_member_field_tables
|
||||
except ImportError: # pre-fix tree
|
||||
_bind_member_field_tables = None
|
||||
|
||||
GREETER = ("package lib;\n"
|
||||
"public class Greeter {\n"
|
||||
" public String greet(String who) { return \"hi \" + who; }\n"
|
||||
"}\n")
|
||||
|
||||
|
||||
def _graph(tmp_path, files: dict[str, str]):
|
||||
for name, body in files.items():
|
||||
p = tmp_path / name
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(body, encoding="utf-8")
|
||||
with redirect_stdout(io.StringIO()):
|
||||
r = extract([tmp_path / n for n in files], cache_root=Path(tempfile.mkdtemp()),
|
||||
root=tmp_path, parallel=False)
|
||||
labels = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
calls = {(labels.get(e["source"]), labels.get(e["target"])): e
|
||||
for e in r["edges"] if e.get("relation") == "calls"}
|
||||
return calls, r
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Java
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_java_same_file_inherited_field_types_the_receiver(tmp_path):
|
||||
"""The issue's first repro: PBase declares the field, Pair extends it in
|
||||
the same file — and the call was still dropped."""
|
||||
calls, _ = _graph(tmp_path, {
|
||||
"src/lib/Greeter.java": GREETER,
|
||||
"src/lib/Pair.java": (
|
||||
"package lib;\n"
|
||||
"class PBase { protected Greeter greeter = new Greeter(); }\n"
|
||||
"public class Pair extends PBase {\n"
|
||||
" void run() { this.greeter.greet(\"same-file-inherited\"); }\n"
|
||||
"}\n"),
|
||||
})
|
||||
assert (".run()", ".greet()") in calls
|
||||
|
||||
|
||||
def test_java_cross_file_inherited_field_types_the_receiver(tmp_path):
|
||||
"""The issue's second repro: `Direct.run` resolved, `Sub.run` did not —
|
||||
one call site out of two, differing only in where the field was declared."""
|
||||
calls, _ = _graph(tmp_path, {
|
||||
"src/lib/Greeter.java": GREETER,
|
||||
"src/lib/Base.java": "package lib;\npublic class Base { protected Greeter greeter = new Greeter(); }\n",
|
||||
"src/lib/Sub.java": (
|
||||
"package lib;\npublic class Sub extends Base {\n"
|
||||
" void run() { this.greeter.greet(\"inherited-field\"); }\n}\n"),
|
||||
"src/lib/Direct.java": (
|
||||
"package lib;\npublic class Direct { private Greeter greeter = new Greeter();\n"
|
||||
" void go() { this.greeter.greet(\"own-field\"); }\n}\n"),
|
||||
})
|
||||
assert (".go()", ".greet()") in calls, "the own-field case must keep working"
|
||||
assert (".run()", ".greet()") in calls, "the inherited-field case was the gap"
|
||||
|
||||
|
||||
def test_java_grandparent_field_is_reachable_through_the_chain(tmp_path):
|
||||
calls, _ = _graph(tmp_path, {
|
||||
"src/lib/Greeter.java": GREETER,
|
||||
"src/lib/A.java": "package lib;\npublic class A { protected Greeter greeter = new Greeter(); }\n",
|
||||
"src/lib/B.java": "package lib;\npublic class B extends A { }\n",
|
||||
"src/lib/C.java": (
|
||||
"package lib;\npublic class C extends B {\n"
|
||||
" void run() { this.greeter.greet(\"grandparent\"); }\n}\n"),
|
||||
})
|
||||
assert (".run()", ".greet()") in calls
|
||||
|
||||
|
||||
def test_java_a_redeclared_field_uses_the_nearest_declaration(tmp_path):
|
||||
"""Sub redeclares the field with another type; the subclass wins."""
|
||||
calls, _ = _graph(tmp_path, {
|
||||
"src/lib/Greeter.java": GREETER,
|
||||
"src/lib/Other.java": (
|
||||
"package lib;\npublic class Other {\n"
|
||||
" public String greet(String who) { return who; }\n"
|
||||
" public String shout(String who) { return who; }\n}\n"),
|
||||
"src/lib/Base.java": "package lib;\npublic class Base { protected Greeter helper = new Greeter(); }\n",
|
||||
"src/lib/Sub.java": (
|
||||
"package lib;\npublic class Sub extends Base {\n"
|
||||
" protected Other helper = new Other();\n"
|
||||
" void run() { this.helper.shout(\"x\"); }\n}\n"),
|
||||
})
|
||||
assert (".run()", ".shout()") in calls
|
||||
|
||||
|
||||
def test_java_untyped_bare_receiver_still_produces_nothing(tmp_path):
|
||||
"""A bare lowercase receiver with no known type must stay unresolved —
|
||||
only `this.`-prefixed receivers may consult the field tables, because a
|
||||
local can shadow a field but never `this.field`."""
|
||||
calls, _ = _graph(tmp_path, {
|
||||
"src/lib/Greeter.java": GREETER,
|
||||
"src/lib/Base.java": "package lib;\npublic class Base { protected Greeter mystery = new Greeter(); }\n",
|
||||
"src/lib/Sub.java": (
|
||||
"package lib;\npublic class Sub extends Base {\n"
|
||||
" void run() { Object mystery = fetch(); }\n"
|
||||
" Object fetch() { return null; }\n}\n"),
|
||||
})
|
||||
assert (".run()", ".greet()") not in calls
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# C# (same-file half; the per-file tables merge up the local chain)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_csharp_same_file_inherited_field_types_the_receiver(tmp_path):
|
||||
calls, _ = _graph(tmp_path, {"src/S.cs": (
|
||||
"public class Greeter { public void Greet() { } }\n"
|
||||
"public class PBase { protected Greeter greeter = new Greeter(); }\n"
|
||||
"public class Pair : PBase {\n"
|
||||
" public void Run() { this.greeter.Greet(); }\n"
|
||||
"}\n")})
|
||||
assert any(s == ".Run()" and t == ".Greet()" for (s, t) in calls), sorted(calls)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Objective-C (corpus tables already merge across files; the chain walk was
|
||||
# the missing half)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
try:
|
||||
import tree_sitter_objc # noqa: F401
|
||||
HAVE_OBJC = True
|
||||
except ImportError:
|
||||
HAVE_OBJC = False
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAVE_OBJC, reason="tree-sitter-objc not installed")
|
||||
def test_objc_property_on_the_superclass_types_self_field(tmp_path, monkeypatch):
|
||||
files = {
|
||||
"src/Greeter.h": "#import <Foundation/Foundation.h>\n@interface Greeter : NSObject\n- (void)greet;\n@end\n",
|
||||
"src/Greeter.m": '#import "Greeter.h"\n@implementation Greeter\n- (void)greet { NSLog(@"hi"); }\n@end\n',
|
||||
"src/Base.h": ('#import <Foundation/Foundation.h>\n#import "Greeter.h"\n'
|
||||
"@interface Base : NSObject\n@property (nonatomic, strong) Greeter *greeter;\n@end\n"),
|
||||
"src/Base.m": '#import "Base.h"\n@implementation Base\n@end\n',
|
||||
"src/Sub.h": ('#import "Base.h"\n@interface Sub : Base\n- (void)run;\n@end\n'),
|
||||
"src/Sub.m": '#import "Sub.h"\n@implementation Sub\n- (void)run { [self.greeter greet]; }\n@end\n',
|
||||
}
|
||||
for name, body in files.items():
|
||||
p = tmp_path / name
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(body, encoding="utf-8")
|
||||
monkeypatch.chdir(tmp_path) # relative paths: independent of the #3150 fix
|
||||
with redirect_stdout(io.StringIO()):
|
||||
r = extract([Path(n) for n in files], cache_root=Path(tempfile.mkdtemp()), parallel=False)
|
||||
labels = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
calls = {(labels.get(e["source"]), labels.get(e["target"]))
|
||||
for e in r["edges"] if e.get("relation") == "calls"}
|
||||
assert ("-run", "-greet") in calls, sorted(calls)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The table binder itself
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.skipif(_bind_member_field_tables is None, reason="pre-fix tree")
|
||||
def test_binder_matches_by_label_and_disambiguates_by_file():
|
||||
nodes = [
|
||||
{"id": "a_base", "label": "Base", "source_file": "a/Base.java"},
|
||||
{"id": "b_base", "label": "Base", "source_file": "b/Base.java"},
|
||||
{"id": "c_only", "label": "Only", "source_file": "c/Only.java"},
|
||||
]
|
||||
per_file = [{"member_field_tables": [
|
||||
{"lang": "java", "class_label": "Base", "source_file": "a/Base.java",
|
||||
"fields": {"g": "Greeter"}},
|
||||
{"lang": "java", "class_label": "Only", "source_file": "c/Only.java",
|
||||
"fields": {"h": "Helper"}},
|
||||
{"lang": "csharp", "class_label": "Only", "source_file": "c/Only.java",
|
||||
"fields": {"x": "Nope"}}, # other language: ignored
|
||||
]}]
|
||||
bound = _bind_member_field_tables(per_file, nodes, lang="java")
|
||||
assert bound == {"a_base": {"g": "Greeter"}, "c_only": {"h": "Helper"}}
|
||||
|
||||
|
||||
@pytest.mark.skipif(_bind_member_field_tables is None, reason="pre-fix tree")
|
||||
def test_binder_skips_what_it_cannot_disambiguate():
|
||||
nodes = [
|
||||
{"id": "a_base", "label": "Base", "source_file": "a/Base.java"},
|
||||
{"id": "b_base", "label": "Base", "source_file": "b/Base.java"},
|
||||
]
|
||||
per_file = [{"member_field_tables": [
|
||||
{"lang": "java", "class_label": "Base", "source_file": "elsewhere/Base.java",
|
||||
"fields": {"g": "Greeter"}},
|
||||
]}]
|
||||
# both candidates share the basename -> still ambiguous -> bind nothing
|
||||
assert _bind_member_field_tables(per_file, nodes, lang="java") == {}
|
||||
@@ -241,7 +241,11 @@ def test_ambiguous_receiver_type_emits_no_edge(tmp_path: Path):
|
||||
assert send_targets == set()
|
||||
|
||||
|
||||
def test_inherited_field_and_chained_receiver_are_deferred(tmp_path: Path):
|
||||
def test_inherited_field_resolves_and_chained_receiver_stays_deferred(tmp_path: Path):
|
||||
"""#3151: a field declared on the superclass now types `this.<field>` in
|
||||
the subclass, so `this.gateway.charge()` resolves. A chained receiver
|
||||
(`factory.create().charge()`) still carries no declared type and stays
|
||||
deferred rather than guessed."""
|
||||
calls, result = _calls(tmp_path, {
|
||||
"Services.java": (
|
||||
"class Gateway { void charge() {} Gateway create() { return this; } }\n"
|
||||
@@ -256,7 +260,9 @@ def test_inherited_field_and_chained_receiver_are_deferred(tmp_path: Path):
|
||||
|
||||
inherited = _find(result, ".inherited()", "checkout")
|
||||
chained = _find(result, ".chained()", "checkout")
|
||||
assert not any(source in {inherited, chained} and "charge" in target
|
||||
assert any(source == inherited and "charge" in target
|
||||
for source, target in calls), "superclass field must type the receiver"
|
||||
assert not any(source == chained and "charge" in target
|
||||
for source, target in calls)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user