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): draw a self edge for bare and self-receiver recursion (#4824)

Swati Ahuja7b651c430470
diff --git a/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py b/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py
index e2a674fde..b9ddf1e65 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py
@@ -466,11 +466,11 @@ def unsatisfied_prop_guard(
def _use_predecessors(graph: Any, node: str) -> list[str]:
- """Predecessors of *node* over a reachability-use edge."""
+ """Predecessors of *node* over a reachability-use edge, a recursive self-use aside."""
return [
pred
for pred in graph.predecessors(node)
- if graph[pred][node].get("edge_type") in REACHABILITY_USE_EDGE_TYPES
+ if pred != node and graph[pred][node].get("edge_type") in REACHABILITY_USE_EDGE_TYPES
]
diff --git a/packages/core/src/repowise/core/analysis/execution_flows.py b/packages/core/src/repowise/core/analysis/execution_flows.py
index d84e93a73..e0efa9cb5 100644
--- a/packages/core/src/repowise/core/analysis/execution_flows.py
+++ b/packages/core/src/repowise/core/analysis/execution_flows.py
@@ -170,7 +170,8 @@ def _build_call_degree_maps(
out_deg: dict[str, int] = defaultdict(int)
in_deg: dict[str, int] = defaultdict(int)
for u, v, d in graph.edges(data=True):
- if is_walkable_execution_edge(
+ # A recursive call is no caller: it must not lower an entry point's score.
+ if u != v and is_walkable_execution_edge(
d.get("edge_type"), d.get("resolution_origin"), d.get("confidence")
):
out_deg[u] += 1
diff --git a/packages/core/src/repowise/core/analysis/execution_graph.py b/packages/core/src/repowise/core/analysis/execution_graph.py
index f01db7195..8afbe3527 100644
--- a/packages/core/src/repowise/core/analysis/execution_graph.py
+++ b/packages/core/src/repowise/core/analysis/execution_graph.py
@@ -300,7 +300,8 @@ class ExecutionGraphIndex:
if edge_type == "defines":
_append_unique(declares, source, target, declaration_seen)
return
- if not is_reliable_execution_edge(edge_type, origin):
+ # Recursion reaches nothing new and must not count as a caller.
+ if source == target or not is_reliable_execution_edge(edge_type, origin):
return
_append_unique(forward, source, target, forward_seen)
_append_unique(reverse, target, source, reverse_seen)
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 35cc94cd8..66cf49cfc 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -391,7 +391,8 @@ class LanguageStrategiesMixin:
sym_id = candidates[0][1]
else:
return None
- if sym_id == caller_id:
+ # The qualifier names the caller's own class: recursion, when nothing else answers to the id.
+ if self._refuses_recursion(sym_id, caller_id, call):
return None
return ResolvedCall(caller_id, sym_id, 0.93, call.line, "scoped_name")
diff --git a/packages/core/src/repowise/core/ingestion/call_overload_selection.py b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
index 3deb75c3b..7fc396095 100644
--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py
+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
@@ -383,6 +383,19 @@ def _kotlin_function_refusing(symbol: Symbol | None, argument_count: int | None)
return not _takes(symbol, argument_count)
+def _could_recurse(symbol: Symbol | None, argument_count: int | None) -> bool:
+ """Whether a call of *argument_count* arguments to *symbol*'s own name may be *symbol*.
+
+ Not where arity binds (Java, C#, C++, Kotlin) and *symbol* cannot take the
+ count: the call means another overload of the name, an inherited one.
+ """
+ if symbol is None or argument_count is None:
+ return True
+ if symbol.language == "kotlin":
+ return not _kotlin_function_refusing(symbol, argument_count)
+ return symbol.language not in ("java", "csharp", "cpp") or _takes(symbol, argument_count)
+
+
def _takes(symbol: Symbol, argument_count: int) -> bool:
"""Whether *symbol*'s parameters admit *argument_count*; an unread signature does."""
admitted = signature_parameter_range(symbol.signature or "", symbol.language)
@@ -565,21 +578,48 @@ class OverloadSelectionMixin:
variants = self._variant_siblings.get(resolved.callee_id, (resolved.callee_id,))
return (resolved.caller_id,) if resolved.caller_id in variants else variants
+ def _refuses_recursion(self, sym_id: str | None, caller_id: str, call: CallSite) -> bool:
+ """Is *sym_id* the caller itself, with nothing to prove the call recursion?
+
+ Proof is a function that alone answers to its id and can take the
+ arguments. Otherwise the call may mean a twin of the id (an explicit
+ interface member, a generic or trait overload) or an inherited
+ overload, so an own-scope tier declines it as it always has.
+ """
+ if sym_id != caller_id:
+ return False
+ caller = self._symbols_by_id.get(caller_id)
+ return (
+ caller is None
+ or caller.kind not in _FUNCTION_KINDS
+ or caller_id in self._shared_ids
+ or not _could_recurse(caller, call.argument_count)
+ )
+
def _narrow_overload(self, resolved: ResolvedCall, call: CallSite) -> ResolvedCall | None:
"""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 (``_overload_target``). An overload calling itself is
- recursion, which draws no edge.
+ a member is chosen (``_overload_target``). Landing on the caller is
+ recursion only when the arguments pick it and the site reads as a call
+ to itself; a fallback onto it is no edge.
"""
rep = self._overload_rep.get(resolved.callee_id)
if rep is None:
return self._inherited_overload(resolved, call)
target = self._overload_target(rep, call.argument_count, call.argument_types)
- if target == resolved.caller_id:
+ if target == resolved.caller_id and not self._picks_itself(rep, target, call):
return None
return resolved if target == resolved.callee_id else replace(resolved, callee_id=target)
+ def _picks_itself(self, rep: str, caller_id: str, call: CallSite) -> bool:
+ """Do the arguments pick the caller from its own set, at a site that reads as recursion?"""
+ if caller_id != self._pick_overload(rep, call.argument_count, call.argument_types):
+ return False
+ if self._refuses_recursion(caller_id, caller_id, call):
+ return False
+ return self._site_shows_recursion(call)
+
def _inherited_overload(self, resolved: ResolvedCall, call: CallSite) -> ResolvedCall | None:
"""A Java callee that cannot take the call's arguments yields to an inherited overload.
@@ -936,6 +976,7 @@ class OverloadSelectionMixin:
The tiers answer such a call with the set's representative, which is
refused as recursion when the caller is that representative itself.
+ The caller itself is left to the tiers, which judge its site.
"""
caller_id = call.caller_symbol_id or ""
rep = self._overload_rep.get(caller_id)
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
index ed7671387..41b56056a 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
@@ -865,7 +865,7 @@ class ReceiverTypingMixin(
_, class_id, tier = found
sym_id = self._declares(class_id, call.target_name)
- if sym_id is None or sym_id == caller_id:
+ if sym_id is None or self._refuses_recursion(sym_id, caller_id, call):
return None
if tier == "same_file":
return ResolvedCall(caller_id, sym_id, 0.93, call.line, "receiver_chain_same_file")
@@ -1480,8 +1480,9 @@ class ReceiverTypingMixin(
"""
if self._symbols_by_id[type_id].language != "go":
return self._class_typed_call(file_path, call, caller_id, type_id)
+ # The type's own method is the target even when it is the caller (recursion).
hit = self._package_method(type_id, call.target_name)
- if hit is None or hit[1] == caller_id:
+ if hit is None or self._refuses_recursion(hit[1], caller_id, call):
return None
method_file, sym_id = hit
package = posixpath.dirname(self._symbol_paths_by_id[type_id])
@@ -1498,7 +1499,7 @@ class ReceiverTypingMixin(
) -> ResolvedCall | None:
"""``_call_typed_receiver`` for a class: no package tier."""
hit = self._located(file_path, self._declares(type_id, call.target_name))
- if hit is None or hit[1] == caller_id:
+ if hit is None or self._refuses_recursion(hit[1], caller_id, call):
return None
return self._body_typed_call(caller_id, hit[1], hit[2], call.line)
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index b4448491e..1e8343b8d 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -24,6 +24,7 @@ per strategy, and it is what the edge carries.
from __future__ import annotations
+import re
from collections import Counter, defaultdict
from dataclasses import replace
from pathlib import PurePosixPath
@@ -64,6 +65,7 @@ from .call_overload_selection import ( # noqa: F401
_ArgumentTypes,
_array_fit,
_closest_fit,
+ _could_recurse,
_java_method_refusing,
_kotlin_function_refusing,
_overload_phase,
@@ -387,6 +389,8 @@ class CallResolver(
for path, parsed in parsed_files.items()
for symbol in parsed.symbols
}
+ # Ids two definitions answer to; a call landing on one proves no recursion.
+ self._shared_ids = _shared_definition_ids(parsed_files)
self._overload_return_types = _overload_return_types(parsed_files)
self._known_type_names = frozenset(
symbol.name for symbol in self._symbols_by_id.values() if symbol.kind in _TYPE_KINDS
@@ -1516,8 +1520,10 @@ class CallResolver(
) -> tuple[bool, ResolvedCall | None]:
"""Tier 1, as ``(handled, edge)``: a handled None is a refusal."""
own = self._enclosing_class_method(file_path, call, caller_id)
+ # Own scope answers recursion, where the site proves it is recursion.
+ own_refused = own == caller_id and not self._is_bare_recursion(file_path, call, caller_id)
if self._is_anonymous_id(own):
- return True, _own_member_call(caller_id, own, call)
+ return True, None if own_refused else _own_member_call(caller_id, own, call)
# ``_file_symbols`` is flat and holds class members, but a JS/TS bare
# call can only name a top-level binding: a same-named method must not
# shadow an import (or hide a top-level function declared before it).
@@ -1530,14 +1536,93 @@ class CallResolver(
if callee_id is None:
return False, None
if own is not None and own != callee_id and _rivals_a_class_method(callee_id):
- if own == caller_id:
- # Recursion the flat index handed to a stranger. No edge.
+ # Own class first: the flat hit is a stranger.
+ if own_refused:
return True, None
return True, ResolvedCall(caller_id, own, 0.95, call.line, "enclosing_class")
- if callee_id != caller_id: # no self-recursion edges for now
+ if callee_id != caller_id or self._bare_name_reaches_caller(file_path, call, own):
return True, ResolvedCall(caller_id, callee_id, 0.95, call.line, "same_file")
+ # A method no bare name reaches here (Python, Go, Rust) is not this call's target.
return False, None
+ def _bare_name_reaches_caller(self, file_path: str, call: CallSite, own: str | None) -> bool:
+ """Is a bare call the flat index answers with its own caller recursion?
+
+ From the caller's own class scope, or when the caller is a top-level
+ function. Answered here, at the caller's own scope, so recursion never
+ falls through to an import, an ancestor or a repo-wide match.
+ """
+ caller_id = call.caller_symbol_id or ""
+ in_scope = own == caller_id or self._symbols_by_id[caller_id].parent_name is None
+ return in_scope and self._is_bare_recursion(file_path, call, caller_id)
+
+ def _is_bare_recursion(self, file_path: str, call: CallSite, caller_id: str) -> bool:
+ """Is a receiver-less call to the caller's own name recursion?
+
+ Only where the site is written bare: the parser can lose a receiver or
+ qualifier (``Outer.this.f()``, ``::f()``, ``a().f()``) that the source
+ line still shows. Not in Kotlin, where a lambda with a receiver
+ (``apply { f() }``) rebinds a bare name, nor past a Python import of the
+ name inside the caller. Ceiling: a bare site on a line that also
+ writes the name qualified is taken as written bare.
+ """
+ if self._refuses_recursion(caller_id, caller_id, call):
+ return False
+ if call.receiver_name or call.receiver_call is not None or call.scope_name:
+ return False
+ language = self._language_of(file_path) or ""
+ caller = self._symbols_by_id[caller_id]
+ lines = self._lines_of(file_path)
+ if self._language_rebinds(language, lines, caller, call):
+ return False
+ return _written_bare(lines, caller, call)
+
+ def _language_rebinds(
+ self, language: str, lines: list[str], caller: Symbol, call: CallSite
+ ) -> bool:
+ """Does *language* let the caller's own bare name mean something else here?
+
+ A Kotlin lambda with a receiver, a Python import inside the caller, a
+ C++ free function of the name in another namespace, a C# explicit
+ interface member (``IValidator.Validate(..)``), which has no bare name.
+ """
+ if language == "kotlin":
+ return True
+ if language == "python":
+ return _imports_name(lines, caller, call.target_name)
+ if language == "cpp":
+ return self._namespace_rival(caller, call)
+ if language == "csharp":
+ return _declared_explicitly(lines, caller, call.target_name)
+ return False
+
+ def _site_shows_recursion(self, call: CallSite) -> bool:
+ """Does a call whose arguments pick its own caller read as a call to itself?
+
+ Not on a chained receiver, and a receiver-less site only when written bare.
+ """
+ if call.receiver_call is not None:
+ return False
+ if call.receiver_name is not None:
+ return True
+ caller_id = call.caller_symbol_id or ""
+ file_path = self._symbol_paths_by_id.get(caller_id, "")
+ return self._is_bare_recursion(file_path, call, caller_id)
+
+ def _namespace_rival(self, caller: Symbol, call: CallSite) -> bool:
+ """Does another C++ free function of the caller's name take the call's arguments?
+
+ Namespaces are on no symbol, so ``detail::f`` and ``fmt::f`` look alike
+ and argument lookup may pick either: the call is no proof of recursion.
+ """
+ if caller.parent_name is not None:
+ return False
+ return any(
+ self._decl_to_def.get(sym_id, sym_id) != caller.id
+ and _free_function_taking(self._symbols_by_id.get(sym_id), call)
+ for sym_id in self._global_symbols.get(call.target_name, ())
+ )
+
def _is_anonymous_id(self, sym_id: str | None) -> bool:
"""Does *sym_id* name an anonymous class member?"""
return sym_id is not None and is_anonymous_member(self._symbols_by_id[sym_id])
@@ -1966,8 +2051,9 @@ class CallResolver(
sym_id = self._file_methods.get(file_path, {}).get(
(caller_class, call.target_name)
) or self._partial_fragment_member(file_path, caller_id, call.target_name)
- if sym_id is None or sym_id == caller_id:
+ if sym_id is None or self._refuses_recursion(sym_id, caller_id, call):
return None
+ # The caller itself is recursion, answered here so it never reaches an ancestor.
return ResolvedCall(caller_id, sym_id, 0.95, call.line, "self_scope")
def _is_self_receiver(self, file_path: str, receiver_name: str | None) -> bool:
@@ -2163,16 +2249,86 @@ def _index_bare_name(
top_level[sym.name] = index_id
-def _own_member_call(caller_id: str, own: str, call: CallSite) -> ResolvedCall | None:
+def _free_function_taking(symbol: Symbol | None, call: CallSite) -> bool:
+ """Is *symbol* a free function that can take *call*'s arguments?"""
+ if symbol is None or symbol.kind not in _FUNCTION_KINDS or symbol.parent_name is not None:
+ return False
+ return _could_recurse(symbol, call.argument_count)
+
+
+def _shared_definition_ids(parsed_files: dict[str, ParsedFile]) -> frozenset[str]:
+ """Ids more than one definition answers to (twins, generic or trait overloads)."""
+ defined = Counter(
+ symbol.id
+ for parsed in parsed_files.values()
+ for symbol in parsed.symbols
+ if not symbol.is_declaration
+ )
+ return frozenset(sym_id for sym_id, count in defined.items() if count > 1)
+
+
+def _own_member_call(caller_id: str, own: str, call: CallSite) -> ResolvedCall:
"""An anonymous class body's call to its own member *own*, before any flat name.
- A same-file top-level function of the name included. Recursion: no edge.
+ A same-file top-level function of the name included. *own* may be the
+ caller itself: recursion.
"""
- if own == caller_id:
- return None
return ResolvedCall(caller_id, own, 0.95, call.line, "same_file")
+def _name_pattern(name: str, *, call: bool) -> re.Pattern[str]:
+ """*name* as a word, followed by its argument list (generics allowed) when *call*."""
+ tail = r"\s*(?:<[^<>()]*>\s*)?\(" if call else ""
+ return re.compile(rf"\b{re.escape(name)}\b{tail}")
+
+
+def _written_bare(lines: list[str], caller: Symbol, call: CallSite) -> bool:
+ """Does *call*'s line call its name with no receiver or qualifier before it?
+
+ The caller's own declaration names it too and is not a call: the first
+ line from the caller's start that names it holds the declaration.
+ """
+ if not 0 < call.line <= len(lines):
+ return False
+ pattern = _name_pattern(call.target_name, call=True)
+ text = lines[call.line - 1]
+ found = list(pattern.finditer(text))
+ declaration_line = next(
+ (i + 1 for i in range(caller.start_line - 1, call.line) if pattern.search(lines[i])),
+ None,
+ )
+ if declaration_line == call.line:
+ found = found[1:]
+ return any(_unqualified(text[: m.start()]) for m in found)
+
+
+# An all-caps macro around a call (``FMT_POSIX_CALL(dup(fd))``) may rewrite it,
+# typically into ``::dup``.
+_MACRO_OPENING = re.compile(r"\b[A-Z][A-Z0-9_]+\s*\([^()]*$")
+
+
+def _unqualified(before: str) -> bool:
+ """Is a name preceded by *before* written with no receiver, qualifier or macro around it?"""
+ return not before.rstrip().endswith((".", "::", "->")) and not _MACRO_OPENING.search(before)
+
+
+def _declared_explicitly(lines: list[str], caller: Symbol, name: str) -> bool:
+ """Is the caller declared under a qualified name, ``Owner.name(``?"""
+ pattern = _name_pattern(name, call=True)
+ for line in lines[caller.start_line - 1 : caller.end_line]:
+ found = pattern.search(line)
+ if found is not None:
+ return line[: found.start()].rstrip().endswith(".")
+ return False
+
+
+def _imports_name(lines: list[str], caller: Symbol, name: str) -> bool:
+ """Does the caller's body import *name* (``from m import name``), shadowing itself?"""
+ pattern = _name_pattern(name, call=False)
+ body = lines[caller.start_line : caller.end_line]
+ return any("import" in line.split() and pattern.search(line) for line in body)
+
+
def _rivals_a_class_method(symbol_id: str) -> bool:
"""Another class's ordinary method — the one shape that proves last-wins.
diff --git a/tests/unit/analysis/test_execution_graph.py b/tests/unit/analysis/test_execution_graph.py
index ba8abfa90..1d5be6c6d 100644
--- a/tests/unit/analysis/test_execution_graph.py
+++ b/tests/unit/analysis/test_execution_graph.py
@@ -64,6 +64,17 @@ def test_index_builds_all_views_in_one_pass_and_deduplicates_edges():
)
+def test_recursion_is_no_caller_of_itself():
+ graph = nx.MultiDiGraph()
+ _symbol(graph, "a.py::fact", "a.py", "fact", 1, 3)
+ graph.add_edge("a.py::fact", "a.py::fact", edge_type="calls", call_lines=[2])
+
+ index = ExecutionGraphIndex(graph)
+
+ assert "a.py::fact" not in index.forward
+ assert index.in_degree.get("a.py::fact", 0) == 0
+
+
def test_definition_lookup_prefers_exact_then_innermost_range():
graph = nx.DiGraph()
_symbol(graph, "a.py::outer", "a.py", "outer", 2, 20)
diff --git a/tests/unit/ingestion/test_bare_recursion_self_edges.py b/tests/unit/ingestion/test_bare_recursion_self_edges.py
new file mode 100644
index 000000000..2f0298970
--- /dev/null
+++ b/tests/unit/ingestion/test_bare_recursion_self_edges.py
@@ -0,0 +1,297 @@
+"""A bare or self-receiver recursive call is a self edge, answered in the caller's own scope.
+
+Answering it there is what keeps recursion from falling through to an import,
+an ancestor or another class's method of the same name.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+_PARSER = ASTParser()
+
+
+def _edges(tmp_path: Path, language: str, rel: str, text: str) -> set[tuple[str, str]]:
+ path = tmp_path / rel
+ path.write_text(text, encoding="utf-8")
+ info = FileInfo(
+ path=rel,
+ abs_path=str(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,
+ )
+ parsed = _PARSER.parse_file(info, text.encode("utf-8"))
+ resolver = CallResolver({rel: parsed}, {rel: set()}, repo_path=str(tmp_path))
+ return {(rc.caller_id, rc.callee_id) for rc in resolver.resolve_file(rel, parsed.calls)}
+
+
+SELF_CASES = [
+ ("python", "m.py", "def fact(n):\n return n * fact(n - 1) if n else 1\n", "m.py::fact"),
+ (
+ "python",
+ "m.py",
+ "class C:\n def walk(self, n):\n return self.walk(n - 1) if n else 0\n",
+ "m.py::C::walk",
+ ),
+ (
+ "python",
+ "m.py",
+ "class Node:\n def __init__(self):\n self.next: Node = None\n"
+ " def walk(self):\n return self.next.walk()\n",
+ "m.py::Node::walk",
+ ),
+ (
+ "java",
+ "A.java",
+ "class A {\n int walk(int n) { return n == 0 ? 0 : walk(n - 1); }\n}\n"
+ "class B {\n int walk(int n) { return 1; }\n}\n",
+ "A.java::A::walk",
+ ),
+ (
+ "java",
+ "A.java",
+ "class A {\n int walk(int n) { return n == 0 ? 0 : this.walk(n - 1); }\n}\n",
+ "A.java::A::walk",
+ ),
+ (
+ "csharp",
+ "A.cs",
+ "class A {\n int Walk(int n) { return n == 0 ? 0 : Walk(n - 1); }\n}\n",
+ "A.cs::A::Walk",
+ ),
+ ("c", "m.c", "int fact(int n) { return n ? n * fact(n - 1) : 1; }\n", "m.c::fact"),
+ (
+ "cpp",
+ "m.cpp",
+ "class S {\npublic:\n int walk(int n) { return n ? walk(n - 1) : 0; }\n};\n",
+ "m.cpp::S::walk",
+ ),
+ (
+ "kotlin",
+ "A.kt",
+ "class A {\n fun walk(n: Int): Int = if (n == 0) 0 else this.walk(n - 1)\n}\n",
+ "A.kt::A::walk",
+ ),
+ (
+ "cpp",
+ "m.cpp",
+ "class S {\npublic:\n int walk(int n);\n};\nint S::walk(int n) { return n ? walk(n - 1) : 0; }\n",
+ "m.cpp::S::walk",
+ ),
+ (
+ "rust",
+ "lib.rs",
+ "pub struct T;\nimpl T {\n"
+ " pub fn walk(&self, n: u32) -> u32 { if n == 0 { 0 } else { self.walk(n - 1) } }\n}\n",
+ "lib.rs::T::walk",
+ ),
+ (
+ "go",
+ "m.go",
+ "package m\n\nfunc fact(n int) int {\n\tif n == 0 {\n\t\treturn 1\n\t}\n"
+ "\treturn n * fact(n-1)\n}\n",
+ "m.go::fact",
+ ),
+]
+
+
+ ("language", "rel", "text", "symbol"),
+ SELF_CASES,
+ ids=[f"{case[0]}-{i}" for i, case in enumerate(SELF_CASES)],
+)
+def test_a_recursive_call_is_a_self_edge(
+ tmp_path: Path, language: str, rel: str, text: str, symbol: str
+) -> None:
+ assert _edges(tmp_path, language, rel, text) == {(symbol, symbol)}
+
+
+def test_a_python_bare_call_never_reaches_the_method_calling_it(tmp_path: Path) -> None:
+ # A bare name inside a Python method is a module or builtin name, never the method.
+ text = "class C:\n def walk(self, n):\n return walk(n)\n"
+ assert _edges(tmp_path, "python", "m.py", text) == set()
+
+
+def test_an_overload_of_another_arity_is_not_recursion(tmp_path: Path) -> None:
+ text = (
+ "class A {\n int f(int n) { return f(n, 1); }\n"
+ " int f(int n, int m) { return f(n); }\n}\n"
+ )
+ assert _edges(tmp_path, "java", "A.java", text) == {
+ ("A.java::A::f#1", "A.java::A::f#2"),
+ ("A.java::A::f#2", "A.java::A::f#1"),
+ }
+
+
+def test_an_overload_its_arguments_pick_is_recursion(tmp_path: Path) -> None:
+ text = "class A {\n int f(int n) { return f(n - 1); }\n int f(int n, int m) { return n; }\n}\n"
+ assert _edges(tmp_path, "java", "A.java", text) == {("A.java::A::f#1", "A.java::A::f#1")}
+
+
+ ("language", "rel", "text"),
+ [
+ ("csharp", "A.cs", "class A : B {\n int F(int a, int b) { return F(a); }\n}\n"),
+ ("java", "A.java", "class A extends B {\n int f(int a, int b) { return this.f(a); }\n}\n"),
+ ],
+ ids=["csharp", "java"],
+)
+def test_a_self_call_its_parameters_cannot_take_is_no_self_edge(
+ tmp_path: Path, language: str, rel: str, text: str
+) -> None:
+ # F(a) inside F(a, b) means an inherited F, never the caller.
+ assert not any(caller == callee for caller, callee in _edges(tmp_path, language, rel, text))
+
+
+NOT_RECURSION = [
+ # The parser drops the receiver of `Outer.this.f()`; the line still shows it.
+ (
+ "java",
+ "A.java",
+ "class A {\n void clear() { }\n class Keys {\n"
+ " public void clear() {\n A.this.clear();\n }\n }\n}\n",
+ ),
+ # A chained receiver: `count` here is the iterator's.
+ ("rust", "lib.rs", "fn count(b: &[u8]) -> usize {\n b.iter().count()\n}\n"),
+ # An explicit interface member shares its id with the public method it calls.
+ (
+ "csharp",
+ "A.cs",
+ "class A : IEnumerable {\n public IEnumerator<int> GetEnumerator() { return null; }\n"
+ " IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }\n}\n",
+ ),
+ # An overload picked by arity, called on a chained receiver.
+ (
+ "java",
+ "A.java",
+ "class A {\n A first() { return this; }\n String val() { return first().val(); }\n"
+ " A val(String v) { return this; }\n}\n",
+ ),
+ # Namespaces are on no symbol: the bare `f` may be `detail::f`.
+ (
+ "cpp",
+ "m.cpp",
+ "namespace detail {\nint f(int n) { return n; }\n}\n"
+ "namespace api {\nint f(int n) { return f(n); }\n}\n",
+ ),
+ # An explicit interface member has no bare name: the call is the public overload's.
+ (
+ "csharp",
+ "A.cs",
+ "class A : IV {\n public int Run(T x, int n = 0) { return n; }\n"
+ " int IV.Run(object x, int n) { return Run(Wrap(x), n); }\n}\n",
+ ),
+ # A macro around the call may rewrite it, here into the POSIX `::dup`.
+ (
+ "cpp",
+ "m.cpp",
+ "class file {\npublic:\n int dup(int fd);\n};\n"
+ "int file::dup(int fd) {\n return FMT_POSIX_CALL(dup(fd));\n}\n",
+ ),
+ # A lambda with a receiver rebinds a bare Kotlin name.
+ ("kotlin", "A.kt", "fun main() {\n App().apply { main() }\n}\n"),
+ # A function-local import shadows the function's own name.
+ (
+ "python",
+ "m.py",
+ "def pager():\n from other import pager\n\n return pager()\n",
+ ),
+]
+
+
+ ("language", "rel", "text"),
+ NOT_RECURSION,
+ ids=[f"{case[0]}-{i}" for i, case in enumerate(NOT_RECURSION)],
+)
+def test_a_call_that_only_looks_recursive_draws_no_self_edge(
+ tmp_path: Path, language: str, rel: str, text: str
+) -> None:
+ assert not any(caller == callee for caller, callee in _edges(tmp_path, language, rel, text))
+
+
+def test_a_method_shadows_a_same_named_top_level_function(tmp_path: Path) -> None:
+ text = (
+ "int walk(int n) { return n; }\n"
+ "class S {\npublic:\n int walk(int n) { return n ? walk(n - 1) : 0; }\n};\n"
+ )
+ assert _edges(tmp_path, "cpp", "m.cpp", text) == {("m.cpp::S::walk", "m.cpp::S::walk")}
+
+
+def test_an_anonymous_class_member_refuses_a_call_its_parameters_cannot_take(
+ tmp_path: Path,
+) -> None:
+ # f(a) inside f(a, b) of an anonymous body is no self edge, and no other edge either.
+ text = "class A {\n Object o = new Object() {\n int f(int a, int b) { return f(a); }\n };\n}\n"
+ assert _edges(tmp_path, "java", "A.java", text) == set()
+
+
+def test_an_anonymous_class_member_recursion_is_a_self_edge(tmp_path: Path) -> None:
+ text = "class A {\n Object o = new Object() {\n int f(int a) { return f(a - 1); }\n };\n}\n"
+ member = "A.java::A::o::Object::f"
+ assert _edges(tmp_path, "java", "A.java", text) == {(member, member)}
+
+
+def test_a_caller_id_two_definitions_share_draws_no_self_edge(tmp_path: Path) -> None:
+ # Which of the two the call means is unproven, so the shared id is not recursion.
+ text = "def fact(n):\n return fact(n - 1)\n\ndef fact(n):\n return fact(n - 1)\n"
+ assert _edges(tmp_path, "python", "m.py", text) == set()
+
+
+def test_a_caller_id_one_definition_holds_draws_a_self_edge(tmp_path: Path) -> None:
+ text = "def fact(n):\n return fact(n - 1)\n"
+ assert _edges(tmp_path, "python", "m.py", text) == {("m.py::fact", "m.py::fact")}
+
+
+def _shared_ids(tmp_path: Path, language: str, rel: str, text: str) -> frozenset[str]:
+ from repowise.core.ingestion.call_resolver import _shared_definition_ids
+
+ (tmp_path / rel).write_text(text, encoding="utf-8")
+ info = FileInfo(
+ path=rel,
+ abs_path=str(tmp_path / rel),
+ 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,
+ )
+ return _shared_definition_ids({rel: _PARSER.parse_file(info, text.encode("utf-8"))})
+
+
+def test_a_declaration_twin_of_one_definition_does_not_share_the_id(tmp_path: Path) -> None:
+ text = "class S {\npublic:\n int walk(int n);\n};\nint S::walk(int n) { return n ? walk(n - 1) : 0; }\n"
+ assert _shared_ids(tmp_path, "cpp", "m.cpp", text) == frozenset()
+ # The one definition still draws its self edge.
+ assert _edges(tmp_path, "cpp", "m.cpp", text) == {("m.cpp::S::walk", "m.cpp::S::walk")}
+
+
+def test_two_definitions_of_one_id_are_shared(tmp_path: Path) -> None:
+ text = "def fact(n):\n return fact(n - 1)\n\ndef fact(n):\n return fact(n - 1)\n"
+ assert _shared_ids(tmp_path, "python", "m.py", text) == frozenset({"m.py::fact"})
+
+
+def test_an_overload_representative_calls_a_sibling_not_itself(tmp_path: Path) -> None:
+ # f#1 is the set's representative; its call has another arity, so it is no recursion.
+ text = (
+ "class A {\n int f(int a) { return f(a, 1, 2); }\n"
+ " int f(int a, int b) { return b; }\n"
+ " int f(int a, int b, int c) { return c; }\n}\n"
+ )
+ assert _edges(tmp_path, "java", "A.java", text) == {("A.java::A::f#1", "A.java::A::f#3")}
diff --git a/tests/unit/ingestion/test_cpp_this_calls.py b/tests/unit/ingestion/test_cpp_this_calls.py
index 306404a8a..810590a82 100644
--- a/tests/unit/ingestion/test_cpp_this_calls.py
+++ b/tests/unit/ingestion/test_cpp_this_calls.py
@@ -89,10 +89,10 @@ class TestOtherNestedReceiversUnchanged:
calls, _ = _parse_and_build(tmp_path)
assert not any(c.target_name == "Run" for c in calls)
- def test_a_this_call_to_the_caller_itself_draws_no_self_edge(self, tmp_path: Path) -> None:
+ def test_a_this_call_to_the_caller_itself_draws_a_self_edge(self, tmp_path: Path) -> None:
_write(tmp_path, "return this->step(n - 1);")
_, graph = _parse_and_build(tmp_path)
- assert not graph.has_edge("lib/s.cc::S::step", "lib/s.cc::S::step")
+ assert graph.has_edge("lib/s.cc::S::step", "lib/s.cc::S::step")
def test_a_plain_receiver_is_unchanged(self, tmp_path: Path) -> None:
_write(tmp_path, "s_->Run(1); return 0;")
diff --git a/tests/unit/ingestion/test_dispatch_edges.py b/tests/unit/ingestion/test_dispatch_edges.py
index cc03da251..e7571f666 100644
--- a/tests/unit/ingestion/test_dispatch_edges.py
+++ b/tests/unit/ingestion/test_dispatch_edges.py
@@ -267,9 +267,9 @@ def test_a_self_call_the_caller_own_class_declares_keeps_its_own_origin(
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."""
+ """Strategy 3 answers a call to its own symbol with a self edge, so the
+ call never reaches the base's declaration of the same name, which it
+ never runs."""
graph = _build(
tmp_path,
{
@@ -284,6 +284,7 @@ def test_a_recursive_self_call_does_not_fall_through_to_an_ancestor(
"python",
)
assert not _calls_by_origin(graph, "self_inherited")
+ assert ("impl.py::Child::run", "impl.py::Child::run") in _calls_by_origin(graph, "self_scope")
def test_a_bare_call_reaches_an_inherited_method_in_an_implicit_receiver_language(
diff --git a/tests/unit/ingestion/test_enclosing_class_calls.py b/tests/unit/ingestion/test_enclosing_class_calls.py
index eec74b390..f3efd3e67 100644
--- a/tests/unit/ingestion/test_enclosing_class_calls.py
+++ b/tests/unit/ingestion/test_enclosing_class_calls.py
@@ -148,10 +148,10 @@ class TestClassAwareTier:
assert hits[0][2:] == (0.95, "enclosing_class")
def test_recursion_does_not_reach_another_class(self, tmp_path: Path) -> None:
- """The caller's own class's `helper` IS the caller — that is a self-call."""
+ """The caller's own class's `helper` IS the caller: a self edge, never B's."""
parsed = _parse_all(tmp_path, {"src/A.java": ("java", JAVA_RECURSIVE)})
edges = _edges(parsed, tmp_path)
- assert _targets_of(edges, "::A::helper") == [], (
+ assert _targets_of(edges, "::A::helper") == ["src/A.java::A::helper"], (
f"recursive helper() must not edge to B::helper; edges: {edges}"
)