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.

feat(graph): link a base method to the implementations that answer for it (#1649)

Raghav Chamadiya1adfbd95fcc2
diff --git a/packages/core/src/repowise/core/analysis/knowledge_graph.py b/packages/core/src/repowise/core/analysis/knowledge_graph.py
index 0397bd833..1dd88fe69 100644
--- a/packages/core/src/repowise/core/analysis/knowledge_graph.py
+++ b/packages/core/src/repowise/core/analysis/knowledge_graph.py
@@ -241,6 +241,7 @@ _EDGE_TYPE_MAP: dict[str, str] = {
"extends": "depends_on",
"implements": "depends_on",
"method_implements": "depends_on",
+ "dispatches_to": "depends_on",
"reads": "depends_on",
"references": "depends_on",
}
diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
index c8b21800c..04f93b2aa 100644
--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
@@ -108,6 +108,7 @@ _RELATION_VERB: dict[str, str] = {
"extends": "extends",
"implements": "implements",
"method_implements": "implements",
+ "dispatches_to": "dispatches to",
"reads": "reads from",
# Named rather than called: a dispatch-table entry, a callback field, an
# argument to a registration macro. "references" is the honest verb, since
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 97d615805..76ac8a0c5 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -54,6 +54,27 @@ log = structlog.get_logger(__name__)
# bare call there is a free function and this tier would resolve it wrongly.
_IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})
+# Languages where a call the caller's own class cannot answer is looked for on
+# its ancestors. Both shapes — an explicit ``self``/``this`` receiver and an
+# implicit one — end in the same walk.
+#
+# C# is absent, and it is an exclusion rather than an omission: the method
+# indexes are keyed ``(class, method)`` with no parameter list, so a class
+# declaring several overloads of one name keeps whichever the index kept. Its
+# precision audit came back 7/30, every failure the same wrong-overload
+# pairing. C++ is absent because its heritage binds a qualified external
+# parent to a same-named local type, which puts unrelated siblings in one
+# hierarchy before this walk even runs. Java is absent because `java.scm`'s
+# bare-call pattern also matches `this.field.m()`, which no receiver-carrying
+# pattern claims, so such a call arrives here indistinguishable from a real
+# implicit receiver — and its measured population on two Java repos was zero,
+# so the tier could only cost.
+_INHERITED_LANGUAGES = frozenset({"kotlin", "python", "typescript", "swift"})
+
+# Ancestors within four hops: ``heritage_ancestors`` bounds expansion, not
+# reach, so 3 reaches 4.
+_MAX_ANCESTOR_EXPAND_DEPTH = 3
+
@dataclass(frozen=True, slots=True)
class _LanguageCallStrategies:
@@ -141,7 +162,13 @@ class CallResolver:
*,
repo_path: str | None = None,
import_maps: Any | None = None,
+ heritage_parents: dict[str, set[str]] | None = None,
) -> None:
+ # {type symbol id: parent type symbol ids}, from the caller's already
+ # resolved heritage. Absent when the resolver is built standalone, in
+ # which case the inherited tier simply never fires.
+ self._heritage_parents: dict[str, set[str]] = heritage_parents or {}
+ self._ancestors: dict[str, tuple[str, ...]] = {}
# Per-file symbol index: {file_path: {symbol_name: symbol_id}}
self._file_symbols: dict[str, dict[str, str]] = {}
@@ -805,6 +832,22 @@ class CallResolver:
return None # reject cross-language Tier 3 match
return ResolvedCall(caller_id, candidates[0], 0.50, call.line, "global_unique")
+ # Last, so it can only add an edge. The member-shaped refusal is the
+ # one ``_enclosing_class_method`` already applies: several grammars
+ # mint a receiver-less site for ``obj.m()`` too, and reading one as an
+ # implicit receiver would bind the wrong class's hierarchy to the call.
+ lang = self._language_of(file_path)
+ if (
+ lang in _IMPLICIT_RECEIVER_LANGUAGES
+ and lang in _INHERITED_LANGUAGES
+ and (call.line, target_name) not in self._member_shaped_sites(file_path)
+ ):
+ sym_id = self._inherited_method(caller_id, target_name)
+ if sym_id is not None:
+ return ResolvedCall(
+ caller_id, sym_id, 0.90, call.line, "enclosing_inherited"
+ )
+
return None
def _resolve_member_call(
@@ -891,8 +934,80 @@ class CallResolver:
if hit is not None:
return hit
+ # Strategy 3, continued: the method may be inherited, and Strategy 3
+ # can only see the caller's own class in the caller's own file. Asked
+ # last so it can add an edge and never displace one.
+ if receiver_name in ("self", "this") and self._language_of(file_path) in (
+ _INHERITED_LANGUAGES
+ ):
+ sym_id = self._inherited_method(caller_id, method_name)
+ if sym_id is not None:
+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "self_inherited")
+
return None
+ def _language_of(self, file_path: str) -> str | None:
+ parsed = self._parsed_files.get(file_path)
+ return parsed.file_info.language if parsed else None
+
+ def _inherited_method(self, caller_id: str, method_name: str) -> str | None:
+ """The method of this name an ancestor of the caller's class declares.
+
+ Ambiguity is terminal: when two ancestors on different branches declare
+ the name there is no way to tell which one the call means, and picking
+ either mints an edge to a class the call may never reach. Refusing
+ costs an edge; guessing costs correctness.
+ """
+ if not self._heritage_parents:
+ return None
+ class_id = _extract_class_id(caller_id)
+ if class_id is None:
+ return None
+ # The caller's own class answers, even when the earlier tier declined
+ # it. Recursion is the case: Strategy 3 refuses to point a call at its
+ # own symbol, and without this that refusal fell through to an
+ # ancestor's bodiless declaration of the same name.
+ if self._declares(class_id, method_name) is not None:
+ return None
+ hits = set()
+ for ancestor in self._ancestors_of(class_id):
+ sym_id = self._declares(ancestor, method_name)
+ if sym_id is not None and sym_id != caller_id:
+ hits.add(sym_id)
+ return next(iter(hits)) if len(hits) == 1 else None
+
+ def _declares(self, class_id: str, method_name: str) -> str | None:
+ """The symbol a type node declares under *method_name*, or None.
+
+ Splitting on the *first* separator, not the last: a nested class is
+ ``path::Outer::Inner`` and ``_file_methods`` keys it under ``Inner``
+ in ``path``. Taking the last would look for a file called
+ ``path::Outer``, miss silently, and — worse than a missed edge — hide
+ an ancestor from the ambiguity check above, letting a wrong single
+ candidate through as if it were unopposed.
+ """
+ file_path, _, name = class_id.partition("::")
+ return self._file_methods.get(file_path, {}).get((name.rpartition("::")[2], method_name))
+
+ def _ancestors_of(self, class_id: str) -> tuple[str, ...]:
+ got = self._ancestors.get(class_id)
+ if got is None:
+ from .heritage_resolver import heritage_ancestors
+
+ # Sorted, because the walk stops expanding an anchor after its
+ # first visit: which branch reaches it first decides how much of
+ # its own chain is expanded, and a set's order is not stable
+ # across processes.
+ reached = heritage_ancestors(
+ class_id,
+ lambda t: sorted(self._heritage_parents.get(t, ())),
+ max_expand_depth=_MAX_ANCESTOR_EXPAND_DEPTH,
+ )
+ reached.discard(class_id)
+ got = tuple(sorted(reached))
+ self._ancestors[class_id] = got
+ return got
+
def _receiver_pair_match(
self,
file_path: str,
@@ -1202,6 +1317,17 @@ def _rivals_a_class_method(symbol_id: str) -> bool:
return len(parts) >= 3 and parts[-1] != parts[-2]
+def _extract_class_id(symbol_id: str) -> str | None:
+ """``path::Cls::meth`` -> ``path::Cls``; None when no class encloses it.
+
+ The heritage graph is keyed on the class's own symbol id, so the class
+ *name* alone cannot be looked up in it — that is the name-keyed shortcut
+ the walk exists to avoid.
+ """
+ parts = symbol_id.split("::")
+ return "::".join(parts[:-1]) if len(parts) >= 3 else None
+
+
def _extract_class_from_symbol_id(symbol_id: str) -> str | None:
"""Extract parent class name from a symbol ID like 'path::ClassName::method'."""
parts = symbol_id.split("::")
diff --git a/packages/core/src/repowise/core/ingestion/dispatch_edges.py b/packages/core/src/repowise/core/ingestion/dispatch_edges.py
new file mode 100644
index 000000000..b1f35d040
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dispatch_edges.py
@@ -0,0 +1,173 @@
+"""Override dispatch: a base method and the implementations that answer for it.
+
+A call written against a base type resolves to the base's method, and there the
+graph stops. Nothing joins ``Handler.handle`` to the twelve classes that
+implement it, so a traversal from the caller never reaches the code that runs,
+and every implementation reads as called by nobody.
+
+This pass runs once over the built graph and emits ``dispatches_to`` from a
+base method to each same-named method declared by a type that inherits from it.
+It is a post-pass rather than a resolution tier because it needs the heritage
+edges to exist first, and it reads only the graph — no source text, no parse.
+
+**Node-anchored.** Both the ancestor walk and the method lookup go through
+symbol ids: parents come from the graph's own ``extends`` / ``implements``
+edges, methods from ``has_method``. A name-keyed version would union the
+parents of every same-named class in the repo, which is the error
+``heritage_ancestors`` refuses in terms.
+
+**What it deliberately cannot see.** ``has_method`` is emitted per file, so a
+method declared away from its type — a Go method set spread over a package, a
+C++ class whose bodies live in the ``.cc``, a C# partial class — is invisible
+here. That is a missed edge, never a wrong one.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+
+import structlog
+
+from .heritage_resolver import heritage_ancestors
+
+log = structlog.get_logger(__name__)
+
+# Languages whose dispatch edges passed a precision audit. A language absent
+# here is mostly one that was never attempted — except C++, which was
+# attempted and failed at 21/30: a qualified external parent binds to a
+# same-named local type, so unrelated siblings land in one hierarchy, and a
+# class-scoped boilerplate macro is extracted as a method every subtype
+# "overrides".
+DISPATCH_LANGUAGES: frozenset[str] = frozenset(
+ {"java", "csharp", "kotlin", "swift", "python"}
+)
+
+_HERITAGE_EDGE_TYPES = frozenset({"extends", "implements"})
+
+# Ancestors within four hops: ``heritage_ancestors`` bounds expansion, not
+# reach, so 3 reaches 4. Same depth the resolver's inherited tier uses.
+_MAX_EXPAND_DEPTH = 3
+
+# A base method answered by more implementations than this is a dispatch point
+# too broad to say anything useful about — every implementation would gain an
+# incoming edge from it and the base would gain the out-degree of a hub it is
+# not. Refused whole rather than truncated, so the cap cannot be mistaken for
+# a complete answer.
+_MAX_IMPLEMENTATIONS = 24
+
+# Name-matched, no signature compared, so the relation is a possible dispatch
+# target rather than a proven override. Sits at the confidence the resolver
+# gives its own "the pair exists somewhere in the repo" tier.
+_DISPATCH_CONFIDENCE = 0.75
+
+# A constructor is never dispatched to: calling the base's runs the base's.
+# Python spells it; the C family names it after the class, which is the same
+# rule `_rivals_a_class_method` encodes in the resolver.
+_CONSTRUCTOR_NAMES = frozenset({"__init__", "__new__", "constructor"})
+
+# Languages where `private` is enforced and therefore excludes a member from
+# dispatch entirely: a private base is not virtual and a private member of a
+# subtype overrides nothing. Python and TypeScript are absent because their
+# `_name` / `private` are conventions the runtime does not enforce. Found by
+# the C# precision audit, where four of six wrong edges were a `private` test
+# helper that happened to share a name with a `virtual` base.
+_PRIVATE_IS_NOT_DISPATCHED = frozenset({"java", "csharp", "kotlin", "swift", "cpp"})
+
+
+def _methods_by_name(graph, type_id: str) -> dict[str, list[str]]:
+ """``{method name: [symbol ids]}`` for one type node, dispatchable only.
+
+ A list, not a symbol: a class declaring two same-named methods is an
+ overload group, and keying by name alone would keep one of them
+ arbitrarily.
+ """
+ out: dict[str, list[str]] = defaultdict(list)
+ for _, member, data in graph.out_edges(type_id, data=True):
+ if data.get("edge_type") != "has_method":
+ continue
+ node = graph.nodes[member]
+ name = node.get("name")
+ if not name:
+ continue
+ if (
+ node.get("visibility") == "private"
+ and node.get("language") in _PRIVATE_IS_NOT_DISPATCHED
+ ):
+ continue
+ out[name].append(member)
+ return out
+
+
+def _is_constructor(name: str, type_id: str) -> bool:
+ return name in _CONSTRUCTOR_NAMES or name == type_id.rpartition("::")[2]
+
+
+def resolve_override_dispatch(
+ graph,
+ *,
+ languages: frozenset[str] = DISPATCH_LANGUAGES,
+ max_implementations: int = _MAX_IMPLEMENTATIONS,
+) -> int:
+ """Emit ``dispatches_to`` edges. Returns the number added."""
+ parents: dict[str, set[str]] = defaultdict(set)
+ for child, parent, data in graph.edges(data=True):
+ if data.get("edge_type") not in _HERITAGE_EDGE_TYPES:
+ continue
+ if (
+ graph.nodes[child].get("node_type") == "symbol"
+ and graph.nodes[parent].get("node_type") == "symbol"
+ ):
+ parents[child].add(parent)
+
+ methods: dict[str, dict[str, list[str]]] = {}
+
+ def methods_of(type_id: str) -> dict[str, list[str]]:
+ got = methods.get(type_id)
+ if got is None:
+ got = _methods_by_name(graph, type_id)
+ methods[type_id] = got
+ return got
+
+ # base method id -> the implementations that could answer for it
+ candidates: dict[str, set[str]] = defaultdict(set)
+ for child in sorted(parents):
+ if graph.nodes[child].get("language") not in languages:
+ continue
+ child_methods = methods_of(child)
+ if not child_methods:
+ continue
+ # Sorted, because the walk stops expanding an anchor after its first
+ # visit: which branch reaches it first decides how much of its own
+ # chain is expanded, and a set's order is not stable across processes.
+ for ancestor in heritage_ancestors(
+ child, lambda t: sorted(parents.get(t, ())), max_expand_depth=_MAX_EXPAND_DEPTH
+ ):
+ if ancestor == child:
+ continue
+ for name, bases in methods_of(ancestor).items():
+ impls = child_methods.get(name)
+ if impls is None or _is_constructor(name, ancestor):
+ continue
+ for base in bases:
+ candidates[base].update(impl for impl in impls if impl != base)
+
+ added = 0
+ refused = 0
+ for base in sorted(candidates):
+ impls = candidates[base]
+ if len(impls) > max_implementations:
+ refused += 1
+ continue
+ for impl in sorted(impls):
+ if graph.has_edge(base, impl):
+ continue
+ graph.add_edge(
+ base,
+ impl,
+ edge_type="dispatches_to",
+ confidence=_DISPATCH_CONFIDENCE,
+ )
+ added += 1
+
+ log.info("dispatch_edges", added=added, bases=len(candidates), over_cap=refused)
+ return added
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 7c6ca9b05..d2039c9a2 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -6,6 +6,7 @@ emitting EXTENDS/IMPLEMENTS, ``reads``, and ``calls`` edges respectively.
from __future__ import annotations
+from collections import defaultdict
from typing import Any
import structlog
@@ -488,6 +489,45 @@ class ResolveMixin:
if callable(done):
done(phase)
+ def _resolve_override_dispatch(self, progress: Any | None = None) -> None:
+ """Emit ``dispatches_to`` edges from base methods to implementations.
+
+ Runs last: it reads the heritage edges Phase 2 resolved and the
+ ``has_method`` edges ``add_file`` laid down, and nothing else.
+ """
+ from ..dispatch_edges import resolve_override_dispatch
+
+ phase = "graph.dispatch"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ resolve_override_dispatch(self._graph)
+ except Exception as exc:
+ log.warning("override_dispatch_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _heritage_parents(self) -> dict[str, set[str]]:
+ """``{type symbol id: parent type symbol ids}`` from the built graph.
+
+ Symbol ids, not type names: a name-keyed map unions the parents of
+ every same-named class in the repo and reaches ancestors that are not
+ this class's.
+ """
+ parents: dict[str, set[str]] = defaultdict(set)
+ for child, parent, data in self._graph.edges(data=True):
+ if data.get("edge_type") not in ("extends", "implements"):
+ continue
+ if (
+ self._graph.nodes[child].get("node_type") == "symbol"
+ and self._graph.nodes[parent].get("node_type") == "symbol"
+ ):
+ parents[child].add(parent)
+ return parents
+
def _resolve_calls(
self,
import_targets: dict[str, set[str]],
@@ -501,6 +541,7 @@ class ResolveMixin:
import_targets,
repo_path=str(self._repo_path) if self._repo_path else None,
import_maps=self._shared_import_maps(),
+ heritage_parents=self._heritage_parents(),
)
# Record which C/C++ declarations were paired with a definition. The
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 44435c2b1..cb3220c03 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -510,6 +510,10 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# --- Phase 3: Resolve symbol-level calls ---
self._resolve_calls(import_targets, progress=progress)
+ # --- Phase 4: Base method → the implementations that answer for it ---
+ # Post-pass: needs heritage resolved and reads only the graph.
+ self._resolve_override_dispatch(progress=progress)
+
self._built = True
# Keep the resolver-built DotNetProjectIndex reachable after the
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 9538a4a70..0a3cfb811 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -282,6 +282,13 @@ EdgeType = Literal[
"extends",
"implements",
"method_implements",
+ # Base method → an implementation that can answer for it. Named for what
+ # it asserts rather than for a heritage relation: the pass matches by
+ # method name and compares no signature, so it is a possible dispatch
+ # target, not a proven override. `method_implements` could not be reused —
+ # it runs implementor → interface, and this edge has to point the other
+ # way for a traversal starting at the base to reach the implementation.
+ "dispatches_to",
"co_changes",
"framework",
# A data reference rather than a call. Two `_add_reads_edge` helpers emit
@@ -364,6 +371,12 @@ ResolutionOrigin = Literal[
"receiver_field_same_package", # 0.90 (JVM)
"receiver_field_import", # 0.88
"receiver_field_global", # 0.75
+ # 0.90 — the caller's own class does not declare the method but exactly one
+ # of its ancestors does. Below the two same-class origins because the walk
+ # compares no signature and reads no visibility, so it can reach a method
+ # the language would not actually dispatch to.
+ "self_inherited", # 0.90 — explicit self/this receiver
+ "enclosing_inherited", # 0.90 — implicit receiver, bare call
]
RESOLUTION_ORIGIN_VALUES: frozenset[str] = frozenset(get_args(ResolutionOrigin))
@@ -449,6 +462,10 @@ SYMBOL_USE_EDGE_TYPES: frozenset[str] = frozenset(
"extends",
"implements",
"method_implements",
+ # An implementation is used by every call written against the base it
+ # answers for, and that call lands on the base. Without this the whole
+ # implementation side of an interface reads as called by nobody.
+ "dispatches_to",
"reads",
# Naming a function is using it. A handler sitting in a dispatch table
# is never called anywhere a parser can see, and treating that as "no
diff --git a/packages/server/src/repowise/server/services/c4_builder/labels.py b/packages/server/src/repowise/server/services/c4_builder/labels.py
index 8cf2e839d..584d3816b 100644
--- a/packages/server/src/repowise/server/services/c4_builder/labels.py
+++ b/packages/server/src/repowise/server/services/c4_builder/labels.py
@@ -35,6 +35,7 @@ _EDGE_VERB: dict[str, str] = {
"extends": "inherits from",
"implements": "implements",
"method_implements": "implements",
+ "dispatches_to": "dispatches to",
# A lazy/registry import and a framework-convention link (a test file to its
# conftest) are both real dependencies that no static import expresses.
"dynamic_uses": "uses",
diff --git a/tests/unit/ingestion/test_dispatch_edges.py b/tests/unit/ingestion/test_dispatch_edges.py
new file mode 100644
index 000000000..4400c2234
--- /dev/null
+++ b/tests/unit/ingestion/test_dispatch_edges.py
@@ -0,0 +1,337 @@
+"""Interface and override dispatch — both directions, end to end.
+
+Forward: a base method gains a ``dispatches_to`` edge to each same-named
+method a subtype declares, so a traversal that reaches the base reaches the
+code that runs.
+
+Reverse: a call the caller's own class cannot answer is looked for on its
+ancestors, for an explicit ``self``/``this`` receiver and for the implicit
+receiver of a bare call.
+
+The tests weigh toward the refusals. A walk that links a base to an unrelated
+same-named method is worse than one that links nothing.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.dispatch_edges import resolve_override_dispatch
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _build(tmp_path: Path, sources: dict[str, str], language: str):
+ builder = GraphBuilder(tmp_path)
+ for rel, text in sources.items():
+ abs_path = tmp_path / rel
+ abs_path.parent.mkdir(parents=True, exist_ok=True)
+ abs_path.write_text(text, encoding="utf-8")
+ info = FileInfo(
+ path=rel,
+ abs_path=str(abs_path),
+ language=language,
+ size_bytes=len(text),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ builder.add_file(_PARSER.parse_file(info, text.encode("utf-8")))
+ return builder.build()
+
+
+def _dispatch_pairs(graph) -> set[tuple[str, str]]:
+ return {
+ (u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "dispatches_to"
+ }
+
+
+def _calls_by_origin(graph, origin: str) -> set[tuple[str, str]]:
+ return {
+ (u, v)
+ for u, v, d in graph.edges(data=True)
+ if d.get("edge_type") == "calls" and d.get("resolution_origin") == origin
+ }
+
+
+_PY_HIERARCHY = {
+ "base.py": (
+ "class Handler:\n"
+ " def handle(self):\n"
+ " return self.finish()\n"
+ " def finish(self):\n"
+ " return 1\n"
+ ),
+ "impl.py": (
+ "from base import Handler\n\n\n"
+ "class JsonHandler(Handler):\n"
+ " def handle(self):\n"
+ " return 2\n"
+ ),
+}
+
+
+def test_a_subtype_method_answers_for_the_base_it_overrides(tmp_path: Path) -> None:
+ graph = _build(tmp_path, _PY_HIERARCHY, "python")
+ assert ("base.py::Handler::handle", "impl.py::JsonHandler::handle") in _dispatch_pairs(graph)
+
+
+def test_a_base_method_no_subtype_declares_gains_nothing(tmp_path: Path) -> None:
+ graph = _build(tmp_path, _PY_HIERARCHY, "python")
+ assert not [
+ pair for pair in _dispatch_pairs(graph) if pair[0].endswith("Handler::finish")
+ ]
+
+
+def test_two_classes_sharing_a_method_name_but_no_heritage_are_not_linked(
+ tmp_path: Path,
+) -> None:
+ graph = _build(
+ tmp_path,
+ {
+ "a.py": "class Alpha:\n def run(self):\n return 1\n",
+ "b.py": "class Beta:\n def run(self):\n return 2\n",
+ },
+ "python",
+ )
+ assert not _dispatch_pairs(graph)
+
+
+def test_a_constructor_is_never_a_dispatch_target(tmp_path: Path) -> None:
+ """Calling the base's ``__init__`` runs the base's, never the subtype's."""
+ graph = _build(
+ tmp_path,
+ {
+ "base.py": "class Base:\n def __init__(self):\n self.x = 1\n",
+ "impl.py": (
+ "from base import Base\n\n\n"
+ "class Child(Base):\n"
+ " def __init__(self):\n"
+ " self.x = 2\n"
+ ),
+ },
+ "python",
+ )
+ assert not _dispatch_pairs(graph)
+
+
+def test_a_grandchild_answers_for_the_root_it_never_names(tmp_path: Path) -> None:
+ graph = _build(
+ tmp_path,
+ {
+ "a.py": "class Root:\n def run(self):\n return 0\n",
+ "b.py": "from a import Root\n\n\nclass Mid(Root):\n pass\n",
+ "c.py": "from b import Mid\n\n\nclass Leaf(Mid):\n def run(self):\n return 1\n",
+ },
+ "python",
+ )
+ assert ("a.py::Root::run", "c.py::Leaf::run") in _dispatch_pairs(graph)
+
+
+def test_an_unregistered_language_gains_no_dispatch_edges(tmp_path: Path) -> None:
+ graph = _build(tmp_path, _PY_HIERARCHY, "python")
+ assert resolve_override_dispatch(graph, languages=frozenset()) == 0
+
+
+def test_a_base_with_more_implementations_than_the_cap_is_refused_whole(
+ tmp_path: Path,
+) -> None:
+ sources = {"base.py": "class Base:\n def run(self):\n return 0\n"}
+ for n in range(4):
+ sources[f"i{n}.py"] = (
+ f"from base import Base\n\n\nclass Impl{n}(Base):\n def run(self):\n return {n}\n"
+ )
+ graph = _build(tmp_path, sources, "python")
+ before = len(_dispatch_pairs(graph))
+ assert before == 4
+ for u, v in list(_dispatch_pairs(graph)):
+ graph.remove_edge(u, v)
+ assert resolve_override_dispatch(graph, max_implementations=3) == 0
+
+
+def test_a_private_implementation_overrides_nothing(tmp_path: Path) -> None:
+ """Four of six wrong C# edges were a `private` test helper sharing a name
+ with a `virtual` base. Private is not dispatched to."""
+ graph = _build(
+ tmp_path,
+ {
+ "Base.cs": (
+ "namespace App;\n\npublic class Base\n{\n"
+ " public virtual void Run() { }\n}\n"
+ ),
+ "Child.cs": (
+ "namespace App;\n\npublic class Child : Base\n{\n"
+ " private void Run(int times) { }\n}\n"
+ ),
+ },
+ "csharp",
+ )
+ assert not _dispatch_pairs(graph)
+
+
+def test_a_private_python_method_is_still_a_dispatch_target(tmp_path: Path) -> None:
+ """Python has no enforced private, so the same refusal there would drop
+ real overrides."""
+ graph = _build(
+ tmp_path,
+ {
+ "base.py": "class Base:\n def _run(self):\n return 0\n",
+ "impl.py": (
+ "from base import Base\n\n\nclass Child(Base):\n def _run(self):\n return 1\n"
+ ),
+ },
+ "python",
+ )
+ assert ("base.py::Base::_run", "impl.py::Child::_run") in _dispatch_pairs(graph)
+
+
+# --------------------------------------------------------------------------
+# Reverse: the call the caller's own class cannot answer
+# --------------------------------------------------------------------------
+
+
+def test_a_self_call_reaches_a_method_the_base_declares(tmp_path: Path) -> None:
+ graph = _build(
+ tmp_path,
+ {
+ "base.py": "class Base:\n def helper(self):\n return 1\n",
+ "impl.py": (
+ "from base import Base\n\n\n"
+ "class Child(Base):\n"
+ " def run(self):\n"
+ " return self.helper()\n"
+ ),
+ },
+ "python",
+ )
+ assert ("impl.py::Child::run", "base.py::Base::helper") in _calls_by_origin(
+ graph, "self_inherited"
+ )
+
+
+def test_two_ancestors_declaring_the_name_resolve_to_neither(tmp_path: Path) -> None:
+ """Ambiguity is terminal: guessing a branch mints an edge to a class the
+ call may never reach."""
+ graph = _build(
+ tmp_path,
+ {
+ "l.py": "class Left:\n def helper(self):\n return 1\n",
+ "r.py": "class Right:\n def helper(self):\n return 2\n",
+ "impl.py": (
+ "from l import Left\n"
+ "from r import Right\n\n\n"
+ "class Child(Left, Right):\n"
+ " def run(self):\n"
+ " return self.helper()\n"
+ ),
+ },
+ "python",
+ )
+ assert not _calls_by_origin(graph, "self_inherited")
+
+
+def test_a_self_call_the_caller_own_class_declares_keeps_its_own_origin(
+ tmp_path: Path,
+) -> None:
+ """The inherited tier is asked last, so it cannot displace ``self_scope``."""
+ graph = _build(
+ tmp_path,
+ {
+ "base.py": "class Base:\n def helper(self):\n return 1\n",
+ "impl.py": (
+ "from base import Base\n\n\n"
+ "class Child(Base):\n"
+ " def helper(self):\n"
+ " return 3\n"
+ " def run(self):\n"
+ " return self.helper()\n"
+ ),
+ },
+ "python",
+ )
+ assert not _calls_by_origin(graph, "self_inherited")
+ assert ("impl.py::Child::run", "impl.py::Child::helper") in _calls_by_origin(
+ graph, "self_scope"
+ )
+
+
+def test_a_recursive_self_call_does_not_fall_through_to_an_ancestor(
+ tmp_path: Path,
+) -> None:
+ """Strategy 3 refuses to point a call at its own symbol. Without this
+ guard that refusal reached the base's declaration of the same name, which
+ the call never runs."""
+ graph = _build(
+ tmp_path,
+ {
+ "base.py": "class Base:\n def run(self):\n return 0\n",
+ "impl.py": (
+ "from base import Base\n\n\n"
+ "class Child(Base):\n"
+ " def run(self, n):\n"
+ " return self.run(n - 1) if n else 0\n"
+ ),
+ },
+ "python",
+ )
+ assert not _calls_by_origin(graph, "self_inherited")
+
+
+def test_a_bare_call_reaches_an_inherited_method_in_an_implicit_receiver_language(
+ tmp_path: Path,
+) -> None:
+ # Two hops, so the file declaring helper is not one the caller imports —
+ # where it is, the merged-import tier answers first. A decoy declares the
+ # same name so the global-unique guess cannot answer either. Those are the
+ # conditions under which the real population misses at all.
+ graph = _build(
+ tmp_path,
+ {
+ "base/Base.kt": (
+ "package app.base\n\nopen class Base {\n fun helper(): Int = 1\n}\n"
+ ),
+ "mid/Mid.kt": (
+ "package app.mid\n\nimport app.base.Base\n\nopen class Mid : Base()\n"
+ ),
+ "web/Child.kt": (
+ "package app.web\n\n"
+ "import app.mid.Mid\n\n"
+ "class Child : Mid() {\n"
+ " fun run(): Int = helper()\n"
+ "}\n"
+ ),
+ "other/Decoy.kt": (
+ "package app.other\n\nclass Decoy {\n fun helper(): Int = 9\n}\n"
+ ),
+ },
+ "kotlin",
+ )
+ assert ("web/Child.kt::Child::run", "base/Base.kt::Base::helper") in _calls_by_origin(
+ graph, "enclosing_inherited"
+ )
+
+
+def test_a_python_bare_call_is_not_read_as_an_implicit_receiver(tmp_path: Path) -> None:
+ """Python spells the receiver, so a bare ``helper()`` is a free function
+ and binding it to the class hierarchy would be wrong."""
+ graph = _build(
+ tmp_path,
+ {
+ "base.py": "class Base:\n def helper(self):\n return 1\n",
+ "impl.py": (
+ "from base import Base\n\n\n"
+ "class Child(Base):\n"
+ " def run(self):\n"
+ " return helper()\n"
+ ),
+ },
+ "python",
+ )
+ assert not _calls_by_origin(graph, "enclosing_inherited")