Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(graph): stop the repo-wide receiver tier answering for foreign types (#1893)
Raghav Chamadiya330ad6fa13ca
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 466e472c2..ae01c0719 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -31,7 +31,7 @@ from typing import Anyimport structlog-from .language_data import get_builtin_methods+from .language_data import get_builtin_methods, get_external_receiver_typesfrom .languages.receiver_types import (FRAMEWORK_DECORATOR_LANGUAGES,IMPLICIT_FIELD_LANGUAGES,@@ -317,6 +317,7 @@ class CallResolver:# {file: {name: type}} — module-level defs a framework decorator retyped.self._framework_types: dict[str, dict[str, str]] = {}self._external_names: dict[str, frozenset[str]] = {}+ self._repo_rebound_names: dict[str, frozenset[str]] = {}self._method_name_set: frozenset[str] | None = Noneself._framework_name_set: frozenset[str] | None = None@@ -1259,6 +1260,8 @@ class CallResolver: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")+ if self._answers_for_a_foreign_type(file_path, receiver_name):+ return Nonereturn ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_global")# Strategy 3: receiver is "self" or "this" — look in same class.@@ -1601,6 +1604,59 @@ class CallResolver:self._external_names[file_path] = namesreturn names+ def _answers_for_a_foreign_type(self, file_path: str, receiver_name: str) -> bool:+ """Is the repo-wide tier about to answer a call on a type we do not own?++ Asked only of the ``global`` tier, which takes the first file-order+ match for a ``(type, method)`` pair with no uniqueness check. A+ repository that writes ``impl RelationshipSourceCollection for+ Vec<Entity>`` declares a ``Vec::new``, and without this the tier hands+ it to every ``Vec::new()`` in the tree whatever the element type is.++ The narrower tiers above are deliberately left alone: both are grounded+ in the caller's own file or its imports, and a same-file ``impl+ From<LocalIndex> for usize`` really is what ``usize::from(i)`` means+ there.+ """+ if receiver_name not in get_external_receiver_types(+ self._language_of(file_path) or ""+ ):+ return False+ return receiver_name not in self._names_rebound_from_a_repo_package(file_path)++ def _names_rebound_from_a_repo_package(self, file_path: str) -> frozenset[str]:+ """Names this file imports from one of the repository's own packages.++ A file writing ``use bevy_platform::collections::HashMap`` means its own+ ``HashMap``, so the repo answer is right and the refusal above must not+ fire. The import list is what separates that from+ ``use std::collections::HashMap`` two files away; the name cannot.++ Read off the raw import statements because a rust import resolves to no+ repository file at all - measured 0 of 843 candidate rows - so+ ``_import_names`` cannot answer this. The package index is what does,+ and the exemption is only ever as good as the one the language has: a+ language given a non-empty ``external_receiver_types`` without a+ workspace index would refuse where it should exempt.+ """+ cached = self._repo_rebound_names.get(file_path)+ if cached is not None:+ return cached++ packages = self._get_rust_crate_src() # keys are already `-`-normalised+ found: set[str] = set()+ parsed = self._parsed_files.get(file_path)+ for imp in parsed.imports if parsed and packages else ():+ head = imp.module_path.split("::")[0].replace("-", "_")+ if head in packages:+ found.update(n for n in (imp.local_names or ()) if n)++ names = frozenset(found)+ if len(self._repo_rebound_names) >= _SOURCE_CACHE_FILES:+ self._repo_rebound_names.clear()+ self._repo_rebound_names[file_path] = names+ return names+def _declared_types_in(self,file_path: str,diff --git a/packages/core/src/repowise/core/ingestion/language_data.py b/packages/core/src/repowise/core/ingestion/language_data.pyindex 991e7d686..afe8005bf 100644--- a/packages/core/src/repowise/core/ingestion/language_data.py+++ b/packages/core/src/repowise/core/ingestion/language_data.py@@ -59,3 +59,9 @@ def get_builtin_types(language: str) -> frozenset[str]:"""Return the type names that never resolve to a repo-declared symbol."""spec = REGISTRY.get(language)return spec.builtin_types if spec else frozenset()+++def get_external_receiver_types(language: str) -> frozenset[str]:+ """Return the type names the repo-wide receiver tier must not answer for."""+ spec = REGISTRY.get(language)+ return spec.external_receiver_types if spec else frozenset()diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.pyindex 6122e29c9..3e2d0b9a2 100644--- a/packages/core/src/repowise/core/ingestion/languages/spec.py+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py@@ -154,6 +154,17 @@ class LanguageSpec:# that set is matched receiver-blind in the parser and drops the call site# outright, which would also delete a real ``obj.unwrap()`` edge.builtin_methods: frozenset[str] = field(default_factory=frozenset)+ # Type names a call may be made ON that this repository does not own:+ # ``Vec::new()``, ``HashMap::default()``. Read only by the repo-wide+ # receiver tier in ``CallResolver``, which has no uniqueness gate, so a+ # repository that writes ``impl SomeTrait for Vec<Entity>`` otherwise hands+ # that method back for every ``Vec`` in the tree whatever its element type.+ #+ # Deliberately its own field rather than a reuse of ``builtin_types``,+ # which answers a different question - whether a *type reference* can point+ # at a repo file - and is populated for nine languages. Keeping them apart+ # is what makes this change a no-op on every language but the one measured.+ external_receiver_types: frozenset[str] = field(default_factory=frozenset)# -- Display ---------------------------------------------------------color_hex: str = "#8b5cf6" # fallback purple ("other")diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py b/packages/core/src/repowise/core/ingestion/languages/specs/rust.pyindex 5d5ea6788..140499c1e 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/rust.py@@ -2,6 +2,22 @@from ..spec import LanguageSpec+# Primitives plus the prelude names a file may use without importing them. Read+# by two spec fields below, which ask different questions of the same list.+_PRELUDE_TYPES = frozenset(+ {+ "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize",+ "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64",+ "String", "Vec", "Option", "Result", "Box", "Arc", "Rc",+ "HashMap", "HashSet", "BTreeMap", "BTreeSet", "Cow",+ "Pin", "Future", "Send", "Sync", "Sized", "Copy", "Clone",+ "Debug", "Display", "Default", "Iterator", "IntoIterator",+ "From", "Into", "TryFrom", "TryInto", "AsRef", "AsMut",+ "Fn", "FnMut", "FnOnce", "Drop", "Deref", "DerefMut",+ "Self", "self",+ }+)+SPEC = LanguageSpec(tag="rust",display_name="Rust",@@ -98,19 +114,12 @@ SPEC = LanguageSpec(# so a type reference to one can never point at a file this repo declares.# Wider than ``builtin_parents``: that set only has to cover what may sit in# an impl clause, this one every position a type may be written in.- builtin_types=frozenset(- {- "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize",- "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64",- "String", "Vec", "Option", "Result", "Box", "Arc", "Rc",- "HashMap", "HashSet", "BTreeMap", "BTreeSet", "Cow",- "Pin", "Future", "Send", "Sync", "Sized", "Copy", "Clone",- "Debug", "Display", "Default", "Iterator", "IntoIterator",- "From", "Into", "TryFrom", "TryInto", "AsRef", "AsMut",- "Fn", "FnMut", "FnOnce", "Drop", "Deref", "DerefMut",- "Self", "self",- }- ),+ builtin_types=_PRELUDE_TYPES,+ # The same names, read for a different question: may a repo symbol answer a+ # call written ON one of these. Measured on bevy at 21 wrong of 28 hand-read+ # (M64); the seven correct ones are all a file that rebound the name from a+ # workspace crate, which the resolver exempts by reading the import list.+ external_receiver_types=_PRELUDE_TYPES,# Prelude constructors and std trait methods. Every one is in scope in# every file without an import, so a bare-name guess that answers one with# a repo symbol is answering for the standard library — `Ok(())` bound todiff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.pyindex b045e8a96..807e73d3c 100644--- a/tests/unit/ingestion/test_call_resolver_strategies.py+++ b/tests/unit/ingestion/test_call_resolver_strategies.py@@ -645,3 +645,78 @@ class TestImportedTypeThroughAReExport:for origin in origins.values()]assert not [o for o in recorded if o.startswith("external:")]+++class TestForeignReceiverTypes:+ """The repo-wide receiver tier must not answer a call on a type we do not own.++ Both tests write the *same* call. Only the import differs, which is the+ whole claim: the name cannot decide this and the caller's import list can.+ """++ @staticmethod+ def _workspace(tmp_path: Path) -> None:+ (tmp_path / "Cargo.toml").write_text(+ '[workspace]\nmembers = ["crates/a", "crates/b"]\n'+ )+ for name in ("a", "b"):+ crate = tmp_path / "crates" / name+ crate.mkdir(parents=True, exist_ok=True)+ (crate / "Cargo.toml").write_text(+ f'[package]\nname = "{name}"\nversion = "0.1.0"\n'+ )++ _DECLARES = (+ "rust",+ "pub struct HashMap;\n\nimpl HashMap {\n pub fn new() -> Self {\n"+ " HashMap\n }\n}\n",+ )++ def test_a_std_named_receiver_gets_no_repo_wide_guess(self, tmp_path: Path) -> None:+ self._workspace(tmp_path)+ parsed = _parse_all(+ tmp_path,+ {+ "crates/a/src/lib.rs": self._DECLARES,+ "crates/b/src/lib.rs": (+ "rust",+ "use std::collections::HashMap;\n\npub fn run() {\n"+ " let m = HashMap::new();\n}\n",+ ),+ },+ )+ assert _edges(parsed, tmp_path) == []++ def test_the_same_call_resolves_when_the_file_rebinds_the_name(+ self, tmp_path: Path+ ) -> None:+ self._workspace(tmp_path)+ parsed = _parse_all(+ tmp_path,+ {+ "crates/a/src/lib.rs": self._DECLARES,+ "crates/b/src/lib.rs": (+ "rust",+ "use a::HashMap;\n\npub fn run() {\n"+ " let m = HashMap::new();\n}\n",+ ),+ },+ )+ assert (+ "crates/b/src/lib.rs::run",+ "crates/a/src/lib.rs::HashMap::new",+ 0.75,+ "receiver_global",+ ) in _edges(parsed, tmp_path)++ def test_no_other_language_carries_the_set(self) -> None:+ """The refusal is a no-op elsewhere by construction, not by measurement."""+ from repowise.core.ingestion.language_data import get_external_receiver_types+ from repowise.core.ingestion.languages.registry import REGISTRY++ populated = {+ spec.tag+ for spec in REGISTRY.all_specs()+ if get_external_receiver_types(spec.tag)+ }+ assert populated == {"rust"}diff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.pyindex 34bb0b4a1..9a0b22455 100644--- a/tests/unit/test_no_bare_type_name_copies.py+++ b/tests/unit/test_no_bare_type_name_copies.py@@ -72,9 +72,10 @@ _KNOWN: dict[str, int] = {# separator is ours rather than the language's, so the shared helper would# be answering about a type where these ask about an ID. `models.py` holds# the one both resolvers used to duplicate. Six of `call_resolver.py`'s- # seven are symbol IDs; the seventh takes the tail of an import's module- # path, which is a module name, not a type.- _PREFIX + "call_resolver.py": 7,+ # eight are symbol IDs; the other two are both an import's module path,+ # which is a module name and not a type: one takes its tail and one takes+ # its head, to ask whether the package it names is one of ours.+ _PREFIX + "call_resolver.py": 8,_PREFIX + "models.py": 1,# Reads the head to decide whether taking a bare name is safe at all: a# qualifier that is a type rather than a package must not be discarded.