Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(graph): an overload tie never lands on an overload that can't take the call's arguments (#3625)

Swati Ahuja0925186235d9
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 3b2dec8b3..65df0b194 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -185,6 +185,23 @@ def _overload_return_types(
return found
+def _overload_phase(admitted: tuple[int, int | None], argument_count: int) -> int | None:
+ """The first phase in which a member with *admitted* arguments takes the call.
+
+ 0 for exactly that arity, 1 when its defaults admit the count (Java's first
+ phase, C#'s normal form), 2 when its varargs or ``params`` expand to it,
+ and None when it cannot take the call.
+ """
+ fewest, most = admitted
+ if argument_count < fewest:
+ return None
+ if most is None:
+ return 2
+ if argument_count > most:
+ return None
+ return 0 if fewest == most else 1
+
+
def _flattened_wildcard_source(imp: Import) -> str | None:
"""The repository file whose every name *imp* forwards, or None.
@@ -315,6 +332,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# {representative: ((member id, (fewest, most) arguments), ...)}.
self._overload_rep: dict[str, str] = {}
self._overload_members: dict[str, tuple[tuple[str, tuple[int, int | None]], ...]] = {}
+ # Representatives of sets with a member whose range is unknown; a count
+ # cannot choose there, since that member may admit it too.
+ self._unranged_overload_sets: set[str] = set()
self._symbols_by_id = {
symbol.id: symbol for parsed in parsed_files.values() for symbol in parsed.symbols
}
@@ -630,7 +650,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
for sym in overloads:
representatives[sym.id] = rep
admitted = signature_parameter_range(sym.signature or "", sym.language)
- if admitted is not None:
+ if admitted is None:
+ self._unranged_overload_sets.add(rep)
+ else:
ranges.setdefault(sym.id, admitted)
self._overload_members[rep] = tuple(ranges.items())
self._overload_rep.update(representatives)
@@ -909,14 +931,13 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""Move an edge on an overload set onto the member its arguments call.
Every tier answers with the set's representative; this is the one place
- a member is chosen. A count no member admits, a tie, or an unknown count
- (a method reference, a C# method group) keeps the representative. An
- overload calling itself is recursion, which draws no edge.
+ a member is chosen (``_overload_target``). An overload calling itself is
+ recursion, which draws no edge.
"""
rep = self._overload_rep.get(resolved.callee_id)
if rep is None:
return resolved
- target = self._pick_overload(rep, call.argument_count) or rep
+ target = self._overload_target(rep, call.argument_count)
if target == resolved.caller_id:
return None
return resolved if target == resolved.callee_id else replace(resolved, callee_id=target)
@@ -929,17 +950,46 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
form), then one whose varargs or ``params`` expand to it. The first
phase with any candidate decides, and two candidates there are a tie.
"""
- if argument_count is None:
- return None
- members = self._overload_members.get(rep, ())
- phases = (
- [m for m, (fewest, most) in members if fewest == most == argument_count],
- [m for m, (fewest, most) in members if most is not None and fewest <= argument_count <= most],
- [m for m, (fewest, most) in members if most is None and fewest <= argument_count],
- )
- found = next((phase for phase in phases if phase), [])
+ found = self._deciding_overloads(rep, argument_count)
return found[0] if len(found) == 1 else None
+ def _overload_target(self, rep: str, argument_count: int | None) -> str:
+ """The member of *rep*'s set a call lands on.
+
+ The member ``_pick_overload`` names, else the representative when the
+ count cannot choose: it is unknown (a method reference, a C# method
+ group), no member admits it, or a member's range is unknown, since
+ that member may admit it too. A tie keeps the representative when it
+ is one of the tied members. A tie among others takes the first of them in declaration
+ order, the order the overload index records: ``charset(x)`` over
+ ``charset()``, ``charset(String)`` and ``charset(Charset)`` never means
+ the no-argument representative, but it does mean the set, which dead
+ code judges as one unit and a constructor set needs for any inbound
+ edge at all.
+ """
+ found = self._deciding_overloads(rep, argument_count)
+ if len(found) == 1:
+ return found[0]
+ tied = self._tied_without_representative(rep, found)
+ return tied[0] if tied else rep
+
+ def _tied_without_representative(self, rep: str, found: list[str]) -> list[str]:
+ """*found* when it is a tie the representative is not in."""
+ if len(found) > 1 and rep not in found:
+ return found
+ return []
+
+ def _deciding_overloads(self, rep: str, argument_count: int | None) -> list[str]:
+ """The members of the first phase with any candidate for *argument_count*."""
+ if argument_count is None or rep in self._unranged_overload_sets:
+ return []
+ phases: dict[int, list[str]] = defaultdict(list)
+ for member, admitted in self._overload_members.get(rep, ()):
+ phase = _overload_phase(admitted, argument_count)
+ if phase is not None:
+ phases[phase].append(member)
+ return phases[min(phases)] if phases else []
+
def _overload_sibling_call(self, call: CallSite) -> ResolvedCall | None:
"""An overload calling another member of its own set, ``f(a)`` inside ``f(a, b)``.
@@ -1220,7 +1270,18 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
callee_id = resolved_inner.callee_id
rep = self._overload_rep.get(callee_id)
if rep is not None:
- callee_id = self._pick_overload(rep, inner.argument_count) or callee_id
+ tied = self._tied_without_representative(
+ rep, self._deciding_overloads(rep, inner.argument_count)
+ )
+ # A tie names a type only when every tied member returns it.
+ returns = {
+ self._callee_return_type(member, inner.argument_count, language) for member in tied
+ }
+ if len(returns) > 1 or None in returns:
+ return None
+ target = self._overload_target(rep, inner.argument_count)
+ if target != rep:
+ callee_id = target
return callee_id
def _callee_chain_return_type(
diff --git a/tests/unit/dead_code/test_overload_unit.py b/tests/unit/dead_code/test_overload_unit.py
index 133213b96..38ee69364 100644
--- a/tests/unit/dead_code/test_overload_unit.py
+++ b/tests/unit/dead_code/test_overload_unit.py
@@ -9,9 +9,12 @@ put them.
from __future__ import annotations
+from pathlib import Path
+
import networkx as nx
from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
_FILE = "src/Box.cs"
_CONFIG = {
@@ -105,3 +108,34 @@ def test_a_call_to_one_cpp_overload_uses_the_exported_set() -> None:
assert sorted(f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT) == [
"spare"
]
+
+
+def test_a_call_tied_between_overloads_keeps_the_set_used(tmp_path: Path) -> None:
+ """``new Inner(x)`` and ``cs(x)`` tie between one-argument members.
+
+ The tie still draws an edge into the set, so neither the class nor the
+ method set reads as unused. ``Spare`` is the control.
+ """
+ source = tmp_path / "app" / "Main.java"
+ source.parent.mkdir()
+ source.write_text(
+ "package app;\n"
+ "public class Main {\n"
+ " private static class Inner {\n"
+ " Inner() { }\n"
+ " Inner(String s) { }\n"
+ " Inner(int n) { }\n"
+ " }\n"
+ " private static class Spare { }\n"
+ " private String cs() { return null; }\n"
+ " private Main cs(String s) { return this; }\n"
+ " private Main cs(Object o) { return this; }\n"
+ " public void run(String x) { new Inner(x); cs(x); }\n"
+ "}\n",
+ encoding="utf-8",
+ )
+ parser, builder = ASTParser(), GraphBuilder(repo_path=tmp_path)
+ for fi in FileTraverser(tmp_path).traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ report = DeadCodeAnalyzer(builder.build(), git_meta_map={}).analyze(_CONFIG)
+ assert sorted(f.symbol_name for f in report.findings) == ["Spare"]
diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.py
index f66f8744a..18b7438fd 100644
--- a/tests/unit/ingestion/test_overload_identity.py
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -697,3 +697,161 @@ class TestNarrowingShapes:
)
edges = _edges(tmp_path, {"app/Base.java": ("java", base), "app/Derived.java": ("java", derived)})
assert edges == {("app/Derived.java::Derived::f", "app/Base.java::Base::f")}
+
+
+class TestOverloadTies:
+ """A tie lands on a member that admits the call.
+
+ Call sites carry no argument types, so same-arity members tie. A tie keeps
+ the representative, the first member declared, when it is tied; a tie
+ among others takes the first tied member in declaration order. Before, a
+ tie always answered with the representative, even when its own arity
+ could not take the call.
+ """
+
+ def test_java_a_tie_among_other_members_takes_the_first_admitting_one(
+ self, tmp_path: Path
+ ) -> None:
+ text = (
+ "package app;\npublic class Out {\n"
+ " public String charset() { return \"\"; }\n"
+ " public Out charset(String name) { return this; }\n"
+ " public Out charset(java.nio.charset.Charset cs) { return this; }\n"
+ " void use(String x) { charset(x); }\n"
+ " void read() { charset(); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"app/Out.java": ("java", text)})
+ base = "app/Out.java::Out::"
+ assert {c for a, c in edges if a == base + "use"} == {base + "charset#1(String)"}
+ assert {c for a, c in edges if a == base + "read"} == {base + "charset#0"}
+
+ def test_java_a_constructor_tie_keeps_an_inbound_edge(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class A {\n"
+ " A() { }\n"
+ " A(String s) { }\n"
+ " A(int n) { }\n"
+ " static A mk(String x) { return new A(x); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"app/A.java": ("java", text)})
+ base = "app/A.java::A::"
+ assert {c for a, c in edges if a == base + "mk"} == {base + "A#1(String)"}
+
+ def test_java_a_varargs_tie_respects_each_floor(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class L {\n"
+ " public void log(String msg) { }\n"
+ " public void log(String fmt, Object... args) { }\n"
+ " public void log(int level, String fmt, Object... args) { }\n"
+ " void one(String m) { log(m); }\n"
+ " void three(String m) { log(m, 1, 2); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"app/L.java": ("java", text)})
+ base = "app/L.java::L::"
+ assert {c for a, c in edges if a == base + "one"} == {base + "log#1"}
+ # Both varargs members admit three arguments; the representative does not.
+ assert {c for a, c in edges if a == base + "three"} == {base + "log#2"}
+
+ def test_java_a_varargs_representative_in_the_tie_is_kept(self, tmp_path: Path) -> None:
+ text = (
+ "package app;\npublic class F {\n"
+ " public void fmt(String f, Object... args) { }\n"
+ " public void fmt(int n, Object... args) { }\n"
+ " public void fmt() { }\n"
+ " void use() { fmt(\"a\", 1); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"app/F.java": ("java", text)})
+ base = "app/F.java::F::"
+ assert {c for a, c in edges if a == base + "use"} == {base + "fmt#2(String,Object[])"}
+
+ def test_csharp_a_tie_among_other_members_takes_the_first_admitting_one(
+ self, tmp_path: Path
+ ) -> None:
+ holder = (
+ "namespace App;\npublic static class H {\n"
+ " public static int Sum() => 0;\n"
+ " public static int Sum(int a) => a;\n"
+ " public static int Sum(string s) => 0;\n"
+ "}\n"
+ )
+ caller = (
+ "namespace App;\npublic class C {\n"
+ " public int One() => H.Sum(1);\n"
+ " public int None() => H.Sum();\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"H.cs": ("csharp", holder), "C.cs": ("csharp", caller)})
+ assert {c for a, c in edges if a == "C.cs::C::One"} == {"H.cs::H::Sum#1(int)"}
+ assert ("C.cs::C::None", "H.cs::H::Sum#0") in edges
+
+ def test_cpp_a_tie_on_declared_defaults_takes_the_first_admitting_one(
+ self, tmp_path: Path
+ ) -> None:
+ header = (
+ "class Pen {\n public:\n void shift();\n"
+ " void shift(int x, int y = 0);\n void shift(double x, double y = 0);\n};\n"
+ )
+ source = (
+ '#include "pen.h"\n'
+ "void Pen::shift() {}\n"
+ "void Pen::shift(int x, int y) {}\n"
+ "void Pen::shift(double x, double y) {}\n"
+ )
+ caller = '#include "pen.h"\nvoid draw(Pen& p) {\n p.shift(1);\n}\nvoid lift(Pen& p) {\n p.shift();\n}\n'
+ edges = _edges(
+ tmp_path, {"pen.h": ("cpp", header), "pen.cpp": ("cpp", source), "draw.cpp": ("cpp", caller)}
+ )
+ # Both two-parameter members admit one argument through the defaults
+ # their declarations write; the no-argument representative does not.
+ assert {c for a, c in edges if a == "draw.cpp::draw"} == {"pen.cpp::Pen::shift#2(int,int)"}
+ assert ("draw.cpp::lift", "pen.cpp::Pen::shift#0") in edges
+
+ def test_a_member_with_an_unknown_range_keeps_the_representative(self, tmp_path: Path) -> None:
+ """A member whose parameter list cannot be read may admit any count."""
+ text = (
+ "package app;\npublic class P {\n"
+ " void put() { }\n"
+ " void put(int a) { }\n"
+ " void put(String s, int n) { }\n"
+ " void use() { put(1); }\n"
+ "}\n"
+ )
+ parsed = _parse("app/P.java", "java", text, tmp_path)
+ for symbol in parsed.symbols:
+ if symbol.id == "app/P.java::P::put#2":
+ symbol.signature = "put" # no closed parameter list: range unknown
+ resolver = CallResolver({"app/P.java": parsed}, {"app/P.java": set()}, repo_path=str(tmp_path))
+ edges = {(rc.caller_id, rc.callee_id) for rc in resolver.resolve_file("app/P.java", parsed.calls)}
+ # Only put#1 is known to admit one argument, but put#2 may too: the
+ # count does not choose, and the representative answers.
+ assert edges == {("app/P.java::P::use", "app/P.java::P::put#0")}
+
+ @pytest.mark.parametrize(
+ ("second_returns", "typed"), [("Tag", True), ("Cs", False)]
+ )
+ def test_csharp_a_chain_through_a_tie_needs_one_return_type(
+ self, tmp_path: Path, second_returns: str, typed: bool
+ ) -> None:
+ # Two Label() methods; untyped, the bare-name tiers answer Cs's, the
+ # one declared last.
+ types = (
+ "namespace App;\npublic class Tag {\n public string Label() => \"\";\n}\n"
+ "public class Cs {\n public string Label() => \"\";\n}\n"
+ )
+ holder = (
+ "namespace App;\npublic class Out {\n"
+ " public Cs Charset() => null;\n"
+ " public Tag Charset(string name) => null;\n"
+ f" public {second_returns} Charset(Out other) => null;\n"
+ " public string Use(string x) => Charset(x).Label();\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"Cs.cs": ("csharp", types), "Out.cs": ("csharp", holder)})
+ # Charset() returns Cs, but Charset(x) is not Charset(). The tied
+ # members type the chain only when they agree; the first one's type
+ # alone (Tag) is not taken.
+ assert (("Out.cs::Out::Use", "Cs.cs::Tag::Label") in edges) is typed