Skip to content

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

feat(graph): resolve a call on a local by typing it from its declaration (#1639)

Raghav Chamadiya58395f4f48c6
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 38e9ef576..9a929f134 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -25,11 +25,18 @@ per strategy, and it is what the edge carries.
from __future__ import annotations
from collections import defaultdict
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
+from pathlib import Path
from typing import Any
import structlog
+from .languages.receiver_types import (
+ RECEIVER_TYPE_LANGUAGES,
+ Declaration,
+ scan_declarations,
+ types_in_span,
+)
from .models import (
CallSite,
NamedBinding,
@@ -51,16 +58,21 @@ class _LanguageCallStrategies:
"""What a language resolves that the language-neutral tiers cannot.
``free`` runs after the same-file tier and before the import tiers;
- ``member`` runs before every receiver strategy. Both stop at the first hit.
+ ``member`` runs before every receiver strategy; ``member_fallback`` runs
+ after all of them, so a strategy there only ever sees a call nothing else
+ claimed and can only add an edge. All three stop at the first hit.
Strategies are named rather than bound so a probe can substitute one.
"""
free: tuple[str, ...] = ()
member: tuple[str, ...] = ()
+ member_fallback: tuple[str, ...] = ()
_NO_LANGUAGE_STRATEGIES = _LanguageCallStrategies()
+_TYPED_RECEIVER = ("_resolve_typed_receiver",)
+
_JVM_STRATEGIES = _LanguageCallStrategies(
free=("_resolve_jvm_same_package",),
member=("_resolve_jvm_receiver_same_package",),
@@ -75,12 +87,19 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
free=("_resolve_go_same_package",),
member=("_resolve_go_package_call",),
),
- "java": _JVM_STRATEGIES,
+ # Kotlin shares the JVM tiers but not the typed-receiver fallback: it has
+ # no declaration shapes yet, so registering it would promise a resolution
+ # the language gate immediately declines.
+ "java": replace(_JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER),
"kotlin": _JVM_STRATEGIES,
+ "csharp": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
"cpp": _CPP_STRATEGIES,
"c": _CPP_STRATEGIES,
}
+_SOURCE_CACHE_FILES = 4
+_BODY_TYPE_CACHE_ENTRIES = 2048
+
@dataclass(frozen=True, slots=True)
class ResolvedCall:
@@ -96,9 +115,14 @@ class ResolvedCall:
class CallResolver:
"""Resolve raw CallSites to symbol-level edges.
- Constructed once per ``GraphBuilder.build()`` call with the full set
- of parsed files and import edges. Stateless after construction —
- ``resolve_file()`` can be called concurrently for different files.
+ Constructed once per ``GraphBuilder.build()`` call with the full set of
+ parsed files and import edges, then driven one file at a time.
+
+ ``resolve_file()`` is **not** safe to call concurrently. Several lazy
+ caches are filled during resolution, and the capped ones evict wholesale.
+ Every cached value is a pure function of state fixed at construction, so a
+ race would cost recomputation rather than a wrong answer, but the eviction
+ makes concurrent use pointless as well as unsupported.
"""
def __init__(
@@ -156,6 +180,18 @@ class CallResolver:
# Lazy per-file set of (line, target) that also carry a receiver.
self._member_shaped: dict[str, set[tuple[int, str]]] = {}
+ # Receiver typing reads source text, so both caches are capped rather
+ # than per-repo: files resolve one at a time, so a few slots always
+ # hit, and the cap is what keeps a whole repo's source out of memory.
+ # Scanning is memoised per *function*, not per reference — one scan
+ # answers every unresolved receiver in a body.
+ self._source_text: dict[str, str] = {}
+ self._declarations: dict[str, tuple[Declaration, ...]] = {}
+ self._symbol_spans: dict[str, dict[str, tuple[int, int]]] = {}
+ self._body_types: dict[tuple[str, str], dict[str, str]] = {}
+ self._external_names: dict[str, frozenset[str]] = {}
+ self._method_name_set: frozenset[str] | None = None
+
# Barrel re-export origins: {barrel_file: {name: origin_file}}
self._barrel_origins: dict[str, dict[str, str]] = defaultdict(dict)
@@ -818,31 +854,15 @@ class CallResolver:
)
# Strategies 2 and 2b: the receiver names a class that declares the
- # method — in this file, in an imported one, or anywhere at all. No
- # class declares the pair unless the global method index holds it, and
- # that check also keeps the merged-import view from being built for a
- # pair that cannot be in it.
- key = (receiver_name, method_name)
- if key in self._global_methods:
- file_methods = self._file_methods.get(file_path, {})
- if key in file_methods:
- return ResolvedCall(
- caller_id, file_methods[key], 0.93, call.line, "receiver_same_file"
- )
-
- merged_methods = self._merged_methods_for(file_path)
- if key in merged_methods:
- return ResolvedCall(
- caller_id, merged_methods[key], 0.88, call.line, "receiver_import"
- )
-
- # Trait method dispatch — the method may be defined on a trait's
- # impl block in another file. The global index preserves
- # file-insertion match order; the caller's own file is skipped.
- for _path, sym_id in self._global_methods[key]:
- if _path == file_path:
- continue
- return ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_global")
+ # method — in this file, in an imported one, or anywhere at all.
+ match = self._receiver_pair_match(file_path, (receiver_name, method_name))
+ if match is not None:
+ sym_id, tier = match
+ if tier == "same_file":
+ return ResolvedCall(caller_id, sym_id, 0.93, call.line, "receiver_same_file")
+ if tier == "import":
+ return ResolvedCall(caller_id, sym_id, 0.88, call.line, "receiver_import")
+ return ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_global")
# Strategy 3: receiver is "self" or "this" — look in same class.
# Only the caller's own file can hold the match, so index straight
@@ -854,11 +874,224 @@ class CallResolver:
if sym_id is not None and sym_id != caller_id:
return ResolvedCall(caller_id, sym_id, 0.95, call.line, "self_scope")
- # No further fallback: any (class, method) pair present in any file's
- # method index was already resolved by strategy 2 (same file) or 2b
- # (global method index), which are built from the same symbols.
+ # Last: the receiver may be a local or parameter, which names no class
+ # at all. Everything above has already declined it.
+ for strategy in self._strategies_for(file_path).member_fallback:
+ hit = getattr(self, strategy)(file_path, call, caller_id)
+ if hit is not None:
+ return hit
+
+ return None
+
+ def _receiver_pair_match(
+ self,
+ file_path: str,
+ key: tuple[str, str],
+ ) -> tuple[str, str] | None:
+ """The symbol a ``(class, method)`` pair names, and the scope that held it.
+
+ No class declares the pair unless the global method index holds it, and
+ that check also keeps the merged-import view from being built for a
+ pair that cannot be in it.
+ """
+ if key not in self._global_methods:
+ return None
+
+ file_methods = self._file_methods.get(file_path, {})
+ if key in file_methods:
+ return file_methods[key], "same_file"
+
+ merged_methods = self._merged_methods_for(file_path)
+ if key in merged_methods:
+ return merged_methods[key], "import"
+
+ # Trait method dispatch — the method may be defined on a trait's impl
+ # block in another file. The global index preserves file-insertion
+ # match order; the caller's own file is skipped.
+ for path, sym_id in self._global_methods[key]:
+ if path != file_path:
+ return sym_id, "global"
+
return None
+ def _resolve_typed_receiver(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """Resolve ``local.method()`` by typing the local from its declaration.
+
+ Emits nothing unless the inferred type declares the method, which is
+ what makes a text scan safe: a mis-inference reaches no index and
+ yields no edge.
+ """
+ receiver_name = call.receiver_name or ""
+ # Lowercase-initial only. A capitalised receiver already names a type
+ # and every tier above has tried it; an underscore one is a field,
+ # whose declaration is not in this body.
+ if not receiver_name[:1].islower() or receiver_name in ("self", "this"):
+ return None
+
+ parsed = self._parsed_files.get(file_path)
+ language = parsed.file_info.language if parsed else ""
+ if language not in RECEIVER_TYPE_LANGUAGES:
+ return None
+
+ # Scanning a body is the expensive half, so refuse before it rather
+ # than after. Nothing here can resolve unless some class declares a
+ # method of this name; the gate above only proves some *symbol* does,
+ # which a free function satisfies.
+ if call.target_name not in self._method_names():
+ return None
+
+ type_name = self._declared_types_in(file_path, caller_id, language).get(receiver_name)
+ if type_name is None:
+ return None
+ key = (type_name, call.target_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)
+ if bound is not None and not bound.startswith("external:"):
+ sym_id = self._file_methods.get(bound, {}).get(key)
+ if sym_id is None:
+ return None
+ return ResolvedCall(caller_id, sym_id, 0.88, call.line, "receiver_typed_import")
+
+ # Bound to something outside the repo and there is no edge to find,
+ # however many local classes share the simple name. A compatibility
+ # test that imports a third-party `Cache` is otherwise read as calling
+ # ours, and it looks right in every sample that does not check imports.
+ if type_name in self._externally_bound_names(file_path):
+ return None
+
+ # The caller's own file first. A nested class here outranks a
+ # same-named one in a package sibling, which is the whole ambiguity in
+ # a repo that keeps near-duplicate implementations side by side.
+ sym_id = self._file_methods.get(file_path, {}).get(key)
+ if sym_id is not None:
+ return ResolvedCall(caller_id, sym_id, 0.93, call.line, "receiver_typed_same_file")
+
+ # Only the JVM registers both a member strategy and this fallback, so
+ # the scope that answers here is its same-package one. A second
+ # language pairing the two needs an origin word of its own.
+ typed_call = replace(call, receiver_name=type_name)
+ for strategy in self._strategies_for(file_path).member:
+ hit = getattr(self, strategy)(file_path, typed_call, caller_id)
+ if hit is not None:
+ return ResolvedCall(
+ caller_id,
+ hit.callee_id,
+ 0.90,
+ call.line,
+ "receiver_typed_same_package",
+ )
+
+ match = self._receiver_pair_match(file_path, key)
+ if match is None:
+ return None
+ sym_id, tier = match
+ if tier == "import":
+ return ResolvedCall(caller_id, sym_id, 0.88, call.line, "receiver_typed_import")
+ return ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_typed_global")
+
+ def _method_names(self) -> frozenset[str]:
+ """Every name declared as a method of some class, built once."""
+ if self._method_name_set is None:
+ self._method_name_set = frozenset(method for _, method in self._global_methods)
+ return self._method_name_set
+
+ def _externally_bound_names(self, file_path: str) -> frozenset[str]:
+ """Simple names this file imports from outside the repo.
+
+ Read off the raw import statements rather than ``_import_names``, which
+ only carries bindings that resolved to a file — precisely the ones this
+ needs to exclude.
+ """
+ names = self._external_names.get(file_path)
+ if names is not None:
+ return names
+
+ parsed = self._parsed_files.get(file_path)
+ found: set[str] = set()
+ for imp in parsed.imports if parsed else ():
+ if imp.resolved_file and not imp.resolved_file.startswith("external:"):
+ continue
+ bound = (*imp.imported_names, imp.module_path.rsplit(".", 1)[-1])
+ found.update(name for name in bound if name and name != "*")
+
+ names = frozenset(found)
+ if len(self._external_names) >= _SOURCE_CACHE_FILES:
+ self._external_names.clear()
+ self._external_names[file_path] = names
+ return names
+
+ def _declared_types_in(
+ self,
+ file_path: str,
+ caller_id: str,
+ language: str,
+ ) -> dict[str, str]:
+ """``{name: type}`` for the body of one function."""
+ key = (file_path, caller_id)
+ types = self._body_types.get(key)
+ if types is not None:
+ return types
+
+ span = self._spans_for(file_path).get(caller_id)
+ if span is None:
+ types = {}
+ else:
+ types = types_in_span(self._declarations_for(file_path, language), *span)
+
+ if len(self._body_types) >= _BODY_TYPE_CACHE_ENTRIES:
+ self._body_types.clear()
+ self._body_types[key] = types
+ return types
+
+ def _declarations_for(self, file_path: str, language: str) -> tuple[Declaration, ...]:
+ """Every declaration in one file, scanned once however many bodies ask."""
+ found = self._declarations.get(file_path)
+ if found is None:
+ found = scan_declarations(self._text_of(file_path), language)
+ if len(self._declarations) >= _SOURCE_CACHE_FILES:
+ self._declarations.clear()
+ self._declarations[file_path] = found
+ return found
+
+ def _spans_for(self, file_path: str) -> dict[str, tuple[int, int]]:
+ """``{symbol_id: (start_line, end_line)}`` for one file."""
+ spans = self._symbol_spans.get(file_path)
+ if spans is None:
+ parsed = self._parsed_files.get(file_path)
+ spans = {s.id: (s.start_line, s.end_line) for s in (parsed.symbols if parsed else ())}
+ if len(self._symbol_spans) >= _SOURCE_CACHE_FILES:
+ self._symbol_spans.clear()
+ self._symbol_spans[file_path] = spans
+ return spans
+
+ def _text_of(self, file_path: str) -> str:
+ """One file's source, or empty if it cannot be read."""
+ text = self._source_text.get(file_path)
+ if text is not None:
+ return text
+
+ parsed = self._parsed_files.get(file_path)
+ text = ""
+ if parsed is not None:
+ try:
+ text = Path(parsed.file_info.abs_path).read_text(
+ encoding="utf-8", errors="ignore"
+ )
+ except OSError:
+ text = ""
+
+ if len(self._source_text) >= _SOURCE_CACHE_FILES:
+ self._source_text.clear()
+ self._source_text[file_path] = text
+ return text
+
def _rivals_a_class_method(symbol_id: str) -> bool:
"""Another class's ordinary method — the one shape that proves last-wins.
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
new file mode 100644
index 000000000..3624f25c6
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -0,0 +1,154 @@
+"""What type is the local a call is made on.
+
+``user.save()`` names no type, so member resolution has nothing to look up.
+The declaration that gives ``user`` its type is almost always inside the same
+function — a parameter, a local, a catch or loop binding — and the languages
+here write it as ``T name``.
+
+The scan is allowed to be wrong. Nothing it returns becomes an edge until the
+resolver has checked that the type actually declares the method, so a
+mis-inference costs a missing edge and never a wrong one. That check is what
+licenses matching declarations with a regex instead of a type checker.
+
+Split in two on purpose. ``scan_declarations`` reads a whole file once and is
+the expensive half; ``types_in_span`` narrows the result to one function body
+and is nearly free. Scanning per body instead would re-read every line that
+two spans share, and a class body contains all of its methods'.
+
+Adding a language means adding its shapes to ``_LANGUAGE_PATTERNS`` and
+nothing else; a language absent from it is excluded by construction.
+"""
+
+from __future__ import annotations
+
+import re
+from bisect import bisect_left, bisect_right
+from typing import NamedTuple
+
+from ..language_data import get_builtin_types
+from ..type_names import bare_type_name, is_resolvable_type_name, strip_type_arguments
+
+# A type as written before a declared name: optionally qualified, optionally
+# generic to two levels of nesting, optionally an array. A third level yields
+# no match, which is a deliberate ceiling — a deeper group needs a real bracket
+# matcher, and failing to type a name costs an edge, never a wrong one.
+_TYPE = r"[A-Z]\w*(?:\.\w+)*(?:<(?:[^<>]|<[^<>]*>)*>)?(?:\[\])*"
+
+# ``T name`` closed by the punctuation that can end a declaration: an
+# initialiser, a statement end, the next parameter, the end of a parameter
+# list, or an enhanced-for colon. Requiring one of those is what keeps the
+# pattern off ``(Foo) bar`` and ``foo(Bar.BAZ, qux)``, which have no space in
+# the same place.
+_TYPED_DECLARATION = re.compile(
+ rf"(?<![\w.])(?P<type>{_TYPE})\s+(?P<name>[a-z_]\w*)\s*(?=[=;,):])"
+)
+
+_INFERRED_FROM_NEW = re.compile(
+ r"(?<![\w.])var\s+(?P<name>[a-z_]\w*)\s*=\s*new\s+(?P<type>[A-Z]\w*(?:\.\w+)*)"
+)
+
+# Truncating at ``//`` also truncates a URL inside a string literal. That can
+# only ever lose a declaration, never invent one, which is the safe direction.
+_LINE_COMMENT = re.compile(r"//.*")
+
+_NEWLINE = re.compile(r"\n")
+
+_C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)
+
+_LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
+ "csharp": _C_FAMILY,
+ "java": _C_FAMILY,
+}
+
+RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)
+
+
+class Declaration(NamedTuple):
+ """One name given one type, at one line."""
+
+ line: int
+ name: str
+ type_name: str
+
+
+def _nests_in_a_builtin(raw: str, language: str) -> bool:
+ """True for ``Map.Entry`` and its kind — a member type of a builtin.
+
+ Taking the bare name of one of these answers ``Entry``, which the repo may
+ well declare somewhere and which the declaration never meant. Discarding a
+ qualifier is right when the qualifier is a package; it is wrong when the
+ qualifier is a type, and a builtin head is the case we can tell apart.
+ """
+ if "." not in raw:
+ return False
+ head, separator, _ = strip_type_arguments(raw).partition(".")
+ return bool(separator) and head in get_builtin_types(language)
+
+
+def _usable_type_name(raw: str, language: str) -> str | None:
+ """The bare name *raw* denotes, or None if it can name no repo symbol."""
+ if _nests_in_a_builtin(raw, language):
+ return None
+ name = raw if raw.isidentifier() else bare_type_name(raw)
+ return name if is_resolvable_type_name(name, language) else None
+
+
+def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
+ """Every declaration *text* makes, in line order."""
+ patterns = _LANGUAGE_PATTERNS.get(language)
+ if not patterns:
+ return ()
+
+ cleaned = _LINE_COMMENT.sub("", text)
+ # Scanned by the regex engine rather than a Python loop over characters:
+ # the loop costs more than the declaration scan it exists to serve.
+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+
+ # One file writes the same type name hundreds of times, and normalising it
+ # walks the string character by character. Resolve each spelling once.
+ resolved: dict[str, str | None] = {}
+ found: list[Declaration] = []
+ for pattern in patterns:
+ for match in pattern.finditer(cleaned):
+ raw = match.group("type")
+ if raw not in resolved:
+ resolved[raw] = _usable_type_name(raw, language)
+ type_name = resolved[raw]
+ if type_name is None:
+ continue
+ found.append(
+ Declaration(bisect_right(starts, match.start()), match.group("name"), type_name)
+ )
+
+ found.sort()
+ return tuple(found)
+
+
+def types_in_span(
+ declarations: tuple[Declaration, ...],
+ start_line: int,
+ end_line: int,
+) -> dict[str, str]:
+ """``{name: type}`` for the declarations inside one function body."""
+ types: dict[str, str] = {}
+ ambiguous: set[str] = set()
+
+ # Bisected rather than skipped over: a file's bodies each ask once, so
+ # walking from the front every time is quadratic in a large file, and that
+ # — not the regex — was what the scan actually cost.
+ first = bisect_left(declarations, start_line, key=lambda d: d.line)
+ for declaration in declarations[first:]:
+ if declaration.line > end_line:
+ break
+ if declaration.name in ambiguous:
+ continue
+ previous = types.get(declaration.name)
+ if previous is None:
+ types[declaration.name] = declaration.type_name
+ elif previous != declaration.type_name:
+ # One name declared twice with two types — a shadowing inner
+ # scope, or a line the scan misread. Neither has an answer.
+ del types[declaration.name]
+ ambiguous.add(declaration.name)
+
+ return types
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index e10c84170..5bd5b34dd 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -346,6 +346,16 @@ ResolutionOrigin = Literal[
# named for Rust trait impls but is gated on no language.
"receiver_global",
"global_unique", # 0.50 — the name is unique repo-wide. A guess.
+ # The four below reach the same scopes as their untyped twins, but through
+ # a receiver whose type was read off its declaration rather than written at
+ # the call. They share their twin's confidence deliberately: the inferred
+ # type had to declare the method before an edge was emitted, so the
+ # evidence is no weaker — what differs is how the receiver was named, and
+ # that is precisely what an origin is for.
+ "receiver_typed_same_file", # 0.93
+ "receiver_typed_same_package", # 0.90 (JVM)
+ "receiver_typed_import", # 0.88
+ "receiver_typed_global", # 0.75
]
RESOLUTION_ORIGIN_VALUES: frozenset[str] = frozenset(get_args(ResolutionOrigin))
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
new file mode 100644
index 000000000..28e2a6e7c
--- /dev/null
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -0,0 +1,137 @@
+"""What the receiver-type scan reads off a function body, and what it refuses.
+
+The refusals matter more than the matches. Every wrong type this scan returns
+is a wrong edge the resolver's validator has to catch.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.languages.receiver_types import (
+ RECEIVER_TYPE_LANGUAGES,
+ scan_declarations,
+ types_in_span,
+)
+
+
+def declared_types(body: str, language: str) -> dict[str, str]:
+ """The two halves composed over a whole body, which is what a caller sees."""
+ return types_in_span(scan_declarations(body, language), 1, 10_000)
+
+
+class TestJavaShapes:
+ def test_parameter(self) -> None:
+ body = "void run(CacheContext context, int n) { context.original(); }"
+ assert declared_types(body, "java")["context"] == "CacheContext"
+
+ def test_local_with_initialiser(self) -> None:
+ body = "void run() { LocalCache cache = build(); cache.put(k); }"
+ assert declared_types(body, "java")["cache"] == "LocalCache"
+
+ def test_bare_local(self) -> None:
+ assert declared_types("void run() { TimerWheel wheel; }", "java")["wheel"] == "TimerWheel"
+
+ def test_var_from_constructor(self) -> None:
+ body = "void run() { var buffer = new BoundedBuffer(); }"
+ assert declared_types(body, "java")["buffer"] == "BoundedBuffer"
+
+ def test_enhanced_for(self) -> None:
+ body = "void run() { for (Node n : nodes) { n.getValue(); } }"
+ assert declared_types(body, "java")["n"] == "Node"
+
+ def test_catch_binding(self) -> None:
+ body = "void run() { try { go(); } catch (LoadException e) { e.report(); } }"
+ assert declared_types(body, "java")["e"] == "LoadException"
+
+ def test_type_arguments_are_stripped(self) -> None:
+ body = "void run(AsyncCache<Int, Int> cache) { }"
+ assert declared_types(body, "java")["cache"] == "AsyncCache"
+
+ def test_nested_type_arguments(self) -> None:
+ body = "void run(Registry<Map<String, Int>> registry) { }"
+ assert declared_types(body, "java")["registry"] == "Registry"
+
+ def test_type_arguments_nested_three_deep_are_a_stated_ceiling(self) -> None:
+ """Two levels is what the pattern balances; a third yields no type.
+
+ Deliberate. A deeper group would need a real bracket matcher, and
+ failing to type a name costs an edge, never a wrong one.
+ """
+ body = "void run(Registry<Map<String, List<Int>>> registry) { }"
+ assert "registry" not in declared_types(body, "java")
+
+ def test_a_lowercase_package_qualifier_is_a_stated_ceiling(self) -> None:
+ """A fully-qualified declaration is not matched, and that is measured.
+
+ Admitting one means the type may start lowercase, which costs ~40% of
+ the scan's time on a Java-heavy repo and bought six edges on caffeine.
+ An uppercase qualifier — C#'s ``Ns.Type x`` — is still matched.
+ """
+ body = "void run(com.example.cache.Ticker ticker) { }"
+ assert "ticker" not in declared_types(body, "java")
+
+
+class TestCsharpShapes:
+ def test_parameter(self) -> None:
+ body = "public void Invoke(IOcelotLoggerFactory factory) { }"
+ assert declared_types(body, "csharp")["factory"] == "IOcelotLoggerFactory"
+
+ def test_var_from_constructor(self) -> None:
+ body = "public void Go() { var builder = new DownstreamRouteBuilder(); }"
+ assert declared_types(body, "csharp")["builder"] == "DownstreamRouteBuilder"
+
+ def test_namespace_qualified_local(self) -> None:
+ body = "public void Go() { Ocelot.Configuration.Route route = null; }"
+ assert declared_types(body, "csharp")["route"] == "Route"
+
+ def test_pattern_match_binding(self) -> None:
+ body = "public void Go() { if (thing is Placeholder p) { p.Name(); } }"
+ assert declared_types(body, "csharp")["p"] == "Placeholder"
+
+
+class TestRefusals:
+ def test_a_member_type_of_a_builtin_is_refused(self) -> None:
+ """``Map.Entry`` bare-names to ``Entry``, which some repo class has.
+
+ Discarding a qualifier is right when it is a package and wrong when it
+ is a type. A builtin head is the case that can be told apart, and it
+ produced real wrong edges before this rule existed.
+ """
+ body = "void run() { Map.Entry<Object, Object> entry = it.next(); }"
+ assert "entry" not in declared_types(body, "java")
+
+ def test_builtin_types_are_refused(self) -> None:
+ body = "void run(String name, Object value) { }"
+ assert declared_types(body, "java") == {}
+
+ def test_single_letter_type_parameter_is_refused(self) -> None:
+ body = "<T> void run(T item) { item.hash(); }"
+ assert "item" not in declared_types(body, "java")
+
+ def test_two_types_for_one_name_yields_neither(self) -> None:
+ body = "void run() { Reader source = a(); if (x) { Writer source = b(); } }"
+ assert "source" not in declared_types(body, "java")
+
+ def test_a_cast_is_not_a_declaration(self) -> None:
+ assert declared_types("void run() { var n = (Node) raw; }", "java") == {}
+
+ def test_a_qualified_constant_argument_is_not_a_declaration(self) -> None:
+ assert declared_types("void run() { call(Config.DEFAULT, other); }", "java") == {}
+
+ def test_a_declaration_in_a_line_comment_is_ignored(self) -> None:
+ assert declared_types("void run() { // a Node node; once lived here\n }", "java") == {}
+
+ def test_an_unregistered_language_yields_nothing(self) -> None:
+ body = "func run(w *TimerWheel) { }"
+ assert declared_types(body, "go") == {}
+
+
+def test_the_language_set_is_what_the_patterns_declare() -> None:
+ """Excluding a language means removing its shapes, not gating a caller."""
+ assert set(RECEIVER_TYPE_LANGUAGES) == {"csharp", "java"}
+
+
[email protected]("language", ["java", "csharp"])
+def test_an_empty_body_is_not_an_error(language: str) -> None:
+ assert declared_types("", language) == {}