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): give Java same-arity overloads and enum-constant methods their own node (#3616)

Swati Ahuja49d7b732bc2c
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index d6789dd7f..c26666b9c 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -64,7 +64,7 @@ from .return_types import (
signature_parameter_count,
signature_parameter_range,
)
-from .symbol_identity import id_segment_name, split_symbol_id
+from .symbol_identity import id_segment_name, pair_overloads, split_symbol_id
from .type_names import (
csharp_extension_receiver,
is_resolvable_type_name,
@@ -610,7 +610,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
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():
+ if payload is not None and payload[0].isdigit():
members[base].append(sym)
representatives: dict[str, str] = {}
for overloads in members.values():
@@ -630,27 +630,49 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""Pair each member of a declared overload set with its definition.
``_link_declarations`` pairs a declared set with a defined one by their
- representatives; the other members pair here by parameter count, so
- each declaration records its definition. The definition also admits
+ representatives; the members pair here by parameter count and types
+ (``pair_overloads``), so each declaration records its definition, even
+ when the source defines one plain-id member. The definition also admits
the defaults its declaration writes: C++ writes them on the header
declaration only, so ``f(int, int)`` alone would refuse the one-argument
call ``f(int, int = 0)`` admits.
"""
+ symbols = self._symbols_by_id
for declared, defined in list(self._decl_to_def.items()):
declared_members = self._overload_members.get(declared, ())
+ if not declared_members:
+ continue
defined_members = self._overload_members.get(defined, ())
- by_count = {split_symbol_id(member)[1]: member for member, _ in defined_members}
- floors: dict[str, int] = {}
- for member, (fewest, _most) in declared_members:
- target = by_count.get(split_symbol_id(member)[1])
- if target is not None:
- self._decl_to_def.setdefault(member, target)
- floors[target] = min(fewest, floors.get(target, fewest))
- if floors:
- self._overload_members[defined] = tuple(
- (member, (min(fewest, floors.get(member, fewest)), most))
- for member, (fewest, most) in defined_members
- )
+ pairs = pair_overloads(
+ [symbols[member] for member, _ in declared_members],
+ [symbols[member] for member, _ in defined_members] or [symbols[defined]],
+ )
+ for member, target in pairs.items():
+ self._decl_to_def[member] = target
+ # The representative was linked by name alone; a definition its own
+ # signature does not reach belongs to another member.
+ if pairs and declared not in pairs:
+ del self._decl_to_def[declared]
+ if defined_members:
+ self._carry_declared_floors(defined, declared_members, pairs)
+
+ def _carry_declared_floors(
+ self,
+ defined: str,
+ declared_members: tuple[tuple[str, tuple[int, int | None]], ...],
+ pairs: dict[str, str],
+ ) -> None:
+ """Lower each paired definition's fewest arguments to its declaration's."""
+ floors: dict[str, int] = {}
+ for member, (fewest, _most) in declared_members:
+ target = pairs.get(member)
+ if target is not None:
+ floors[target] = min(fewest, floors.get(target, fewest))
+ if floors:
+ self._overload_members[defined] = tuple(
+ (member, (min(fewest, floors.get(member, fewest)), most))
+ for member, (fewest, most) in self._overload_members[defined]
+ )
def _index_extension_methods(
self, candidates: dict[tuple[str, str], set[tuple[str, str]]]
diff --git a/packages/core/src/repowise/core/ingestion/dispatch_edges.py b/packages/core/src/repowise/core/ingestion/dispatch_edges.py
index 036df56ba..9c17bd958 100644
--- a/packages/core/src/repowise/core/ingestion/dispatch_edges.py
+++ b/packages/core/src/repowise/core/ingestion/dispatch_edges.py
@@ -29,7 +29,7 @@ from collections import defaultdict
import structlog
from .heritage_resolver import heritage_ancestors
-from .symbol_identity import id_segment_name, symbol_id_discriminator
+from .symbol_identity import id_segment_name, symbol_id_arity
log = structlog.get_logger(__name__)
@@ -104,9 +104,13 @@ def _is_constructor(name: str, type_id: str) -> bool:
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)
+ """False only when both are overload members of different arities.
+
+ Parameter types are not compared: a generic base's ``T`` erases apart from
+ the ``String`` its implementation writes.
+ """
+ base_arity = symbol_id_arity(base)
+ impl_arity = symbol_id_arity(impl)
return base_arity is None or impl_arity is None or base_arity == impl_arity
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 3d4ba8cdd..c22e1a224 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -290,7 +290,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
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,
+ # one erase to one signature: the first declared keeps the node,
# so its span does not depend on how many follow it.
elif (
existing is not None
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 86cadf102..16e6a9727 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -1370,6 +1370,35 @@ def _parse_tree(
return root, parse_errors, grammar_tag, language
+def _parent_type_name(ancestor: Node, src: str) -> str | None:
+ """The name a class/impl ancestor gives its members, without type arguments."""
+ name_node = ancestor.child_by_field_name("name") or (
+ ancestor.child_by_field_name("type") # Rust impl_item
+ )
+ if name_node is None:
+ return None
+ # For Rust impl blocks with generic types (e.g. impl<T> Foo<T>),
+ # extract only the base type name, not the full generic signature.
+ if name_node.type in ("generic_type", "scoped_type_identifier"):
+ inner = name_node.child_by_field_name(
+ "type" if name_node.type == "generic_type" else "name"
+ )
+ if inner and inner.type == "type_identifier":
+ name_node = inner
+ return _node_text(name_node, src)
+
+
+def _java_enum_constant(def_node: Node, config: LanguageConfig, src: str) -> str | None:
+ """The enum constant whose body declares *def_node*, before any enclosing type."""
+ ancestor = def_node.parent
+ while ancestor is not None and ancestor.type not in config.parent_class_types:
+ if ancestor.type == "enum_constant":
+ name = ancestor.child_by_field_name("name")
+ return _node_text(name, src) if name else None
+ ancestor = ancestor.parent
+ return None
+
+
class ASTParser:
"""Unified AST parser — works for all languages via .scm query files.
@@ -1728,15 +1757,15 @@ class ASTParser:
params_nodes = capture_dict.get("symbol.params", [])
params_text = _node_text(params_nodes[0], src) if params_nodes else ""
- sym_id = (
- f"{file_info.path}::{parent_name}::{name}"
- if parent_name
- else f"{file_info.path}::{name}"
- )
+ # The id scope adds a Java enum constant to its parent, so each
+ # constant's override is its own node while the enum stays its owner.
+ constant = _java_enum_constant(def_node, config, src) if language == "java" else None
+ scope = f"{parent_name}::{constant}" if parent_name and constant else parent_name
+ sym_id = f"{file_info.path}::{scope}::{name}" if scope else f"{file_info.path}::{name}"
symbol = Symbol(
id=sym_id,
name=name,
- qualified_name=_build_qualified_name(file_info.path, parent_name, name),
+ qualified_name=_build_qualified_name(file_info.path, scope, name),
kind=kind, # type: ignore[arg-type]
signature=build_signature(node_type, name, params_text, def_node, src),
start_line=start_line,
@@ -1861,21 +1890,9 @@ class ASTParser:
ancestor = def_node.parent
while ancestor is not None:
if ancestor.type in config.parent_class_types:
- name_node = ancestor.child_by_field_name("name") or (
- ancestor.child_by_field_name("type") # Rust impl_item
- )
- if name_node:
- # For Rust impl blocks with generic types (e.g. impl<T> Foo<T>),
- # extract only the base type name, not the full generic signature.
- if name_node.type == "generic_type":
- inner = name_node.child_by_field_name("type")
- if inner and inner.type == "type_identifier":
- name_node = inner
- elif name_node.type == "scoped_type_identifier":
- inner = name_node.child_by_field_name("name")
- if inner and inner.type == "type_identifier":
- name_node = inner
- return _node_text(name_node, src)
+ name = _parent_type_name(ancestor, src)
+ if name is not None:
+ return name
ancestor = ancestor.parent
return None
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index 0cb7ea35c..617ae8001 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -285,7 +285,7 @@ def _qualified_cpp_parent(name_node: Node, src: str) -> str | None:
def _build_qualified_name(file_path: str, parent_name: str | None, name: str) -> str:
module = Path(file_path).with_suffix("").as_posix().replace("/", ".")
if parent_name:
- return f"{module}.{parent_name}.{name}"
+ return f"{module}.{parent_name.replace('::', '.')}.{name}"
return f"{module}.{name}"
diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.py
index 127ee4773..e8c37d5f0 100644
--- a/packages/core/src/repowise/core/ingestion/return_types.py
+++ b/packages/core/src/repowise/core/ingestion/return_types.py
@@ -22,7 +22,7 @@ def declared_return_type(signature: str) -> str | None:
_PAIRS = {"(": ")", "[": "]", "{": "}", "<": ">"}
-def _top_level_parameters(signature: str) -> list[str] | None:
+def signature_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. A
@@ -56,7 +56,7 @@ def _top_level_parameters(signature: str) -> list[str] | None:
def signature_parameter_count(signature: str) -> int | None:
"""Count top-level parameters in a stored callable signature."""
- parameters = _top_level_parameters(signature)
+ parameters = signature_parameters(signature)
return None if parameters is None else len(parameters)
@@ -67,7 +67,7 @@ def signature_parameter_range(signature: str, language: str) -> tuple[int, int |
top open, a C# or 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)
+ parameters = signature_parameters(signature)
if parameters is None:
return None
texts = [text.strip() for text in parameters]
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
index 4d5dea144..fc89aae00 100644
--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -7,7 +7,10 @@ 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.
+ narrows to the member whose parameters admit its argument count. Members
+ that share a count also carry their erased parameter types,
+ ``StringUtil.java::StringUtil::append#1(String)``, so an inserted overload
+ never renames its siblings.
- ``#<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.
@@ -27,10 +30,13 @@ from collections import defaultdict
from collections.abc import Callable, Iterable
from .models import Symbol
-from .return_types import signature_parameter_count
+from .return_types import signature_parameter_count, signature_parameters
+from .type_names import strip_type_arguments
-# The payload after ``#``: a parameter count, or a build-variant predicate.
-_PAYLOAD = re.compile(r"\d+|[A-Za-z_]\w*\(.*\)")
+# The payload after ``#``: a parameter count with optional parameter types, or
+# a build-variant predicate.
+_PAYLOAD = re.compile(r"\d+(?:\([^()]*\))?|[A-Za-z_]\w*\(.*\)")
+_COUNT = re.compile(r"\d+")
_GENERIC_ARITY = re.compile(r"`\d+$")
@@ -57,6 +63,20 @@ def symbol_id_discriminator(symbol_id: str) -> str | None:
return split_symbol_id(symbol_id)[1]
+def symbol_id_arity(symbol_id: str) -> str | None:
+ """The discriminator without its parameter types: ``put#1(String)`` -> ``1``."""
+ payload = symbol_id_discriminator(symbol_id)
+ count = _COUNT.match(payload) if payload else None
+ return count.group() if count else payload
+
+
+def untyped_symbol_id(symbol_id: str) -> str:
+ """*symbol_id* with its parameter types dropped: ``put#1(String)`` -> ``put#1``."""
+ base, payload = split_symbol_id(symbol_id)
+ count = _COUNT.match(payload) if payload else None
+ return f"{base}#{count.group()}" if count else symbol_id
+
+
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("#")
@@ -83,6 +103,50 @@ def _parameter_count(symbol: Symbol) -> str | None:
return None if count is None else str(count)
+# Words in a parameter that are not its type, and builtin words a type may end
+# on (``unsigned int`` has no name to drop).
+_PARAMETER_MODIFIERS = frozenset(
+ {"final", "const", "volatile", "mutable", "register", "struct", "class", "enum",
+ "typename", "ref", "out", "in", "params", "this", "scoped", "readonly"}
+)
+_BUILTIN_TYPE_WORDS = frozenset(
+ {"signed", "unsigned", "short", "long", "int", "char", "double", "float", "bool", "void"}
+)
+_WORD = re.compile(r"[A-Za-z_$][\w$]*(?:(?:\.|::)[A-Za-z_$][\w$]*)*")
+_TYPE_MARKS = re.compile(r"\*|&&?|\[\s*,*\s*\]|\.\.\.|\?")
+_ANNOTATION = re.compile(r"@[\w.]+(?:\([^)]*\))?")
+# ``(*cb)`` in ``void (*cb)(int)``: the pointer marks, then the parameter name.
+_FUNCTION_DECLARATOR = re.compile(r"\(\s*([*&^]+)\s*[\w$]*\s*\)")
+
+
+def _erased_parameter_type(parameter: str) -> str:
+ """``final Map<K, V> m`` -> ``Map``, ``const std::string& s`` -> ``string&``.
+
+ Type arguments, qualifiers, modifiers, defaults and the parameter name
+ go; array, pointer, reference and nullable marks stay, so ``vector<int*>``
+ erases apart from ``vector<int>``. Varargs read as the array they are, and
+ a function pointer as its return type plus ``fn``. The result never holds
+ ``.``, ``/`` or ``::``, which id consumers split names on.
+ """
+ text = _ANNOTATION.sub(" ", parameter).partition("=")[0]
+ pointer = _FUNCTION_DECLARATOR.search(strip_type_arguments(text))
+ if pointer is not None:
+ return _erased_parameter_type(text[: text.find("(")]) + pointer.group(1) + "fn"
+ words = [w for w in _WORD.findall(strip_type_arguments(text)) if w not in _PARAMETER_MODIFIERS]
+ if len(words) > 1 and words[-1] not in _BUILTIN_TYPE_WORDS:
+ words.pop()
+ marks = "".join(
+ "[]" if m == "..." else re.sub(r"[\s,]", "", m) for m in _TYPE_MARKS.findall(text)
+ )
+ return "_".join(re.split(r"\.|::", w)[-1] for w in words) + marks
+
+
+def _parameter_types(symbol: Symbol) -> str:
+ """``(String,int[])``: the erased types that split a same-count overload."""
+ parameters = signature_parameters(symbol.signature or "") or []
+ return "(" + ",".join(_erased_parameter_type(p) for p in parameters) + ")"
+
+
# 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]] = {
@@ -109,9 +173,10 @@ def symbol_discriminator(symbol: Symbol) -> str | None:
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.
+ Members that share a parameter count are told apart by their erased
+ parameter types; members equal on both (a C++ declaration and its
+ definition) stay one id. 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:
@@ -125,6 +190,8 @@ def disambiguate_colliding_ids(symbols: list[Symbol], language: str) -> None:
if len(members) < 2:
continue
keyed = [(symbol, discriminator(symbol)) for symbol in members]
+ if discriminator is _parameter_count:
+ keyed = _split_same_counts(keyed)
if len({key for _, key in keyed if key is not None}) < 2:
continue
for symbol, key in keyed:
@@ -132,6 +199,53 @@ def disambiguate_colliding_ids(symbols: list[Symbol], language: str) -> None:
symbol.id = f"{base}#{key}"
+def _split_same_counts(keyed: list[tuple[Symbol, str | None]]) -> list[tuple[Symbol, str | None]]:
+ """Append parameter types to every count two members share, when they differ."""
+ typed: dict[str, dict[int, str]] = defaultdict(dict)
+ for index, (symbol, key) in enumerate(keyed):
+ if key is not None:
+ typed[key][index] = f"{key}{_parameter_types(symbol)}"
+ out = list(keyed)
+ for by_index in typed.values():
+ if len(set(by_index.values())) > 1:
+ for index, key in by_index.items():
+ out[index] = (keyed[index][0], key)
+ return out
+
+
+def pair_overloads(declared: list[Symbol], defined: list[Symbol]) -> dict[str, str]:
+ """``{declared id: defined id}``: by count and erased types, then by count.
+
+ The count alone pairs only where each side has one unpaired member of it,
+ which covers a type spelled two ways (``size_t`` and ``unsigned long``).
+ """
+ by_key: dict[str | None, dict[str, str]] = defaultdict(dict)
+ for symbol in defined:
+ by_key[_parameter_count(symbol)].setdefault(_parameter_types(symbol), symbol.id)
+ pairs: dict[str, str] = {}
+ left: dict[str | None, list[Symbol]] = defaultdict(list)
+ for symbol in declared:
+ target = by_key[_parameter_count(symbol)].get(_parameter_types(symbol))
+ if target is None:
+ left[_parameter_count(symbol)].append(symbol)
+ else:
+ pairs[symbol.id] = target
+ pairs.update(_pair_by_count(left, by_key, set(pairs.values())))
+ return pairs
+
+
+def _pair_by_count(
+ left: dict[str | None, list[Symbol]], by_key: dict[str | None, dict[str, str]], taken: set[str]
+) -> dict[str, str]:
+ """Pair a count each side has exactly one unpaired member of."""
+ pairs: dict[str, str] = {}
+ for count, members in left.items():
+ free = set(by_key.get(count, {}).values()) - taken
+ if count is not None and len(members) == 1 and len(free) == 1:
+ pairs[members[0].id] = free.pop()
+ return pairs
+
+
def _split_generic_types(symbols: list[Symbol]) -> None:
"""Suffix a generic type that shares its id with a sibling of another arity.
@@ -174,7 +288,10 @@ __all__ = [
"has_overload_identity",
"id_segment_name",
"overload_sets",
+ "pair_overloads",
"split_symbol_id",
"symbol_discriminator",
+ "symbol_id_arity",
"symbol_id_discriminator",
+ "untyped_symbol_id",
]
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index 85c09ea00..da3370faf 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -74,7 +74,13 @@ STORE_FORMAT_VERSION: int = 2
#: v7: code naming Alembic gets a framework edge to every migration it can
#: load, and a VS Code extension test to the entry its package declares; the
#: first update writes those edges for unchanged files too.
-PARSER_SCHEMA_VERSION: int = 7
+#:
+#: v8: Java, C# and C++ overloads of one arity carry their erased parameter
+#: types (``put#1(String)``, ``put#1(int)``), and a method in a Java enum
+#: constant's body sits under the constant (``Op::PLUS::apply``); the first
+#: update re-keys those symbols and graph nodes. A Swift ``extension`` is an
+#: ``impl``, no longer a ``class``.
+PARSER_SCHEMA_VERSION: int = 8
#: state.json key holding the store format version that wrote the store.
STORE_FORMAT_VERSION_KEY = "store_format_version"
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 6020655ea..f6adfaf7d 100644
--- a/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
+++ b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
@@ -19,7 +19,11 @@ 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.ingestion.symbol_identity import (
+ base_symbol_id,
+ id_segment_name,
+ untyped_symbol_id,
+)
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
@@ -204,7 +208,9 @@ async def resolve_symbol_rows(session, repo_id: str, symbol_id: str) -> list[Wik
# 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.
+ # ``notNull#2``); they answer only when no row matches exactly. A
+ # count-only id (``put#1``) also reads the members typed under it
+ # (``put#1(String)``).
variants = symbol_id_variants(symbol_id)
res = await session.execute(
select(WikiSymbol).where(
@@ -212,15 +218,18 @@ async def resolve_symbol_rows(session, repo_id: str, symbol_id: str) -> list[Wik
or_(
WikiSymbol.symbol_id.in_(variants),
*(
- WikiSymbol.symbol_id.like(f"{escape_like(sid)}#%", escape=LIKE_ESCAPE)
+ WikiSymbol.symbol_id.like(f"{escape_like(sid)}{tail}%", escape=LIKE_ESCAPE)
for sid in variants
+ for tail in ("#", "(")
),
),
)
)
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
+ row
+ for row in found
+ if base_symbol_id(row.symbol_id) in variants or untyped_symbol_id(row.symbol_id) in variants
]
if rows:
return order_candidates(rows, file_path)
diff --git a/tests/unit/ingestion/test_overload_identity.py b/tests/unit/ingestion/test_overload_identity.py
index da3214f04..f66f8744a 100644
--- a/tests/unit/ingestion/test_overload_identity.py
+++ b/tests/unit/ingestion/test_overload_identity.py
@@ -7,9 +7,13 @@ 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.
+Overloads of one arity also carry their erased parameter types,
+``put#1(String)``. A Java enum constant's body methods sit under the constant,
+``Op::PLUS::apply``.
+
+The controls: a name declared once keeps its plain id, members equal in count
+and types (a C++ declaration and its definition) stay one node, and a language
+without a registered discriminator is untouched.
"""
from __future__ import annotations
@@ -26,10 +30,13 @@ 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 (
+ _erased_parameter_type,
base_symbol_id,
id_segment_name,
overload_sets,
split_symbol_id,
+ symbol_id_arity,
+ untyped_symbol_id,
)
from repowise.core.ingestion.traverser import FileTraverser
from repowise.core.ingestion.type_names import type_argument_count
@@ -205,18 +212,99 @@ class TestJavaOverloads:
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:
+ def test_overloads_of_one_arity_split_by_erased_parameter_types(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"
+ " public void put(final java.util.Map<String, Integer> m, @Nullable Object... rest) { }\n"
+ " public void put(char k[], long v) { }\n"
+ " public void put(String k, int v, int w) { }\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
+ node = graph.nodes["P.java::P::put#1(int)"]
+ assert (node["start_line"], node["signature"]) == (3, "put(int k) -> void")
+ assert {
+ "P.java::P::put#1(String)",
+ # Varargs read as the array they are: no ``.`` in an id payload.
+ "P.java::P::put#2(Map,Object[])",
+ "P.java::P::put#2(char[],long)",
+ # A count no sibling shares keeps the bare count.
+ "P.java::P::put#3",
+ } <= set(graph)
+ assert split_symbol_id("P.java::P::put#2(char[],long)") == ("P.java::P::put", "2(char[],long)")
+ assert symbol_id_arity("P.java::P::put#2(char[],long)") == "2"
+ assert id_segment_name("put#2(char[],long)") == "put"
+ assert bare_name("P.java::P::put#2(Map,Object[])") == "put"
+ assert untyped_symbol_id("P.java::P::put#2(char[],long)") == "P.java::P::put#2"
+
+ @pytest.mark.parametrize(
+ ("parameter", "erased"),
+ [
+ ("Object... rest", "Object[]"),
+ ("final java.util.Map<String, Integer> m", "Map"),
+ ("void (*cb)(int, int)", "void*fn"),
+ ("int (&row)[4]", "int&fn"),
+ ("...", "[]"),
+ ("Args&&... args", "Args&&[]"),
+ ("const std::vector<ns::T*>& v", "vector*&"),
+ ("@a.b.C(x = \"/p.q\") String s", "String"),
+ ("unsigned long n", "unsigned_long"),
+ ],
+ )
+ def test_an_erased_parameter_type_never_holds_a_name_separator(
+ self, parameter: str, erased: str
+ ) -> None:
+ got = _erased_parameter_type(parameter)
+ assert got == erased
+ assert not any(sep in got for sep in (".", "/", "::", "(", ")", "#"))
+
+ def test_an_inserted_overload_renames_no_sibling(self) -> None:
+ body = " void put(String k) { }\n void put(int k) { }\n"
+ before = set(_ids(_parse("P.java", "java", "class P {\n" + body + "}\n")))
+ after = set(_ids(_parse("P.java", "java", "class P {\n void put(long k) { }\n" + body + "}\n")))
+ assert before < after
+
+ def test_enum_constant_bodies_get_their_own_methods(self, tmp_path: Path) -> None:
+ text = (
+ "public enum Op {\n"
+ " PLUS { int apply(int a, int b) { return a + b; } },\n"
+ " MINUS { int apply(int a, int b) { return negate(b) + a; } };\n"
+ " abstract int apply(int a, int b);\n"
+ " static int negate(int x) { return -x; }\n"
+ "}\n"
+ )
+ by_id = {s.id: s for s in _parse("Op.java", "java", text).symbols}
+ assert {"Op.java::Op::PLUS::apply", "Op.java::Op::MINUS::apply", "Op.java::Op::apply"} <= set(by_id)
+ assert by_id["Op.java::Op::MINUS::apply"].qualified_name == "Op.Op.MINUS.apply"
+ # The enum stays the owner: its node holds every constant's method.
+ assert by_id["Op.java::Op::MINUS::apply"].parent_name == "Op"
+ graph = _graph({"Op.java": ("java", text)})
+ assert graph.has_edge("Op.java::Op", "Op.java::Op::PLUS::apply")
+ assert graph["Op.java::Op"]["Op.java::Op::PLUS::apply"]["edge_type"] == "has_method"
+ edges = _edges(tmp_path, {"Op.java": ("java", text)})
+ assert ("Op.java::Op::MINUS::apply", "Op.java::Op::negate") in edges
+
+ def test_a_same_arity_call_keeps_the_representative_and_callers_keep_their_ids(
+ self, tmp_path: Path
+ ) -> None:
+ text = (
+ "public class S {\n"
+ " public S append(String s) { return emit(s); }\n"
+ " public S append(char c) { return emit(String.valueOf(c)); }\n"
+ " S emit(String s) { return this; }\n"
+ " void use() { append('x'); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"S.java": ("java", text)})
+ base = "S.java::S::"
+ # Each overload's own call is attributed to its own node.
+ assert (base + "append#1(String)", base + "emit") in edges
+ assert (base + "append#1(char)", base + "emit") in edges
+ # A count cannot choose between them: the set's representative, the
+ # first declared, answers, as the shared node did before.
+ assert {c for a, c in edges if a == base + "use"} == {base + "append#1(String)"}
def test_a_record_keeps_its_canonical_constructor_beside_an_overload(self) -> None:
text = (
@@ -333,6 +421,18 @@ class TestCSharpGenericSiblings:
assert ("C.cs::C::Two", "H.cs::H::Sum#3") in edges
assert ("C.cs::C::Four", "H.cs::H::Sum#2") in edges
+ def test_csharp_same_arity_constructors_get_their_own_nodes(self) -> None:
+ text = (
+ "namespace App;\npublic class P {\n"
+ " public P(string name) { }\n"
+ " public P(TimeSpan? delay) { }\n"
+ " public P(int[] ids) { }\n"
+ " public P() { }\n"
+ "}\n"
+ )
+ ids = set(_ids(_parse("P.cs", "csharp", text)))
+ assert {"P.cs::P::P#1(string)", "P.cs::P::P#1(TimeSpan?)", "P.cs::P::P#1(int[])", "P.cs::P::P#0"} <= ids
+
SHAPES_H = """namespace geo {
class Shape {
@@ -370,8 +470,8 @@ class TestCppOverloads:
ids = set(_ids(_parse("shapes.h", "cpp", SHAPES_H)))
base = "shapes.h::Shape::"
assert {base + "Shape#0", base + "Shape#2", base + "scale#1", base + "scale#2"} <= ids
- # Same arity stays one id: template overloads and const overloads.
- assert {base + "put", base + "area"} <= ids
+ # Same arity splits by parameter type; const overloads erase alike.
+ assert {base + "put#1(T)", base + "put#1(T*)", base + "area"} <= ids
assert base + "once" in ids
def test_an_in_class_declaration_and_its_inline_definition_share_an_id(self) -> None:
@@ -421,6 +521,33 @@ class TestCppOverloads:
assert graph.nodes["util.h::pad#3"]["defined_by"] == "util.cpp::pad#3"
assert graph.has_edge("main.cpp::main", "util.cpp::pad#3")
+ @pytest.mark.parametrize("header_first", [True, False])
+ def test_a_member_pairs_with_a_plain_id_definition(self, tmp_path: Path, header_first: bool) -> None:
+ decls = ["int f(int a);", "int f(long a);"]
+ if not header_first:
+ decls.reverse()
+ (tmp_path / "f.h").write_text("\n".join(decls) + "\n")
+ (tmp_path / "f.cpp").write_text('#include "f.h"\nint f(int x) { return x; }\n')
+ graph = self._build(tmp_path)
+ assert graph.nodes["f.h::f#1(int)"]["defined_by"] == "f.cpp::f"
+ assert not graph.nodes["f.h::f#1(long)"].get("defined_by")
+
+ def test_a_type_spelled_two_ways_pairs_by_count(self, tmp_path: Path) -> None:
+ (tmp_path / "g.h").write_text("int g(int a);\nint g(size_t n);\n")
+ (tmp_path / "g.cpp").write_text(
+ '#include "g.h"\nint g(int a) { return a; }\nint g(unsigned long n) { return 0; }\n'
+ )
+ graph = self._build(tmp_path)
+ assert graph.nodes["g.h::g#1(int)"]["defined_by"] == "g.cpp::g#1(int)"
+ assert graph.nodes["g.h::g#1(size_t)"]["defined_by"] == "g.cpp::g#1(unsigned_long)"
+
+ @staticmethod
+ def _build(root: Path):
+ builder = GraphBuilder(repo_path=root)
+ for info in FileTraverser(root).traverse():
+ builder.add_file(_PARSER.parse_file(info, Path(info.abs_path).read_bytes()))
+ return builder.build()
+
def test_a_set_split_between_header_and_source_keeps_its_pairing(self, tmp_path: Path) -> None:
"""One overload inline in the header, one in the .cpp: the .cpp body takes the call."""
caller = '#include "shapes.h"\nvoid draw(geo::Shape& s) {\n s.scale(2, 3);\n}\n'
diff --git a/tests/unit/server/mcp/test_overload_symbol_lookup.py b/tests/unit/server/mcp/test_overload_symbol_lookup.py
index 0f651b820..cea1ad0f8 100644
--- a/tests/unit/server/mcp/test_overload_symbol_lookup.py
+++ b/tests/unit/server/mcp/test_overload_symbol_lookup.py
@@ -61,3 +61,30 @@ async def test_an_unknown_member_falls_back_to_the_name(setup_mcp, session) -> N
repo_id = await _add_overloads(session)
rows = await resolve_symbol_rows(session, repo_id, f"{_FILE}::Other::notNull#9")
assert len(rows) == 2
+
+
+async def test_a_count_only_id_returns_the_members_typed_under_it(setup_mcp, session) -> None:
+ """``notNull#1`` held from before same-count overloads carried their types."""
+ repo = (await session.execute(select(Repository))).scalars().first()
+ for suffix, start in (("#1(Object)", 3), ("#1(String)", 7), ("#2", 11)):
+ 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()
+ rows = await resolve_symbol_rows(session, repo.id, f"{_FILE}::Validate::notNull#1")
+ assert sorted(r.symbol_id for r in rows) == [
+ f"{_FILE}::Validate::notNull#1(Object)",
+ f"{_FILE}::Validate::notNull#1(String)",
+ ]