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(core): give each Java and C# overload its own symbol (#2811)

Raghav Chamadiya35acb47bcfbe
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/_text.py b/packages/core/src/repowise/core/analysis/actions/rules/_text.py
index b6d689057..a8372c06f 100644
--- a/packages/core/src/repowise/core/analysis/actions/rules/_text.py
+++ b/packages/core/src/repowise/core/analysis/actions/rules/_text.py
@@ -2,10 +2,19 @@
from __future__ import annotations
+import re
+
def code(text: str) -> str:
- """Mark a path or symbol for a mono renderer."""
- return f"`{text}`"
+ """Mark a path or symbol for a mono renderer.
+
+ A C# generic id carries a backtick (``IFoo`1``), so the span is fenced with
+ one more backtick than the longest run inside it.
+ """
+ if "`" not in text:
+ return f"`{text}`"
+ fence = "`" * (max(len(run) for run in re.findall(r"`+", text)) + 1)
+ return f"{fence} {text} {fence}"
def plural(n: int, noun: str) -> str:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 1f3d50dc7..3831249eb 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -24,6 +24,7 @@ import structlog
from ...entry_candidacy import is_reachability_root
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
+from ...ingestion.symbol_identity import base_symbol_id, overload_sets
from .constants import (
_CONTAINER_USE_LANGUAGES,
_DEAD_CODE_EXEMPT_LANGUAGES,
@@ -840,6 +841,8 @@ class DeadCodeAnalyzer:
# by _get_unsatisfied_prop_guard so each TSX/JSX file is read from
# disk and parsed by tree-sitter at most once per analysis run.
self._guard_cache: dict[str, list[tuple[str, str, str]]] = {}
+ # {base id: overload member ids}, built on first use.
+ self._overload_units: dict[str, list[str]] | None = None
def _reachability_rescues(self, whitelist: AbstractSet[str]) -> ReachabilityRescues:
"""Assemble the rescue state the shared predicate reads."""
@@ -1673,7 +1676,27 @@ class DeadCodeAnalyzer:
return findings
+ def _overload_unit(self, node: str) -> list[str]:
+ """The members of the overload set *node* belongs to or names, else ``[]``.
+
+ A plain id names its set when the set's members carry discriminators,
+ which is how a composed constructor id ``path::X::X`` still finds
+ ``X::X#0`` and ``X::X#2``.
+ """
+ if self._overload_units is None:
+ self._overload_units = overload_sets(
+ n for n in self.graph.nodes if isinstance(n, str)
+ )
+ return self._overload_units.get(base_symbol_id(node), [])
+
def _has_inbound_use(self, node: str) -> bool:
+ """Whether any reachability-use edge lands on *node* or its overload set."""
+ members = self._overload_unit(node)
+ if members:
+ return any(self._lands_on(member) for member in members)
+ return self._lands_on(node)
+
+ def _lands_on(self, node: str) -> bool:
"""Whether any reachability-use edge lands on *node* (False if absent)."""
if not self.graph.has_node(node):
return False
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
index 4c19351c4..33da777d3 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -40,6 +40,7 @@ from .languages.receiver_types import (
from .models import CallSite, ParsedFile, Symbol, symbol_id_language
from .resolved_call import ResolvedCall
from .return_types import declared_return_type, go_first_result
+from .symbol_identity import id_segment_name
from .type_names import POINTER_LIKE_MEMBERS, bare_type_name
# Which symbols own a class scope, and which of them swallow one. A class span
@@ -231,19 +232,39 @@ class ReceiverTypingMixin:
The scope is returned rather than an edge so that each caller stamps
its own origin literal, which is what keeps a field-typed edge separable
from a body-typed one after the build.
+
+ A C# generic spelling (``IFoo`1``) first asks for the type that carries
+ that arity in its id, which exists only beside a same-file ``IFoo``;
+ a repo-wide guess under it is not taken over the bare name's answer.
"""
+ bare = id_segment_name(type_name)
+ if bare != type_name:
+ found = self._typed_receiver_lookup(file_path, call, caller_id, type_name)
+ if found is not None and found[1] != "global":
+ return found
+ return self._typed_receiver_lookup(file_path, call, caller_id, bare)
+
+ def _typed_receiver_lookup(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ type_name: str,
+ ) -> tuple[str, str] | None:
key = (type_name, call.target_name)
+ # What an import binds is the written name, never its arity.
+ written = id_segment_name(type_name)
# An import statement binds the name outright, so it settles which type
# this is before any scope search.
- bound = self._import_names.get(file_path, {}).get(type_name)
+ bound = self._import_names.get(file_path, {}).get(written)
if bound is not None and not bound.startswith("external:"):
sym_id = self._import_bound_method(file_path, bound, key)
return None if sym_id is None else (sym_id, "import")
# Bound to something outside the repo: there is no edge to find,
# however many local classes share the simple name.
- if type_name in self._externally_bound_names(file_path):
+ if written in self._externally_bound_names(file_path):
return None
# The caller's own file first: a nested class here outranks a
@@ -510,6 +531,8 @@ class ReceiverTypingMixin:
or declared in *file_path* itself, and name exactly one type there:
no repo-wide guess, since every hop of a chain rests on this.
"""
+ # A chain hop asks for the type by its written name, arity aside.
+ type_name = id_segment_name(type_name)
bound = self._import_names.get(file_path, {}).get(type_name)
if bound is not None:
if bound.startswith("external:"):
@@ -577,7 +600,9 @@ class ReceiverTypingMixin:
) -> ResolvedCall | None:
if language != "csharp":
return None
- extension = self._extension_target(file_path, (type_name, call.target_name))
+ # Extensions are indexed by the type they name, written without arity.
+ key = (id_segment_name(type_name), call.target_name)
+ extension = self._extension_target(file_path, key)
if extension is None:
return None
return self._extension_typed_call(caller_id, *extension, 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 7c30ff503..15a0752b4 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -56,7 +56,13 @@ from .models import (
)
from .resolved_call import ResolvedCall
from .resolvers.cpp import _SOURCE_TU_EXTS
-from .return_types import declared_return_type, normalize_return_type, signature_parameter_count
+from .return_types import (
+ declared_return_type,
+ normalize_return_type,
+ signature_parameter_count,
+ signature_parameter_range,
+)
+from .symbol_identity import id_segment_name, split_symbol_id
from .type_names import (
csharp_extension_receiver,
is_resolvable_type_name,
@@ -77,8 +83,8 @@ _IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})
# absent because `java.scm`'s bare-call pattern also matches `this.field.m()`,
# which then arrives here indistinguishable from a real implicit receiver.
#
-# C# is present: a name's overloads all share one symbol id, so a declaration
-# line read back out of the graph may name another overload of the right id.
+# C# is present: the tier answers with a name's overload set, and
+# ``resolve_file`` narrows it to the member the argument count names.
_INHERITED_LANGUAGES = frozenset({"kotlin", "python", "typescript", "swift", "csharp"})
# Languages where a bare name is scoped lexically: it can only mean the
@@ -272,6 +278,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Global symbol index: {name: [symbol_ids]} — for Tier 3
self._global_symbols: dict[str, list[str]] = defaultdict(list)
+
+ # Overload sets whose members have their own ids. Every index above
+ # holds a set by its representative, the first declared member, so the
+ # tiers answer exactly as for one id and ``resolve_file`` narrows the
+ # answer by argument count: {member id: representative} and
+ # {representative: ((member id, (fewest, most) arguments), ...)}.
+ self._overload_rep: dict[str, str] = {}
+ self._overload_members: dict[str, tuple[tuple[str, tuple[int, int | None]], ...]] = {}
self._symbols_by_id = {
symbol.id: symbol for parsed in parsed_files.values() for symbol in parsed.symbols
}
@@ -457,9 +471,13 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
def _collapse_declarations(self, sym_ids: list[str]) -> set[str]:
"""Fold each declaration onto the definition it was paired with.
- Two ids naming one symbol must not read as an ambiguity.
+ Two ids naming one symbol must not read as an ambiguity, and neither
+ must the members of one overload set, which fold to its representative.
"""
- return {self._decl_to_def.get(sym_id, sym_id) for sym_id in sym_ids}
+ return {
+ self._overload_rep.get(target, target)
+ for target in (self._decl_to_def.get(sym_id, sym_id) for sym_id in sym_ids)
+ }
def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
"""Build symbol lookup indices from parsed file data.
@@ -492,11 +510,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""Index one file's symbols, collecting what is settled repo-wide later."""
file_syms: dict[str, str] = {}
file_methods: dict[tuple[str, str], str] = {}
+ representatives = self._index_overload_sets(parsed)
for sym in parsed.symbols:
+ # An overload set is indexed once, under its representative.
+ index_id = representatives.get(sym.id, sym.id)
decl_key = (sym.parent_name, sym.name)
if sym.is_declaration:
- declarations.append((path, sym.id, decl_key))
+ declarations.append((path, index_id, decl_key))
# A declaration must never displace a definition already
# indexed under this name — a .cpp that forward-declares a
# helper above its own body holds both.
@@ -506,23 +527,23 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# can legally reach a method. The (class, method) index
# below still takes it.
if sym.parent_name is None:
- file_syms.setdefault(sym.name, sym.id)
+ file_syms.setdefault(sym.name, index_id)
else:
- definitions[decl_key].append((path, sym.id))
+ definitions[decl_key].append((path, index_id))
# File-level symbol index (top-level symbols and methods)
- file_syms[sym.name] = sym.id
+ file_syms[sym.name] = index_id
# Method index: (class_name, method_name) → symbol_id
if sym.parent_name:
key = (sym.parent_name, sym.name)
- file_methods[key] = sym.id
- self._global_methods[key].append((path, sym.id))
+ file_methods[key] = index_id
+ self._global_methods[key].append((path, index_id))
extended = self._csharp_extended_type(sym)
if extended is not None:
- extensions[(extended, sym.name)].add((path, sym.id))
+ extensions[(extended, sym.name)].add((path, index_id))
- self._index_globally(path, sym)
+ self._index_globally(path, sym, index_id)
self._file_symbols[path] = file_syms
self._file_methods[path] = file_methods
@@ -536,16 +557,41 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return None
return extended if extended in self._csharp_type_names else None
- def _index_globally(self, path: str, sym: Symbol) -> None:
+ def _index_globally(self, path: str, sym: Symbol, index_id: str) -> None:
if _has_internal_linkage(path, sym):
- self._tu_local_ids.add(sym.id)
+ self._tu_local_ids.add(index_id)
if sym.kind in _NON_CALLABLE_KINDS:
- self._non_callable_ids.add(sym.id)
+ self._non_callable_ids.add(index_id)
if _is_property_accessor(sym):
- self._property_accessor_ids.add(sym.id)
+ self._property_accessor_ids.add(index_id)
# Same rule as the per-file index, for the global-unique tier.
if not (sym.is_declaration and sym.parent_name is not None):
- self._global_symbols[sym.name].append(sym.id)
+ self._global_symbols[sym.name].append(index_id)
+
+ def _index_overload_sets(self, parsed: ParsedFile) -> dict[str, str]:
+ """Record *parsed*'s overload sets; ``{member id: representative}``.
+
+ Only parameter-count members are narrowed: a build-variant member
+ (``#cfg(...)``) is not chosen by its arguments.
+ """
+ members: dict[str, list[Symbol]] = defaultdict(list)
+ for sym in parsed.symbols:
+ base, payload = split_symbol_id(sym.id)
+ if payload is not None and payload.isdigit():
+ members[base].append(sym)
+ representatives: dict[str, str] = {}
+ for overloads in members.values():
+ overloads.sort(key=lambda sym: sym.start_line)
+ rep = overloads[0].id
+ ranges: dict[str, tuple[int, int | None]] = {}
+ for sym in overloads:
+ representatives[sym.id] = rep
+ admitted = signature_parameter_range(sym.signature or "", sym.language)
+ if admitted is not None:
+ ranges.setdefault(sym.id, admitted)
+ self._overload_members[rep] = tuple(ranges.items())
+ self._overload_rep.update(representatives)
+ return representatives
def _index_extension_methods(
self, candidates: dict[tuple[str, str], set[tuple[str, str]]]
@@ -557,8 +603,8 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
costs an edge; guessing costs correctness.
An overload set is not this case -- every overload of one method in one
- class shares a symbol id. A ``partial`` class split across files is,
- and stays refused.
+ class is indexed under one representative id. A ``partial`` class split
+ across files is, and stays refused.
"""
for key, sites in candidates.items():
if len({sym_id for _, sym_id in sites}) != 1:
@@ -752,9 +798,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Module-level call — assign to synthetic __module__ symbol
call = replace(call, caller_symbol_id=f"{file_path}::__module__")
- resolved = self._resolve_one(file_path, call)
+ resolved = self._overload_sibling_call(call) or self._resolve_one(file_path, call)
+ if resolved:
+ resolved = self._narrow_overload(self._redirect_to_definition(resolved), call)
if resolved:
- resolved = self._redirect_to_definition(resolved)
# The edge type is a property of the call syntax, not of the
# tier that answered, so it is stamped once here.
if call.edge_type != "calls":
@@ -763,6 +810,58 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return results
+ 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. 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.
+ """
+ rep = self._overload_rep.get(resolved.callee_id)
+ if rep is None:
+ return resolved
+ target = self._pick_overload(rep, call.argument_count) or rep
+ if target == resolved.caller_id:
+ return None
+ return resolved if target == resolved.callee_id else replace(resolved, callee_id=target)
+
+ def _pick_overload(self, rep: str, argument_count: int | None) -> str | None:
+ """The one member of *rep*'s set a call with *argument_count* arguments means.
+
+ Asked in the order the languages apply: a member of exactly that arity,
+ then one whose defaults admit the count (Java's first phase, C#'s normal
+ 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), [])
+ return found[0] if len(found) == 1 else None
+
+ def _overload_sibling_call(self, call: CallSite) -> ResolvedCall | None:
+ """An overload calling another member of its own set, ``f(a)`` inside ``f(a, b)``.
+
+ The tiers answer such a call with the set's representative, which is
+ refused as recursion when the caller is that representative itself.
+ """
+ caller_id = call.caller_symbol_id or ""
+ rep = self._overload_rep.get(caller_id)
+ if rep is None or call.receiver_name not in (None, "this", "self"):
+ return None
+ if self._symbols_by_id[caller_id].name != call.target_name:
+ return None
+ target = self._pick_overload(rep, call.argument_count)
+ if target is None or target == caller_id:
+ return None
+ return ResolvedCall(caller_id, target, 0.95, call.line, "same_file")
+
def _resolve_one(self, file_path: str, call: CallSite) -> ResolvedCall | None:
"""Resolve a single CallSite through the three-tier fallback."""
caller_id = call.caller_symbol_id
@@ -1656,7 +1755,7 @@ def _rivals_a_class_method(symbol_id: str) -> bool:
its own ``Entry``.
"""
parts = symbol_id.split("::")
- return len(parts) >= 3 and parts[-1] != parts[-2]
+ return len(parts) >= 3 and id_segment_name(parts[-1]) != id_segment_name(parts[-2])
def _is_super_receiver(receiver: CallReceiver | None) -> bool:
diff --git a/packages/core/src/repowise/core/ingestion/dispatch_edges.py b/packages/core/src/repowise/core/ingestion/dispatch_edges.py
index b1f35d040..036df56ba 100644
--- a/packages/core/src/repowise/core/ingestion/dispatch_edges.py
+++ b/packages/core/src/repowise/core/ingestion/dispatch_edges.py
@@ -29,6 +29,7 @@ from collections import defaultdict
import structlog
from .heritage_resolver import heritage_ancestors
+from .symbol_identity import id_segment_name, symbol_id_discriminator
log = structlog.get_logger(__name__)
@@ -99,7 +100,14 @@ def _methods_by_name(graph, type_id: str) -> dict[str, list[str]]:
def _is_constructor(name: str, type_id: str) -> bool:
- return name in _CONSTRUCTOR_NAMES or name == type_id.rpartition("::")[2]
+ return name in _CONSTRUCTOR_NAMES or name == id_segment_name(type_id.rpartition("::")[2])
+
+
+def _same_overload(base: str, impl: str) -> bool:
+ """False only when both are overload members of different arities."""
+ base_arity = symbol_id_discriminator(base)
+ impl_arity = symbol_id_discriminator(impl)
+ return base_arity is None or impl_arity is None or base_arity == impl_arity
def resolve_override_dispatch(
@@ -149,7 +157,9 @@ def resolve_override_dispatch(
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)
+ candidates[base].update(
+ impl for impl in impls if impl != base and _same_overload(base, impl)
+ )
added = 0
refused = 0
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 8f4349d42..ba63dfbdd 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -19,6 +19,7 @@ from ..languages.python_modules import dotted_module_for
from ..models import ParsedFile
from ..resolvers import ResolverContext, resolve_import
from ..resolvers.go import read_go_module_path, read_go_modules
+from ..symbol_identity import has_overload_identity
from ..type_ref_resolution import resolve_type_refs
from ._edges import EdgesMixin
from ._metrics import MetricsMixin
@@ -256,11 +257,21 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# the one-line declaration overwrites a definition's span, kind and
# ``is_declaration``, and every consumer that tells the two apart
# then reads the header line as the whole symbol.
+ existing = self._graph.nodes.get(sym.id)
if sym.is_declaration:
- existing = self._graph.nodes.get(sym.id)
if existing is not None and existing.get("is_declaration") is False:
self._graph.add_edge(path, sym.id, edge_type="defines")
continue
+ # Where overloads get their own ids, two definitions still sharing
+ # one are overloads of one arity: the first declared keeps the node,
+ # so its span does not depend on how many follow it.
+ elif (
+ existing is not None
+ and existing.get("is_declaration") is False
+ and has_overload_identity(sym.language)
+ ):
+ self._graph.add_edge(path, sym.id, edge_type="defines")
+ continue
self._graph.add_node(
sym.id,
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index ab063f3a4..a43684d64 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -31,6 +31,7 @@ from ..type_names import (
bare_type_name,
is_resolvable_type_name,
strip_type_arguments,
+ type_argument_count,
type_qualifier,
unwrap_pointer_like,
)
@@ -675,7 +676,9 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:
"""``(bare name, unwrapped)`` for *raw*, or ``(None, False)``.
Only C++ looks inside the spelling: ``shared_ptr<Foo>`` is a ``Foo`` behind
- the arrow. Elsewhere the generic head is the value's real type.
+ the arrow. Elsewhere the generic head is the value's real type. A C# head
+ keeps its arity, ``IFoo`1``, since a same-file ``IFoo`` may be another type;
+ the lookup falls back to the bare name.
"""
if _nests_in_a_builtin(raw, language):
return None, False
@@ -683,6 +686,8 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:
name = inner or (raw if raw.isidentifier() else bare_type_name(raw))
if not is_resolvable_type_name(name, language):
return None, False
+ if language == "csharp" and (arity := type_argument_count(raw)):
+ name = f"{name}`{arity}"
return name, inner is not None
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index e78dc5a82..511ed6335 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -195,7 +195,9 @@ class RepoStructure:
class Symbol:
"""A code symbol (function, class, method, …) extracted from a file."""
- id: str # "<rel_path>::<name>" or "<rel_path>::<class>::<method>"
+ # "<rel_path>::<name>" or "<rel_path>::<class>::<method>", plus a
+ # discriminator when a scope declares the name twice (see symbol_identity).
+ id: str
name: str
qualified_name: str # dotted full name, e.g. "myapp.calc.Calculator.add"
kind: SymbolKind
@@ -221,6 +223,9 @@ class Symbol:
# stubs and TypeScript overload signatures are declarations too: they share
# the implementation's id, and the implementation is the symbol to serve.
is_declaration: bool = False
+ # C# type declarations only: how many type parameters it declares, which is
+ # what tells ``IFoo<T>`` from a same-named ``IFoo``. None elsewhere.
+ type_parameter_count: int | None = None
@dataclass
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index dc80bdcd9..99f8db139 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -89,6 +89,7 @@ from .parser_helpers import (
_classify_param_origin,
_collect_error_nodes,
_count_arguments,
+ _csharp_type_parameter_count,
_dedupe_objc_interface_symbols,
_dedupe_pascal_interface_symbols,
_elixir_call_is_definitional,
@@ -119,6 +120,7 @@ from .parser_helpers import (
from .python_local_refs import extract_python_local_refs
from .sfc_source import component_call_sites, prepare_source
from .special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_special
+from .symbol_identity import disambiguate_colliding_ids, symbol_discriminator
log = structlog.get_logger(__name__)
@@ -1330,8 +1332,14 @@ class ASTParser:
# without a registered extractor.
synthetic = extract_synthetic_symbols(root, src, file_info)
if synthetic:
- existing_ids = {s.id for s in symbols}
- symbols.extend(s for s in synthetic if s.id not in existing_ids)
+ # Keyed with the discriminator too, so a record's synthetic
+ # canonical constructor survives beside an explicit overload of
+ # another arity. A language without one dedupes on the id alone.
+ existing = {(s.id, symbol_discriminator(s)) for s in symbols}
+ symbols.extend(s for s in synthetic if (s.id, symbol_discriminator(s)) not in existing)
+ # Before calls and references are extracted, so both attribute to the
+ # final ids.
+ disambiguate_colliding_ids(symbols, lang)
imports = self._extract_imports(matches, config, file_info, src)
calls = self._extract_calls(matches, config, file_info, src, symbols)
# An SFC instantiates a component by writing its tag in the markup
@@ -1566,6 +1574,9 @@ class ASTParser:
parent_name=parent_name,
is_exported_symbol=is_exported_symbol,
is_declaration=_is_declaration(def_node, config, language, export_type, src),
+ type_parameter_count=(
+ _csharp_type_parameter_count(def_node) if language == "csharp" else None
+ ),
)
return symbol, def_node
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index ea0ae6642..ad35a4af3 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -203,6 +203,27 @@ def _build_qualified_name(file_path: str, parent_name: str | None, name: str) ->
return f"{module}.{name}"
+_CSHARP_TYPE_NODES = frozenset(
+ {
+ "class_declaration",
+ "interface_declaration",
+ "struct_declaration",
+ "record_declaration",
+ "delegate_declaration",
+ }
+)
+
+
+def _csharp_type_parameter_count(def_node: Node) -> int | None:
+ """How many type parameters a C# type declares (0 if none); None for a non-type."""
+ if def_node.type not in _CSHARP_TYPE_NODES:
+ return None
+ for child in def_node.children:
+ if child.type == "type_parameter_list":
+ return sum(1 for param in child.children if param.type == "type_parameter")
+ return 0
+
+
def _count_arguments(arg_node: Node) -> int:
"""Count the number of arguments in an argument/argument_list node.
diff --git a/packages/core/src/repowise/core/ingestion/queries/java.scm b/packages/core/src/repowise/core/ingestion/queries/java.scm
index f2f1d0806..239ba231d 100644
--- a/packages/core/src/repowise/core/ingestion/queries/java.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/java.scm
@@ -39,7 +39,11 @@
name: (identifier) @symbol.name
) @symbol.def
+; One pattern, modifiers optional: two overlapping patterns kept whichever
+; matched first, which dropped either the modifiers or the parameters that
+; name an overload.
(method_declaration
+ (modifiers)? @symbol.modifiers
name: (identifier) @symbol.name
parameters: (formal_parameters) @symbol.params
) @symbol.def
@@ -49,12 +53,6 @@
parameters: (formal_parameters) @symbol.params
) @symbol.def
-; Public modifier capture
-(method_declaration
- (modifiers) @symbol.modifiers
- name: (identifier) @symbol.name
-) @symbol.def
-
; ---------------------------------------------------------------------------
; Imports
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.py
index 530f461f2..c9f5a9ddb 100644
--- a/packages/core/src/repowise/core/ingestion/return_types.py
+++ b/packages/core/src/repowise/core/ingestion/return_types.py
@@ -19,33 +19,70 @@ def declared_return_type(signature: str) -> str | None:
return value or None
-def signature_parameter_count(signature: str) -> int | None:
- """Count top-level parameters in a stored callable signature."""
+_PAIRS = {"(": ")", "[": "]", "{": "}", "<": ">"}
+
+def _top_level_parameters(signature: str) -> list[str] | None:
+ """The top-level parameter texts of a stored callable signature.
+
+ ``[]`` for an empty list, None when the signature has no closed list.
+ """
start = signature.find("(")
if start < 0:
return None
- depth = 0
- commas = 0
+ pieces: list[str] = []
+ current: list[str] = []
content = False
- pairs = {"(": ")", "[": "]", "{": "}", "<": ">"}
closers: list[str] = []
for char in signature[start + 1 :]:
if char == ")" and not closers:
- return commas + 1 if content else 0
- if char in pairs:
- closers.append(pairs[char])
- depth += 1
+ pieces.append("".join(current))
+ return pieces if content else []
+ if char in _PAIRS:
+ closers.append(_PAIRS[char])
elif closers and char == closers[-1]:
closers.pop()
- depth -= 1
- elif char == "," and depth == 0:
- commas += 1
- elif not char.isspace() and depth == 0:
+ elif char == "," and not closers:
+ pieces.append("".join(current))
+ current = []
+ continue
+ elif not char.isspace() and not closers:
content = True
+ current.append(char)
return None
+def signature_parameter_count(signature: str) -> int | None:
+ """Count top-level parameters in a stored callable signature."""
+ parameters = _top_level_parameters(signature)
+ return None if parameters is None else len(parameters)
+
+
+def signature_parameter_range(signature: str, language: str) -> tuple[int, int | None] | None:
+ """``(fewest, most)`` arguments a call may pass; ``most`` is None when open.
+
+ Java ``T...`` and C# ``params`` leave the top open, a C# default lowers
+ the floor, and a C# extension method is also called on its receiver, one
+ argument short of its declared list.
+ """
+ parameters = _top_level_parameters(signature)
+ if parameters is None:
+ return None
+ texts = [text.strip() for text in parameters]
+ fewest = most = len(texts)
+ if not texts:
+ return 0, 0
+ if language == "java" and "..." in texts[-1]:
+ fewest, most = fewest - 1, None
+ if language == "csharp":
+ if texts[-1].startswith("params "):
+ fewest, most = fewest - 1, None
+ fewest -= sum(1 for text in texts if "=" in text)
+ if texts[0].startswith("this "):
+ fewest -= 1
+ return max(fewest, 0), most
+
+
def go_first_result(value: str) -> str:
"""The first result's type of a go result list, ``(*T, error)`` -> ``*T``.
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
new file mode 100644
index 000000000..ece680cb0
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -0,0 +1,179 @@
+"""Symbol ids for names a scope declares more than once.
+
+A ``Symbol.id`` is ``<path>::<name>`` or ``<path>::<parent>::<name>``. Where a
+language lets one scope declare a name twice with different meanings, the ids
+would collide and the graph would keep one node for both. Only then, the id
+gains a discriminator:
+
+- ``#<digits>`` on the last segment: the declared parameter count of one
+ member of an overload set, ``Validate.java::Validate::notNull#1``. A call
+ narrows to the member whose parameters admit its argument count.
+- ``#<tag>(<predicate>)`` on the last segment: one build variant of a symbol
+ declared once per configuration, ``lib.rs::f#cfg(not(unix))``. A call may
+ mean any variant.
+- `` `<digits> `` on a type segment: the CLR generic arity that tells a C#
+ ``IFoo<T>`` from a same-file ``IFoo``, ``IFoo.cs::IFoo`1``. Its members
+ carry the suffix in ``parent_name`` and so in their own ids.
+
+``Symbol.name``, ``qualified_name`` and the signature never change, and a name
+declared once keeps its plain id. Discriminators are registered per language
+below, so a language without an entry is untouched by construction.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from collections.abc import Callable, Iterable
+
+from .models import Symbol
+from .return_types import signature_parameter_count
+
+# The payload after ``#``: a parameter count, or a build-variant predicate.
+_PAYLOAD = re.compile(r"\d+|[A-Za-z_]\w*\(.*\)")
+_GENERIC_ARITY = re.compile(r"`\d+$")
+
+
+def split_symbol_id(symbol_id: str) -> tuple[str, str | None]:
+ """``(base id, payload)``; the payload is None when the id carries none.
+
+ Only a payload matching the grammar is split off, so a name that merely
+ contains ``#`` (a TypeScript ``#private`` member) is left whole.
+ """
+ head, separator, last = symbol_id.rpartition("::")
+ name, hash_mark, payload = last.partition("#")
+ if not hash_mark or not name or _PAYLOAD.fullmatch(payload) is None:
+ return symbol_id, None
+ return f"{head}{separator}{name}", payload
+
+
+def base_symbol_id(symbol_id: str) -> str:
+ """*symbol_id* without its discriminator: the id an overload set shares."""
+ return split_symbol_id(symbol_id)[0]
+
+
+def symbol_id_discriminator(symbol_id: str) -> str | None:
+ """The discriminator after ``#``, or None for a plain id."""
+ return split_symbol_id(symbol_id)[1]
+
+
+def id_segment_name(segment: str) -> str:
+ """The source name one id segment spells: ``notNull#1`` or ``IFoo`1`` -> the bare name."""
+ name, hash_mark, payload = segment.partition("#")
+ if hash_mark and name and _PAYLOAD.fullmatch(payload):
+ segment = name
+ return _GENERIC_ARITY.sub("", segment)
+
+
+def overload_sets(symbol_ids: Iterable[str]) -> dict[str, list[str]]:
+ """``{base id: member ids}`` for every id that carries a discriminator."""
+ sets: dict[str, list[str]] = defaultdict(list)
+ for symbol_id in symbol_ids:
+ base = base_symbol_id(symbol_id)
+ if base != symbol_id:
+ sets[base].append(symbol_id)
+ return dict(sets)
+
+
+def _parameter_count(symbol: Symbol) -> str | None:
+ """A callable's declared parameter count, the overload discriminator."""
+ if symbol.kind not in ("function", "method"):
+ return None
+ count = signature_parameter_count(symbol.signature or "")
+ return None if count is None else str(count)
+
+
+# Which discriminator tells colliding members apart, per language. A build
+# variant (C ``#if`` branches, Rust ``cfg``) registers here as its own function.
+_DISCRIMINATORS: dict[str, Callable[[Symbol], str | None]] = {
+ "java": _parameter_count,
+ "csharp": _parameter_count,
+}
+
+# Languages where a type may share its name with a sibling of another arity.
+_GENERIC_ARITY_LANGUAGES = frozenset({"csharp"})
+
+
+def has_overload_identity(language: str) -> bool:
+ """Does *language* give colliding declarations their own ids?"""
+ return language in _DISCRIMINATORS
+
+
+def symbol_discriminator(symbol: Symbol) -> str | None:
+ """What would tell *symbol* apart from a same-id sibling, or None."""
+ discriminator = _DISCRIMINATORS.get(symbol.language)
+ return None if discriminator is None else discriminator(symbol)
+
+
+def disambiguate_colliding_ids(symbols: list[Symbol], language: str) -> None:
+ """Give each member of a colliding id its own id, in place.
+
+ Members whose discriminators are equal stay one id (two overloads of one
+ arity are one node); a member with no discriminator, such as a nested type
+ beside a method of its name, keeps the plain id.
+ """
+ discriminator = _DISCRIMINATORS.get(language)
+ if discriminator is None:
+ return
+ if language in _GENERIC_ARITY_LANGUAGES:
+ _split_generic_types(symbols)
+ groups: dict[str, list[Symbol]] = defaultdict(list)
+ for symbol in symbols:
+ groups[symbol.id].append(symbol)
+ for base, members in groups.items():
+ if len(members) < 2:
+ continue
+ keyed = [(symbol, discriminator(symbol)) for symbol in members]
+ if len({key for _, key in keyed if key is not None}) < 2:
+ continue
+ for symbol, key in keyed:
+ if key is not None:
+ symbol.id = f"{base}#{key}"
+
+
+def _split_generic_types(symbols: list[Symbol]) -> None:
+ """Suffix a generic type that shares its id with a sibling of another arity.
+
+ The non-generic sibling keeps the plain id. Members declared inside the
+ renamed type's span are re-parented onto it, which has to happen before
+ overload sets are grouped, or ``IFoo.Validate`` and ``IFoo<T>.Validate``
+ would read as one overload set.
+ """
+ types: dict[str, list[Symbol]] = defaultdict(list)
+ for symbol in symbols:
+ if symbol.type_parameter_count is not None:
+ types[symbol.id].append(symbol)
+ for siblings in types.values():
+ if len({s.type_parameter_count for s in siblings}) < 2:
+ continue
+ for generic in siblings:
+ if generic.type_parameter_count:
+ _reparent_members(symbols, generic, f"{generic.name}`{generic.type_parameter_count}")
+ generic.id = f"{generic.id}`{generic.type_parameter_count}"
+
+
+def _reparent_members(symbols: list[Symbol], owner: Symbol, segment: str) -> None:
+ old_tail = f"::{owner.name}::"
+ for member in symbols:
+ if (
+ member is owner
+ or member.parent_name != owner.name
+ or not owner.start_line <= member.start_line <= owner.end_line
+ ):
+ continue
+ head, found, rest = member.id.rpartition(old_tail)
+ if found and rest == member.name:
+ member.id = f"{head}::{segment}::{rest}"
+ member.parent_name = segment
+
+
+__all__ = [
+ "base_symbol_id",
+ "disambiguate_colliding_ids",
+ "has_overload_identity",
+ "id_segment_name",
+ "overload_sets",
+ "split_symbol_id",
+ "symbol_discriminator",
+ "symbol_id_discriminator",
+]
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
index ea462392c..f21199efb 100644
--- a/packages/core/src/repowise/core/ingestion/type_names.py
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -94,6 +94,31 @@ def bare_type_name(raw: str) -> str:
return text.strip()
+def type_argument_count(raw: str) -> int:
+ """How many type arguments the named type in *raw* is given.
+
+ ``Gen<A, B<C>>`` → 2; ``Gen<A>?`` → 1; ``Outer<A>.Inner`` and ``Plain`` → 0,
+ since only arguments on the last segment belong to the type named.
+ """
+ text = raw.strip().rstrip("?").rstrip()
+ while text.endswith("[]"):
+ text = text[:-2].rstrip()
+ if not text.endswith(">"):
+ return 0
+ depth = 0
+ commas = 0
+ for char in reversed(text):
+ if char == ">":
+ depth += 1
+ elif char == "<":
+ depth -= 1
+ if depth == 0:
+ return commas + 1
+ elif char == "," and depth == 1:
+ commas += 1
+ return 0
+
+
def type_qualifier(raw: str) -> str:
"""Return what ``bare_type_name`` drops from the front of *raw*, or ``""``.
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index cee8fa96c..e7bc15f7a 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -583,8 +583,15 @@ async def persist_incremental_symbols(
"""
if not parsed_files:
return
+ from repowise.core.ingestion.parse_cache import parser_fingerprint
from repowise.core.persistence.crud import reconcile_symbols_for_files
+ # An extraction change can re-key symbols in files git did not touch (an
+ # overload gaining its own id), so it widens to the whole parsed set on the
+ # same check that widens edges. The stamp is written once, by
+ # :func:`persist_incremental_edges`, which runs after this.
+ if await _stored_edges_parser_fingerprint(session, repo_id) != parser_fingerprint():
+ changed_paths = [pf.file_info.path for pf in parsed_files]
reconcile_paths, symbols = _changed_file_symbols(parsed_files, changed_paths)
if not reconcile_paths:
return
@@ -804,9 +811,53 @@ async def persist_incremental_edges(
# caller before the commit) leaves the old stamp, so the next update retries
# rather than stranding the files it never reached.
if parser_changed:
+ await _prune_vanished_symbol_nodes(session, repo_id, graph_builder, parsed_files)
await stamp_edges_parser_fingerprint(session, repo_id, fingerprint)
+async def _prune_vanished_symbol_nodes(
+ session: Any, repo_id: str, graph_builder: Any, parsed_files: list[Any]
+) -> None:
+ """Delete symbol ``graph_nodes`` a re-extraction no longer produces.
+
+ ``persist_graph_nodes`` upserts the current graph and never deletes, so a
+ symbol whose id changed under a new parser (an overload gaining its own id)
+ would otherwise keep its old row beside the new ones. Scoped to files this
+ run parsed; a file that is gone is :func:`_prune_stale_file_rows`'s job.
+ Membership rows prune themselves on their next write, and ``graph_metrics``
+ holds files only.
+ """
+ from sqlalchemy import delete, or_, select
+
+ from repowise.core.persistence.models import GraphEdge, GraphNode
+
+ graph = graph_builder.graph()
+ paths = [pf.file_info.path for pf in parsed_files]
+ stale: list[str] = []
+ for i in range(0, len(paths), _PRUNE_CHUNK):
+ rows = await session.execute(
+ select(GraphNode.node_id).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type != "file",
+ GraphNode.file_path.in_(paths[i : i + _PRUNE_CHUNK]),
+ )
+ )
+ stale.extend(node_id for node_id in rows.scalars() if node_id not in graph)
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(
+ delete(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ or_(GraphEdge.source_node_id.in_(batch), GraphEdge.target_node_id.in_(batch)),
+ )
+ )
+ await session.execute(
+ delete(GraphNode).where(GraphNode.repository_id == repo_id, GraphNode.node_id.in_(batch))
+ )
+ if stale:
+ logger.info("graph_nodes_parser_prune", repo_id=repo_id, nodes=len(stale))
+
+
# Chunk size for IN (...) deletes — stays under SQLite's host-parameter limit.
_PRUNE_CHUNK = 500
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index d5e1a9c44..01dcc20c2 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -65,7 +65,10 @@ STORE_FORMAT_VERSION: int = 2
#:
#: v6: a member call a bare-call pattern also matched (Java ``obj.m()``, Ruby
#: ``obj.m(x)``) is kept once, with its receiver and ``bare_name_fallback``, so
-#: a cached receiver-less copy no longer resolves by bare name beside it.
+#: a cached receiver-less copy no longer resolves by bare name beside it. Also,
+#: Java and C# overloads of different arity get their own ids (``notNull#1``,
+#: ``notNull#2``) and a C# generic type beside a same-named one gets its arity
+#: (``IFoo`1``); the first update re-keys symbols and graph nodes repo-wide.
PARSER_SCHEMA_VERSION: int = 6
#: state.json key holding the store format version that wrote the store.
diff --git a/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
index 0298e9a80..6020655ea 100644
--- a/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
+++ b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
@@ -19,6 +19,7 @@ from __future__ import annotations
from sqlalchemy import or_, select
+from repowise.core.ingestion.symbol_identity import base_symbol_id, id_segment_name
from repowise.core.persistence.models import WikiSymbol
from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
from repowise.core.support_paths import is_support_path
@@ -94,11 +95,15 @@ def symbol_id_variants(symbol_id: str) -> list[str]:
def bare_name(name: str) -> str:
- """Return the last name segment regardless of separator style."""
+ """Return the last name segment regardless of separator style.
+
+ An overload or generic-arity discriminator (``notNull#1``, ``IFoo`1``) is
+ part of the id, never of the name, so it is dropped.
+ """
tail = name
for sep in NAME_SEPARATORS:
tail = tail.rsplit(sep, 1)[-1]
- return tail
+ return id_segment_name(tail)
# Kinds a bare name most likely means, best first; everything else (variables,
@@ -196,14 +201,27 @@ async def resolve_symbol_rows(session, repo_id: str, symbol_id: str) -> list[Wik
"""
file_path, name = parse_symbol_id(symbol_id)
- # 1. Exact symbol_id — try every separator variant.
+ # 1. Exact symbol_id — try every separator variant. The same query also
+ # reads the members of an overload set the id names, which carry a
+ # discriminator (``Validate.java::Validate::notNull`` -> ``notNull#1``,
+ # ``notNull#2``); they answer only when no row matches exactly.
+ variants = symbol_id_variants(symbol_id)
res = await session.execute(
select(WikiSymbol).where(
WikiSymbol.repository_id == repo_id,
- WikiSymbol.symbol_id.in_(symbol_id_variants(symbol_id)),
+ or_(
+ WikiSymbol.symbol_id.in_(variants),
+ *(
+ WikiSymbol.symbol_id.like(f"{escape_like(sid)}#%", escape=LIKE_ESCAPE)
+ for sid in variants
+ ),
+ ),
)
)
- rows = list(res.scalars().all())
+ found = list(res.scalars().all())
+ rows = [row for row in found if row.symbol_id in variants] or [
+ row for row in found if base_symbol_id(row.symbol_id) in variants
+ ]
if rows:
return order_candidates(rows, file_path)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index a4375e94d..df87e3056 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -33,6 +33,7 @@ from repowise.core.ingestion.models import (
FILE_DEPENDENCY_EDGE_TYPES,
SYMBOL_USE_EDGE_TYPES,
)
+from repowise.core.ingestion.symbol_identity import id_segment_name
from repowise.core.persistence.crud import (
coverage_row_dict,
doc_drift_references_stored,
@@ -196,7 +197,7 @@ async def _resolve_call_graph(
node = await get_graph_node(session, repo_id, target)
if node is None and "::" in target:
# Fuzzy: try bare name
- bare_name = target.split("::")[-1]
+ bare_name = id_segment_name(target.split("::")[-1])
res = await session.execute(
select(GraphNode).where(
GraphNode.repository_id == repo_id,
diff --git a/tests/unit/dead_code/test_overload_unit.py b/tests/unit/dead_code/test_overload_unit.py
new file mode 100644
index 000000000..59ed3be22
--- /dev/null
+++ b/tests/unit/dead_code/test_overload_unit.py
@@ -0,0 +1,80 @@
+"""An overload set is one dead-code unit.
+
+Java and C# overloads of different arity carry their own ids (``pad#1``,
+``pad#2``). Dead code still judges the set as one symbol: a use of any member
+uses all of them, no member becomes a finding of its own, and the composed
+constructor id ``path::X::X`` finds ``X``'s constructors wherever their arities
+put them.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+
+_FILE = "src/Box.cs"
+_CONFIG = {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+}
+
+
+def _graph(symbols: list[tuple[str, str, str, int]], calls: list[tuple[str, str]]) -> nx.DiGraph:
+ """*symbols* as ``(id suffix, name, kind, start line)``, all private C#."""
+ g = nx.DiGraph()
+ g.add_node(_FILE, language="csharp")
+ for suffix, name, kind, line in symbols:
+ sym_id = f"{_FILE}::{suffix}"
+ g.add_node(
+ sym_id,
+ node_type="symbol",
+ file_path=_FILE,
+ name=name,
+ kind=kind,
+ language="csharp",
+ visibility="private",
+ decorators=[],
+ start_line=line,
+ end_line=line + 2,
+ )
+ g.add_edge(_FILE, sym_id, edge_type="defines")
+ for caller, callee in calls:
+ g.add_edge(caller, f"{_FILE}::{callee}", edge_type="calls")
+ return g
+
+
+def _unused(g: nx.DiGraph) -> list[tuple[str, int]]:
+ report = DeadCodeAnalyzer(g, git_meta_map={}).analyze(_CONFIG)
+ return sorted(
+ (f.symbol_name, f.start_line)
+ for f in report.findings
+ if f.kind == DeadCodeKind.UNUSED_INTERNAL
+ )
+
+
+_PAD = [("Box::pad#1", "pad", "method", 10), ("Box::pad#2", "pad", "method", 20)]
+
+
+def test_a_use_of_one_overload_uses_the_set() -> None:
+ assert _unused(_graph(_PAD, [("src/Main.cs::Main::Run", "Box::pad#2")])) == []
+
+
+def test_an_unused_overload_set_adds_no_finding_per_member() -> None:
+ """Members are reached through their type, so the split adds no findings."""
+ assert _unused(_graph(_PAD, [])) == []
+
+
+def test_a_constructor_overload_rescues_its_class() -> None:
+ """``new Inner(a, b)`` lands on ``Inner::Inner#2``; the class is used."""
+ symbols = [
+ ("Inner", "Inner", "class", 3),
+ ("Inner::Inner#0", "Inner", "method", 4),
+ ("Inner::Inner#2", "Inner", "method", 5),
+ ("Spare", "Spare", "class", 30),
+ ]
+ found = _unused(_graph(symbols, [("src/Main.cs::Main::Run", "Inner::Inner#2")]))
+ assert ("Inner", 3) not in found
+ assert ("Spare", 30) in found
diff --git a/tests/unit/ingestion/test_csharp_extension_methods.py b/tests/unit/ingestion/test_csharp_extension_methods.py
index cefbeff16..bf805b508 100644
--- a/tests/unit/ingestion/test_csharp_extension_methods.py
+++ b/tests/unit/ingestion/test_csharp_extension_methods.py
@@ -264,7 +264,8 @@ class TestRefusals:
assert "Dup" not in _resolve(tmp_path, files, "src/Consumer.cs")
def test_an_overload_set_is_not_ambiguous(self, tmp_path: Path) -> None:
- """Every overload in one class shares a symbol id, so the pair survives."""
+ """An overload set is indexed once, so the pair survives and the call
+ narrows to the member its arguments admit."""
files = {
"src/Order.cs": ORDER,
"src/Ext.cs": (
@@ -278,4 +279,4 @@ class TestRefusals:
),
}
found = _resolve(tmp_path, files, "src/Consumer.cs")
- assert found["Net"] == ("receiver_extension_global", 0.75)
+ assert found["Net#1"] == ("receiver_extension_global", 0.75)
diff --git a/tests/unit/ingestion/test_dispatch_edges.py b/tests/unit/ingestion/test_dispatch_edges.py
index e1f4269a5..f94d5487e 100644
--- a/tests/unit/ingestion/test_dispatch_edges.py
+++ b/tests/unit/ingestion/test_dispatch_edges.py
@@ -365,10 +365,9 @@ def test_a_csharp_bare_call_reaches_an_inherited_method(tmp_path: Path) -> None:
)
-def test_a_csharp_overload_set_resolves_to_the_one_id_it_shares(tmp_path: Path) -> None:
- """Overloads of one name in one class carry one symbol id, so a call
- reaching any of them lands on the same node. Pins the property the
- inherited tier relies on: there is nothing to choose between."""
+def test_a_csharp_inherited_overload_call_lands_on_the_member_it_names(tmp_path: Path) -> None:
+ """The inherited tier answers with the overload set, and the call narrows
+ to the member whose arity its arguments match."""
graph = _build(
tmp_path,
{
@@ -385,9 +384,9 @@ def test_a_csharp_overload_set_resolves_to_the_one_id_it_shares(tmp_path: Path)
},
"csharp",
)
- assert ("Test.cs::Test::Run", "Steps.cs::Steps::Given") in _calls_by_origin(
- graph, "enclosing_inherited"
- )
+ assert _calls_by_origin(graph, "enclosing_inherited") == {
+ ("Test.cs::Test::Run", "Steps.cs::Steps::Given#2")
+ }
# ``super().m()`` walks the caller's MRO past its own class. It used to reach
diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.py
new file mode 100644
index 000000000..68e31df25
--- /dev/null
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -0,0 +1,419 @@
+"""Overloads and same-named generic siblings get their own symbol ids.
+
+Java and C# let one scope declare a name more than once. The ids used to
+collide, so the graph kept one node per overload set (whichever declaration was
+written last) and every call to any overload drew an edge to that one line. A
+colliding member now carries a discriminator, ``#<parameter count>``, and a C#
+generic type beside a same-named one carries its arity, ``IFoo`1``. Calls narrow
+to the member their argument count names.
+
+The controls: a name declared once keeps its plain id, two overloads of one
+arity stay one node, and a language without a registered discriminator is
+untouched.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.actions.rules._text import code
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.graph.builder import GraphBuilder
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.return_types import signature_parameter_range
+from repowise.core.ingestion.symbol_identity import (
+ base_symbol_id,
+ id_segment_name,
+ overload_sets,
+ split_symbol_id,
+)
+from repowise.core.ingestion.traverser import FileTraverser
+from repowise.core.ingestion.type_names import type_argument_count
+from repowise.server.mcp_server._symbol_lookup import bare_name
+
+_PARSER = ASTParser()
+_FIXTURES = Path(__file__).resolve().parents[2] / "fixtures"
+
+
+def _info(rel: str, abs_path: str, language: str, size: int) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language=language, # type: ignore[arg-type]
+ size_bytes=size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _parse(rel: str, language: str, text: str, root: Path | None = None) -> ParsedFile:
+ """Parse *text*; with *root*, also write it there, where receiver typing reads it."""
+ abs_path = rel
+ if root is not None:
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ abs_path = str(path)
+ return _PARSER.parse_file(_info(rel, abs_path, language, len(text)), text.encode("utf-8"))
+
+
+def _ids(parsed: ParsedFile) -> list[str]:
+ return [s.id for s in parsed.symbols]
+
+
+def _edges(root: Path, files: dict[str, tuple[str, str]]) -> set[tuple[str, str]]:
+ parsed = {rel: _parse(rel, lang, text, root) for rel, (lang, text) in files.items()}
+ resolver = CallResolver(
+ parsed, {rel: set(parsed) - {rel} for rel in parsed}, repo_path=str(root)
+ )
+ return {
+ (rc.caller_id, rc.callee_id)
+ for rel, pf in parsed.items()
+ for rc in resolver.resolve_file(rel, pf.calls)
+ }
+
+
+def _graph(files: dict[str, tuple[str, str]]):
+ builder = GraphBuilder()
+ for rel, (lang, text) in files.items():
+ builder.add_file(_parse(rel, lang, text))
+ return builder.build()
+
+
+VALIDATE = """package app;
+
+public final class Validate {
+ public static void notNull(Object obj) {
+ notNull(obj, "must not be null");
+ }
+
+ public static void notNull(Object obj, String msg) {
+ if (obj == null) throw new IllegalArgumentException(msg);
+ }
+
+ public static void fail(String msg, Object... args) {
+ throw new IllegalStateException(msg);
+ }
+
+ public static void fail(String msg) {
+ fail(msg, new Object[0]);
+ }
+
+ public static void once() {
+ }
+}
+"""
+
+CALLER = """package app;
+
+public class Caller {
+ public void run(Object o) {
+ Validate.notNull(o);
+ Validate.notNull(o, "o");
+ Validate.fail("x");
+ Validate.fail("x", 1, 2);
+ Validate.once();
+ }
+}
+"""
+
+
+class TestIdGrammar:
+ @pytest.mark.parametrize(
+ ("symbol_id", "base", "payload"),
+ [
+ ("V.java::V::notNull#1", "V.java::V::notNull", "1"),
+ ("lib.rs::f#cfg(not(unix))", "lib.rs::f", "cfg(not(unix))"),
+ ("V.java::V::notNull", "V.java::V::notNull", None),
+ # A TypeScript private member names itself with `#`; it is no payload.
+ ("a.ts::Box::#secret", "a.ts::Box::#secret", None),
+ ("I.cs::IFoo`1::Validate#2", "I.cs::IFoo`1::Validate", "2"),
+ ],
+ )
+ def test_split(self, symbol_id: str, base: str, payload: str | None) -> None:
+ assert split_symbol_id(symbol_id) == (base, payload)
+ assert base_symbol_id(symbol_id) == base
+
+ def test_segment_name_strips_both_discriminators(self) -> None:
+ assert id_segment_name("notNull#2") == "notNull"
+ assert id_segment_name("IFoo`1") == "IFoo"
+ assert id_segment_name("#secret") == "#secret"
+ assert bare_name("Validate::notNull#1") == "notNull"
+ assert bare_name("IValidator`1") == "IValidator"
+
+ def test_overload_sets_groups_only_suffixed_ids(self) -> None:
+ assert overload_sets(["a::f#1", "a::f#2", "a::g", "a::T`1"]) == {"a::f": ["a::f#1", "a::f#2"]}
+
+ @pytest.mark.parametrize(
+ ("signature", "language", "expected"),
+ [
+ ("f(int a, int b) -> void", "java", (2, 2)),
+ ("f() -> void", "java", (0, 0)),
+ ("f(String msg, Object... args) -> void", "java", (1, None)),
+ ("f(string a, params object[] rest) -> void", "csharp", (1, None)),
+ ("f(int a, int b = 0, bool c = false) -> int", "csharp", (1, 3)),
+ ("Ext(this Order o, bool round) -> int", "csharp", (1, 2)),
+ ("f(Map<K, V> m) -> void", "java", (1, 1)),
+ ("noparens", "java", None),
+ ],
+ )
+ def test_parameter_range(self, signature: str, language: str, expected) -> None:
+ assert signature_parameter_range(signature, language) == expected
+
+ @pytest.mark.parametrize(
+ ("raw", "count"),
+ [("IFoo<T>", 1), ("Dictionary<string, List<int>>", 2), ("IFoo<T>?", 1),
+ ("Outer<T>.Inner", 0), ("Plain", 0), ("Foo<T>[]", 1)],
+ )
+ def test_type_argument_count(self, raw: str, count: int) -> None:
+ assert type_argument_count(raw) == count
+
+ def test_markdown_code_span_survives_a_backtick(self) -> None:
+ assert code("a.py::f") == "`a.py::f`"
+ assert code("I.cs::IFoo`1") == "`` I.cs::IFoo`1 ``"
+
+
+class TestJavaOverloads:
+ def test_colliding_members_get_their_parameter_count(self) -> None:
+ ids = _ids(_parse("app/Validate.java", "java", VALIDATE))
+ assert "app/Validate.java::Validate::notNull#1" in ids
+ assert "app/Validate.java::Validate::notNull#2" in ids
+ assert "app/Validate.java::Validate::fail#2" in ids
+ assert "app/Validate.java::Validate::fail#1" in ids
+ # Declared once: the plain id, byte for byte.
+ assert "app/Validate.java::Validate::once" in ids
+ assert "app/Validate.java::Validate" in ids
+
+ def test_a_modified_method_signature_names_its_parameters(self) -> None:
+ parsed = _parse("app/Validate.java", "java", VALIDATE)
+ once = next(s for s in parsed.symbols if s.name == "once")
+ assert once.signature == "once() -> void"
+
+ def test_two_overloads_of_one_arity_stay_one_node_and_the_first_keeps_it(self) -> None:
+ text = (
+ "public class P {\n"
+ " public void put(String k) { }\n"
+ " public void put(int k) { }\n"
+ " public void put(String k, int v) { }\n"
+ "}\n"
+ )
+ graph = _graph({"P.java": ("java", text)})
+ node = graph.nodes["P.java::P::put#1"]
+ assert (node["start_line"], node["signature"]) == (2, "put(String k) -> void")
+ assert "P.java::P::put#2" in graph
+
+ def test_a_record_keeps_its_canonical_constructor_beside_an_overload(self) -> None:
+ text = (
+ "public record Point(int x, int y) {\n"
+ " public Point(int x) { this(x, 0); }\n"
+ "}\n"
+ )
+ ids = _ids(_parse("Point.java", "java", text))
+ assert "Point.java::Point::Point#1" in ids
+ assert "Point.java::Point::Point#2" in ids
+
+ def test_calls_narrow_to_the_member_their_arguments_name(self, tmp_path: Path) -> None:
+ edges = _edges(tmp_path, {"app/Validate.java": ("java", VALIDATE), "app/Caller.java": ("java", CALLER)})
+ run = "app/Caller.java::Caller::run"
+ targets = {callee for caller, callee in edges if caller == run}
+ assert targets == {
+ "app/Validate.java::Validate::notNull#1",
+ "app/Validate.java::Validate::notNull#2",
+ "app/Validate.java::Validate::fail#1",
+ "app/Validate.java::Validate::fail#2",
+ "app/Validate.java::Validate::once",
+ }
+
+ def test_an_overload_calls_its_sibling_and_never_itself(self, tmp_path: Path) -> None:
+ edges = _edges(tmp_path, {"app/Validate.java": ("java", VALIDATE)})
+ base = "app/Validate.java::Validate::"
+ # notNull(obj) is the set's first member; its call to the two-argument
+ # form used to be refused as recursion on the shared id.
+ assert (base + "notNull#1", base + "notNull#2") in edges
+ assert (base + "fail#1", base + "fail#2") in edges
+ assert not [e for e in edges if e[0] == e[1]]
+
+ def test_an_unknown_argument_count_falls_back_to_the_first_member(self, tmp_path: Path) -> None:
+ text = (
+ "import java.util.function.Consumer;\n"
+ "public class R {\n"
+ " public void go() { Consumer<Object> c = Validate::notNull; c.accept(1); Validate.notNull(); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"app/Validate.java": ("java", VALIDATE), "app/R.java": ("java", text)})
+ hits = {callee for caller, callee in edges if caller == "app/R.java::R::go"}
+ # A zero-argument call matches no member; it keeps the representative.
+ assert hits <= {"app/Validate.java::Validate::notNull#1"}
+
+
+IVALIDATOR = """namespace App;
+
+public interface IValidator<in T> : IValidator {
+ ValidationResult Validate(T instance);
+}
+
+public interface IValidator {
+ ValidationResult Validate(IValidationContext context);
+ bool CanValidate(Type type);
+}
+"""
+
+USES = """namespace App;
+
+public class Runner {
+ private readonly IValidator _plain;
+
+ public void Typed(IValidator<string> typed, IValidationContext ctx) {
+ typed.Validate("x");
+ _plain.Validate(ctx);
+ }
+}
+"""
+
+
+class TestCSharpGenericSiblings:
+ def test_the_generic_sibling_carries_its_arity_and_its_members(self) -> None:
+ ids = _ids(_parse("src/IValidator.cs", "csharp", IVALIDATOR))
+ assert "src/IValidator.cs::IValidator`1" in ids
+ assert "src/IValidator.cs::IValidator`1::Validate" in ids
+ assert "src/IValidator.cs::IValidator" in ids
+ assert "src/IValidator.cs::IValidator::Validate" in ids
+ assert "src/IValidator.cs::IValidator::CanValidate" in ids
+
+ def test_has_method_hangs_off_the_generic_type(self) -> None:
+ graph = _graph({"src/IValidator.cs": ("csharp", IVALIDATOR)})
+ assert graph.has_edge("src/IValidator.cs::IValidator`1", "src/IValidator.cs::IValidator`1::Validate")
+ assert not graph.has_edge("src/IValidator.cs::IValidator", "src/IValidator.cs::IValidator`1::Validate")
+
+ def test_a_lone_generic_type_keeps_its_plain_id(self) -> None:
+ text = "namespace App;\npublic class Repo<T> {\n public void Save(T item) { }\n}\n"
+ assert _ids(_parse("Repo.cs", "csharp", text))[-2:] == ["Repo.cs::Repo", "Repo.cs::Repo::Save"]
+
+ def test_a_receiver_reaches_the_sibling_its_type_arguments_name(self, tmp_path: Path) -> None:
+ edges = _edges(tmp_path, {"src/IValidator.cs": ("csharp", IVALIDATOR), "src/Runner.cs": ("csharp", USES)})
+ targets = {callee for caller, callee in edges if caller == "src/Runner.cs::Runner::Typed"}
+ assert targets == {
+ "src/IValidator.cs::IValidator`1::Validate",
+ "src/IValidator.cs::IValidator::Validate",
+ }
+
+ def test_csharp_overloads_narrow_by_defaults_and_params(self, tmp_path: Path) -> None:
+ holder = (
+ "namespace App;\npublic static class H {\n"
+ " public static int Sum(int a) => a;\n"
+ " public static int Sum(int a, int b, int c = 0) => a + b + c;\n"
+ " public static int Sum(string s, params int[] rest) => 0;\n"
+ "}\n"
+ )
+ caller = (
+ "namespace App;\npublic class C {\n"
+ " public int One() => H.Sum(1);\n"
+ " public int Two() => H.Sum(1, 2);\n"
+ " public int Four() => H.Sum(\"a\", 1, 2, 3);\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"H.cs": ("csharp", holder), "C.cs": ("csharp", caller)})
+ assert ("C.cs::C::One", "H.cs::H::Sum#1") in edges
+ assert ("C.cs::C::Two", "H.cs::H::Sum#3") in edges
+ assert ("C.cs::C::Four", "H.cs::H::Sum#2") in edges
+
+
+class TestOtherLanguagesAreUntouched:
+ @pytest.mark.parametrize(
+ ("rel", "language", "text"),
+ [
+ ("m.py", "python", "def f(a):\n pass\n\ndef f(a, b):\n pass\n"),
+ ("m.cpp", "cpp", "int f(int a) { return a; }\nint f(int a, int b) { return a; }\n"),
+ ("m.kt", "kotlin", "class K {\n fun f(a: Int) {}\n fun f(a: Int, b: Int) {}\n}\n"),
+ ],
+ )
+ def test_same_named_definitions_keep_one_plain_id(self, rel: str, language: str, text: str) -> None:
+ ids = _ids(_parse(rel, language, text))
+ assert all(base_symbol_id(i) == i for i in ids), ids
+
+
+def test_fixture_ids_carry_a_discriminator_only_on_collision() -> None:
+ """Every fixture symbol declared once keeps its plain id, in every language.
+
+ A discriminator appears only on an id another symbol of the same file
+ shares, and only in a language that registers one.
+ """
+ parser = ASTParser()
+ checked = 0
+ for sample in ("lang_samples", "jvm_sample", "dotnet_solution", "cpp_sample", "ts_sample", "sample_repo"):
+ for info in FileTraverser(_FIXTURES / sample).traverse():
+ parsed = parser.parse_file(info, Path(info.abs_path).read_bytes())
+ bases = [base_symbol_id(s.id) for s in parsed.symbols]
+ for symbol, base in zip(parsed.symbols, bases, strict=True):
+ checked += 1
+ if symbol.id == base and "`" not in symbol.id:
+ continue
+ assert symbol.language in ("java", "csharp"), symbol.id
+ assert bases.count(base) > 1 or "`" in symbol.id, symbol.id
+ assert checked > 500
+
+
+class TestNarrowingShapes:
+ """Call shapes the narrowing step must read by argument count alone."""
+
+ def test_csharp_named_arguments_and_explicit_type_arguments(self, tmp_path: Path) -> None:
+ holder = (
+ "namespace App;\npublic static class H {\n"
+ " public static int Sum(int a) => a;\n"
+ " public static int Sum(int a, int b) => a + b;\n"
+ " public static T Make<T>(T v) => v;\n"
+ " public static T Make<T>(T v, int n) => v;\n"
+ "}\n"
+ )
+ caller = (
+ "namespace App;\npublic class C {\n"
+ " public int Named() => H.Sum(b: 2, a: 1);\n"
+ " public int Typed() => H.Make<int>(1, 2);\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"H.cs": ("csharp", holder), "C.cs": ("csharp", caller)})
+ assert ("C.cs::C::Named", "H.cs::H::Sum#2") in edges
+ assert ("C.cs::C::Typed", "H.cs::H::Make#2") in edges
+
+ def test_java_explicit_type_arguments(self, tmp_path: Path) -> None:
+ util = (
+ "package app;\npublic class U {\n"
+ " public static <T> T make(T v) { return v; }\n"
+ " public static <T> T make(T v, int n) { return v; }\n"
+ "}\n"
+ )
+ caller = 'package app;\npublic class K {\n public void go() { U.<String>make("x", 2); }\n}\n'
+ edges = _edges(tmp_path, {"app/U.java": ("java", util), "app/K.java": ("java", caller)})
+ assert ("app/K.java::K::go", "app/U.java::U::make#2") in edges
+
+ def test_an_interface_default_method_calls_into_its_overload_set(self, tmp_path: Path) -> None:
+ shape = (
+ "package app;\npublic interface Shape {\n"
+ " default double area() { return scale(1.0); }\n"
+ " default double scale(double f) { return scale(f, 1.0); }\n"
+ " double scale(double f, double g);\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"app/Shape.java": ("java", shape)})
+ base = "app/Shape.java::Shape::"
+ assert (base + "area", base + "scale#1") in edges
+ assert (base + "scale#1", base + "scale#2") in edges
+
+ def test_overloads_split_across_a_superclass_keep_plain_ids(self, tmp_path: Path) -> None:
+ """Ids collide per class, so a base and a subclass overload stay plain."""
+ base = "package app;\npublic class Base {\n public void f(int a) { }\n}\n"
+ derived = (
+ "package app;\npublic class Derived extends Base {\n"
+ " public void f(int a, int b) { f(a); }\n"
+ "}\n"
+ )
+ 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")}
diff --git a/tests/unit/ingestion/test_overload_set_uniqueness.py b/tests/unit/ingestion/test_overload_set_uniqueness.py
index 82364ae6f..ff48141c3 100644
--- a/tests/unit/ingestion/test_overload_set_uniqueness.py
+++ b/tests/unit/ingestion/test_overload_set_uniqueness.py
@@ -1,9 +1,11 @@
"""Behaviour pins for tier 3 counting symbols rather than declaration rows.
``_global_symbols`` holds one entry per declaration, so an overload set is
-several rows under one id and ``len(candidates) == 1`` read it as an ambiguity
-that does not exist. C#'s ``AddRetry`` is two rows and one symbol; the tier
-refused it and the call reached nothing.
+several rows under one indexed id and ``len(candidates) == 1`` read it as an
+ambiguity that does not exist. C#'s ``AddRetry`` is two rows and one symbol; the
+tier refused it and the call reached nothing. Overloads of different arity now
+carry their own ids (``Widen#1``, ``Widen#2``), indexed under the first, and the
+call narrows to the one its arguments name.
The controls are what make the collapse safe, and each is a shape that reads
like the same defect and is not: a name two DIFFERENT symbols declare stays two
@@ -62,7 +64,7 @@ def _edges(
]
-# Two declarations, one symbol id: the shape the row count read as ambiguous.
+# Two declarations, one indexed name: the shape the row count read as ambiguous.
CS_OVERLOADS = """
namespace App;
@@ -163,8 +165,8 @@ class TestOverloadSetIsOneSymbol:
)
edges = _edges(parsed, tmp_path)
hits = [e for e in edges if e[0].endswith("::Caller::Run")]
- assert [e[1].split("::")[-2:] for e in hits] == [["Helpers", "Widen"]], (
- f"Widen's two declarations are one symbol and must resolve; edges: {edges}"
+ assert [e[1].split("::")[-2:] for e in hits] == [["Helpers", "Widen#2"]], (
+ f"Widen's overload set must resolve, to the two-argument member; edges: {edges}"
)
def test_two_different_symbols_of_one_name_stay_refused(self, tmp_path: Path) -> None:
diff --git a/tests/unit/persistence/test_overload_identity_migration.py b/tests/unit/persistence/test_overload_identity_migration.py
new file mode 100644
index 000000000..999c5d8d5
--- /dev/null
+++ b/tests/unit/persistence/test_overload_identity_migration.py
@@ -0,0 +1,163 @@
+"""An update re-keys an overload set that an older build stored under one id.
+
+Before overloads had their own ids, ``Validate.notNull(Object)`` and
+``Validate.notNull(Object, String)`` were one graph node and one
+``wiki_symbols`` row, ``Validate.java::Validate::notNull``. The new build parses
+them as ``notNull#1`` and ``notNull#2``. A file git did not touch must still
+lose the old row, because the change is in the parser, and the first update
+under the new build is the one that does it: symbols, graph nodes and edges are
+reconciled repo-wide once, then the stamp returns updates to the changed set.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from sqlalchemy import select
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.parse_cache import parser_fingerprint
+from repowise.core.persistence import batch_upsert_graph_edges
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository, WikiSymbol
+from repowise.core.pipeline.persist import (
+ persist_graph_nodes,
+ persist_incremental_edges,
+ persist_incremental_symbols,
+ stamp_edges_parser_fingerprint,
+)
+from tests.unit.persistence.helpers import insert_repo
+
+_VALIDATE = """package app;
+
+public final class Validate {
+ public static void notNull(Object obj) {
+ notNull(obj, "null");
+ }
+
+ public static void notNull(Object obj, String msg) {
+ if (obj == null) throw new IllegalArgumentException(msg);
+ }
+}
+"""
+
+_CALLER = """package app;
+
+public class Caller {
+ public void run(Object o) {
+ Validate.notNull(o);
+ }
+}
+"""
+
+_OLD_ID = "app/Validate.java::Validate::notNull"
+
+
+def _build(repo_dir: Path) -> tuple[GraphBuilder, list]:
+ parser = ASTParser()
+ gb = GraphBuilder(repo_dir)
+ parsed = []
+ for fi in FileTraverser(repo_dir).traverse():
+ pf = parser.parse_file(fi, Path(fi.abs_path).read_bytes())
+ parsed.append(pf)
+ gb.add_file(pf)
+ gb.build()
+ return gb, parsed
+
+
+async def _seed_old_build(session, repo_id: str) -> None:
+ """What the older build left: one node, one row and one edge for the set."""
+ session.add(
+ GraphNode(
+ repository_id=repo_id,
+ node_id=_OLD_ID,
+ node_type="symbol",
+ kind="method",
+ name="notNull",
+ file_path="app/Validate.java",
+ start_line=8,
+ )
+ )
+ session.add(
+ WikiSymbol(
+ repository_id=repo_id,
+ file_path="app/Validate.java",
+ symbol_id=_OLD_ID,
+ name="notNull",
+ qualified_name="app.Validate.Validate.notNull",
+ kind="method",
+ start_line=8,
+ end_line=10,
+ )
+ )
+ await batch_upsert_graph_edges(
+ session,
+ repo_id,
+ [
+ {
+ "source_node_id": "app/Caller.java::Caller::run",
+ "target_node_id": _OLD_ID,
+ "imported_names_json": "[]",
+ "edge_type": "calls",
+ "confidence": 0.9,
+ }
+ ],
+ )
+ await stamp_edges_parser_fingerprint(session, repo_id, "older-parser-build")
+
+
+async def _update(session, repo_id: str, gb: GraphBuilder, parsed: list, changed: list[str]) -> None:
+ """The persist order both update paths use."""
+ await persist_graph_nodes(session, repo_id, gb)
+ await persist_incremental_symbols(session, repo_id, parsed, changed)
+ await persist_incremental_edges(session, repo_id, gb, parsed, changed)
+ await session.commit()
+
+
+async def _ids(session, repo_id: str, column, model) -> set[str]:
+ rows = await session.execute(select(column).where(model.repository_id == repo_id))
+ return set(rows.scalars())
+
+
+async def test_first_update_rekeys_an_untouched_file_once(async_session, tmp_path) -> None:
+ repo = await insert_repo(async_session)
+ (tmp_path / "app").mkdir()
+ (tmp_path / "app" / "Validate.java").write_text(_VALIDATE)
+ (tmp_path / "app" / "Caller.java").write_text(_CALLER)
+ await _seed_old_build(async_session, repo.id)
+ await async_session.commit()
+
+ gb, parsed = _build(tmp_path)
+ # Only Caller.java changed; Validate.java is where the ids moved.
+ await _update(async_session, repo.id, gb, parsed, ["app/Caller.java"])
+
+ members = {f"{_OLD_ID}#1", f"{_OLD_ID}#2"}
+ nodes = await _ids(async_session, repo.id, GraphNode.node_id, GraphNode)
+ symbols = await _ids(async_session, repo.id, WikiSymbol.symbol_id, WikiSymbol)
+ assert _OLD_ID not in nodes and members <= nodes
+ assert _OLD_ID not in symbols and members <= symbols
+
+ edges = await async_session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(
+ GraphEdge.repository_id == repo.id, GraphEdge.edge_type == "calls"
+ )
+ )
+ pairs = set(edges.all())
+ assert ("app/Caller.java::Caller::run", f"{_OLD_ID}#1") in pairs
+ assert (f"{_OLD_ID}#1", f"{_OLD_ID}#2") in pairs
+ assert not [pair for pair in pairs if _OLD_ID in pair]
+
+ stamp = await async_session.execute(
+ select(Repository.graph_edges_parser_fingerprint).where(Repository.id == repo.id)
+ )
+ assert stamp.scalar_one() == parser_fingerprint()
+
+ # Stamped: the next update is scoped to its changed set again, so a row an
+ # untouched file holds is left exactly as it is.
+ async_session.add(
+ GraphNode(repository_id=repo.id, node_id="app/Validate.java::Validate::stray",
+ node_type="symbol", file_path="app/Validate.java")
+ )
+ await async_session.commit()
+ await _update(async_session, repo.id, gb, parsed, ["app/Caller.java"])
+ nodes = await _ids(async_session, repo.id, GraphNode.node_id, GraphNode)
+ assert "app/Validate.java::Validate::stray" in nodes
diff --git a/tests/unit/server/mcp/test_overload_symbol_lookup.py b/tests/unit/server/mcp/test_overload_symbol_lookup.py
new file mode 100644
index 000000000..0f651b820
--- /dev/null
+++ b/tests/unit/server/mcp/test_overload_symbol_lookup.py
@@ -0,0 +1,63 @@
+"""Symbol lookup across overload ids.
+
+Java and C# overloads of different arity carry ``#<parameter count>`` in their
+ids. An id held from before that change, or typed from the source name, still
+names the method: it returns every overload as one ambiguous answer, and a
+suffixed id returns exactly its member.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.persistence.models import Repository, WikiSymbol
+from repowise.server.mcp_server._symbol_lookup import resolve_symbol_rows
+
+_FILE = "src/Validate.java"
+
+
+async def _add_overloads(session) -> str:
+ repo = (await session.execute(select(Repository))).scalars().first()
+ for suffix, start in (("#1", 3), ("#2", 7)):
+ session.add(
+ WikiSymbol(
+ repository_id=repo.id,
+ file_path=_FILE,
+ symbol_id=f"{_FILE}::Validate::notNull{suffix}",
+ name="notNull",
+ qualified_name="src.Validate.Validate.notNull",
+ kind="method",
+ signature="notNull(Object obj) -> void",
+ start_line=start,
+ end_line=start + 2,
+ language="java",
+ )
+ )
+ await session.flush()
+ return repo.id
+
+
+async def test_the_plain_id_returns_the_whole_set(setup_mcp, session) -> None:
+ repo_id = await _add_overloads(session)
+ rows = await resolve_symbol_rows(session, repo_id, f"{_FILE}::Validate::notNull")
+ assert sorted(r.symbol_id for r in rows) == [
+ f"{_FILE}::Validate::notNull#1",
+ f"{_FILE}::Validate::notNull#2",
+ ]
+
+
+async def test_a_suffixed_id_returns_exactly_its_member(setup_mcp, session) -> None:
+ repo_id = await _add_overloads(session)
+ rows = await resolve_symbol_rows(session, repo_id, f"{_FILE}::Validate.notNull#2")
+ assert [r.symbol_id for r in rows] == [f"{_FILE}::Validate::notNull#2"]
+
+
+async def test_an_unknown_member_falls_back_to_the_name(setup_mcp, session) -> None:
+ """``notNull#9`` matches no row; its bare name still finds the set."""
+ repo_id = await _add_overloads(session)
+ rows = await resolve_symbol_rows(session, repo_id, f"{_FILE}::Other::notNull#9")
+ assert len(rows) == 2