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(rust): type a call receiver from its parameter, let annotation or constructor (#2800)
Raghav Chamadiya7b193906a8d3
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.pyindex 8abbaa04a..2647bbba9 100644--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py@@ -75,6 +75,9 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {"swift": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),# TypeScript's typed fallback also walks a dotted receiver's fields."typescript": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),+ # Rust types a local or parameter only; a `self.field` receiver is not+ # walked, since Rust has no `_CHAIN_SELF` row.+ "rust": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),"cpp": _CPP_STRATEGIES,"c": _CPP_STRATEGIES,}diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex 9245a7d20..ab063f3a4 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -267,6 +267,28 @@ _CPP_DECLARATION = re.compile()+# Rust annotates after the name: parameters, `let x: Foo`, closure parameters.+# A path is kept only when it starts inside the crate (`crate::`, `self::`,+# `super::`): `std::process::Child` bares to a `Child` the repo may also+# declare. A borrow (`&Foo`, `&'a mut Foo`) and a `Box<Foo>` still reach+# `Foo` by auto-deref, so both are read through; `dyn`/`impl` heads are+# lowercase and match nothing. A bare `Foo` path is still refused downstream+# when a `use` binds it outside the repo.+_RUST_TYPE = r"(?:(?:crate|self|super)::(?:\w+::)*)?[A-Z]\w*"+_RUST_ANNOTATED = re.compile(+ rf"(?<![\w.:'])(?P<name>[a-z_]\w*)\s*:\s*(?:&(?:'\w+\s+)?(?:mut\s+)?)?(?P<box>Box<)?"+ rf"(?P<type>{_RUST_TYPE}(?:<(?:[^<>]|<[^<>]*>)*>)?)(?(box)>)\s*(?=[=,;)|])"+)++# `let x = Foo::new(..)` and the other constructor-named associated functions,+# the Rust spelling of `_KT_CONSTRUCTED`. A chain is refused as there+# (`Foo::new().build()` is whatever `build` returns); a `?` is read through,+# since it unwraps the `Result<Foo>` a fallible constructor returns.+_RUST_CONSTRUCTED = re.compile(+ rf"(?<![\w.])let\s+(?:mut\s+)?(?P<name>[a-z_]\w*)\s*=\s*(?P<type>{_RUST_TYPE})"+ r"::(?:new|default|from|with_\w+)\s*\((?![^()]*\)\s*\??\s*\.)"+)+_C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)# Only the field shapes reach class scope. Go is still not in# IMPLICIT_FIELD_LANGUAGES: a field is read through its receiver (``c.parent``),@@ -284,6 +306,7 @@ _LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {"java": _C_FAMILY,"kotlin": _KT_FAMILY,"python": _PY_FAMILY,+ "rust": (_RUST_ANNOTATED, _RUST_CONSTRUCTED),"swift": _SWIFT_FAMILY,"typescript": _TS_FAMILY,}@@ -578,6 +601,7 @@ _LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {"go": _LINE_COMMENT,"java": _LINE_COMMENT,"kotlin": _LINE_COMMENT,+ "rust": _LINE_COMMENT,"swift": _LINE_COMMENT,"python": _HASH_COMMENT,"typescript": _LINE_COMMENT,diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.pyindex 1f2fc4686..e05231d09 100644--- a/tests/unit/ingestion/test_receiver_types.py+++ b/tests/unit/ingestion/test_receiver_types.py@@ -736,6 +736,7 @@ def test_the_language_set_is_what_the_patterns_declare() -> None:"java","kotlin","python",+ "rust","swift","typescript",}@@ -853,3 +854,67 @@ def test_c_has_no_shapes_of_its_own() -> None:"""assert "c" not in RECEIVER_TYPE_LANGUAGESassert scan_declarations("Widget* w;", "c") == ()+++class TestRustShapes:+ """Rust annotates after the name, and a constructor is an associated fn."""++ def test_a_parameter(self) -> None:+ assert declared_types("fn run(searcher: Searcher) {}", "rust") == {"searcher": "Searcher"}++ def test_a_borrowed_parameter_is_its_referent(self) -> None:+ body = "fn run(a: &Searcher, b: &mut Printer, c: &'a mut Sink<'a>) {}"+ assert declared_types(body, "rust") == {"a": "Searcher", "b": "Printer", "c": "Sink"}++ def test_a_boxed_parameter_is_its_contents(self) -> None:+ assert declared_types("fn run(m: Box<Matcher>) {}", "rust") == {"m": "Matcher"}++ def test_a_typed_let_and_a_closure_parameter(self) -> None:+ body = "fn run() {\n let w: Walker = make();\n let f = |p: Printer| p.go();\n}"+ assert declared_types(body, "rust") == {"w": "Walker", "p": "Printer"}++ def test_a_constructor_local(self) -> None:+ body = (+ "fn run() {\n let b = IgnoreBuilder::new();\n"+ " let mut e = PartialErrorBuilder::default();\n"+ " let g = GlobSet::from(x)?;\n let v = Buf::with_capacity(8);\n}"+ )+ assert declared_types(body, "rust") == {+ "b": "IgnoreBuilder",+ "e": "PartialErrorBuilder",+ "g": "GlobSet",+ "v": "Buf",+ }++ def test_a_crate_relative_path_is_kept(self) -> None:+ assert declared_types("fn run(m: crate::walk::Walker) {}", "rust") == {"m": "Walker"}+++class TestRustRefusals:+ def test_a_path_from_outside_the_crate_is_refused(self) -> None:+ """``std::process::Child`` would bare to a ``Child`` the repo may declare."""+ body = "fn run(c: &mut std::process::Child) {\n let p = io::Path::new(x);\n}"+ assert declared_types(body, "rust") == {}++ def test_a_trait_object_or_impl_type_is_refused(self) -> None:+ body = "fn run(w: &mut dyn Write, b: Box<dyn Sink>, i: impl Matcher) {}"+ assert declared_types(body, "rust") == {}++ def test_builtins_and_type_parameters_are_refused(self) -> None:+ body = "fn run<M>(v: Vec<Foo>, s: String, m: M, me: Self) {\n let x = Self::new();\n}"+ assert declared_types(body, "rust") == {}++ def test_a_chained_constructor_types_nothing(self) -> None:+ body = "fn run() {\n let w = WalkBuilder::new(p).hidden(false).build();\n}"+ assert declared_types(body, "rust") == {}++ def test_an_associated_fn_not_named_as_a_constructor_types_nothing(self) -> None:+ """``Glob::compile(..)`` may return anything; only constructor names are read."""+ assert declared_types("fn run() {\n let g = Glob::compile(p);\n}", "rust") == {}++ def test_a_declaration_in_a_comment_is_ignored(self) -> None:+ assert declared_types("fn run() {\n // let w: Walker = x;\n}", "rust") == {}++ def test_rust_is_not_a_field_language(self) -> None:+ """A field is read through ``self.``, a dotted receiver not walked yet."""+ assert "rust" not in IMPLICIT_FIELD_LANGUAGESdiff --git a/tests/unit/ingestion/test_rust_typed_receivers.py b/tests/unit/ingestion/test_rust_typed_receivers.pynew file mode 100644index 000000000..0284e4599--- /dev/null+++ b/tests/unit/ingestion/test_rust_typed_receivers.py@@ -0,0 +1,91 @@+"""A Rust ``x.method()`` must resolve against the type that declares ``x``.++Rust had no receiver-typing shapes, so ``b.build()`` reached only bare-name+tiers: with ``build`` declared on several types it bound to none, or to the+wrong one. A parameter, a ``let x: T`` and a ``let x = T::new(..)`` now type+the receiver, and the resolver still refuses unless ``T`` declares the method.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+++def _build(repo: Path):+ traverser = FileTraverser(repo)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in traverser.traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ return builder.build()+++def _call_targets(graph, caller: str) -> set[str]:+ return {+ str(t)+ for s, t, d in graph.edges(data=True)+ if d.get("edge_type") == "calls" and str(s) == caller+ }+++def _repo(root: Path, caller_body: str, *, signature: str = "") -> None:+ """``Builder::build``, a decoy ``Other::build``, and a same-file ``Local::build``."""+ (root / "Cargo.toml").write_text('[package]\nname = "demo"\nversion = "0.1.0"\n')+ src = root / "src"+ src.mkdir(parents=True, exist_ok=True)+ (src / "lib.rs").write_text("pub mod a;\npub mod b;\npub mod c;\n")+ (src / "a.rs").write_text(+ "pub struct Builder { n: u32 }\n"+ "impl Builder {\n"+ " pub fn new() -> Builder { Builder { n: 0 } }\n"+ " pub fn build(&self) -> u32 { self.n }\n"+ "}\n"+ )+ (src / "b.rs").write_text(+ "pub struct Other;\nimpl Other {\n pub fn build(&self) -> u32 { 1 }\n}\n"+ )+ (src / "c.rs").write_text(+ "use crate::a::Builder;\n"+ "pub struct Local;\nimpl Local {\n pub fn build(&self) -> u32 { 2 }\n}\n"+ f"pub fn run({signature}) -> u32 {{\n{caller_body}\n}}\n"+ )+++def _resolves_to_builder(root: Path) -> bool:+ return "src/a.rs::Builder::build" in _call_targets(_build(root), "src/c.rs::run")+++class TestTypedReceiverResolves:+ def test_a_constructor_local(self, tmp_path: Path) -> None:+ _repo(tmp_path, " let b = Builder::new();\n b.build()")+ assert _resolves_to_builder(tmp_path)++ def test_a_typed_let(self, tmp_path: Path) -> None:+ _repo(tmp_path, " let b: Builder = make();\n b.build()")+ assert _resolves_to_builder(tmp_path)++ def test_a_borrowed_parameter(self, tmp_path: Path) -> None:+ _repo(tmp_path, " b.build()", signature="b: &mut Builder")+ assert _resolves_to_builder(tmp_path)++ def test_a_boxed_parameter(self, tmp_path: Path) -> None:+ _repo(tmp_path, " b.build()", signature="b: Box<Builder>")+ assert _resolves_to_builder(tmp_path)++ def test_it_does_not_answer_with_a_same_named_method_elsewhere(self, tmp_path: Path) -> None:+ _repo(tmp_path, " b.build()", signature="b: &Builder")+ targets = _call_targets(_build(tmp_path), "src/c.rs::run")+ assert not any("Other" in t or "Local" in t for t in targets)+++class TestUntypedReceiverRefuses:+ def test_an_external_type_resolves_nothing(self, tmp_path: Path) -> None:+ """``std::process::Child`` is not the repo's type, whatever it declares."""+ _repo(tmp_path, " b.build()", signature="b: &std::process::Child")+ assert not any("build" in t for t in _call_targets(_build(tmp_path), "src/c.rs::run"))++ def test_a_chained_constructor_resolves_nothing(self, tmp_path: Path) -> None:+ _repo(tmp_path, " let b = Builder::new().into_other();\n b.build()")+ assert not _resolves_to_builder(tmp_path)