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(ingestion): bind Dart calls on a dotted receiver and prefixed named constructors (#3738) (#4114)

Aman7ff3086062b8
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 470e0ab96..8b5ec269d 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -794,14 +794,19 @@ class LanguageStrategiesMixin:
call: CallSite,
caller_id: str,
) -> ResolvedCall | None:
- """``Foo.named(..)``: the class, when its body declares that constructor.
+ """``Foo.named(..)`` or ``p.Foo.named(..)``: the class, when its body declares it.
A Dart named or factory constructor is no symbol, so the call binds to
its class, as ``Foo(..)`` does. A static member of the name is a symbol
- and is left to the member tiers. Ceiling: a prefixed ``p.Foo.named(..)``
- is not captured with ``Foo`` as its receiver, so it binds nothing.
+ and is left to the member tiers. Through an import prefix the class is
+ the one the prefixed library declares, and the edge is a
+ ``module_alias`` one, as ``p.Foo(..)`` draws.
"""
- class_name = call.receiver_name or ""
+ prefix, _, class_name = (call.receiver_name or "").rpartition(".")
+ if prefix:
+ return self._resolve_dart_prefixed_constructor(
+ file_path, call, caller_id, prefix, class_name
+ )
if class_name not in self._known_type_names:
return None
hit = self._class_seen_from(file_path, caller_id, class_name, call.line)
@@ -809,6 +814,31 @@ class LanguageStrategiesMixin:
return None
return hit if call.target_name in self._dart_constructors_of(hit.callee_id) else None
+ def _resolve_dart_prefixed_constructor(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ prefix: str,
+ class_name: str,
+ ) -> ResolvedCall | None:
+ """``p.Foo.named(..)``: *prefix* must be an import prefix of the caller's file.
+
+ Only ``prefix.Class`` is read: a longer path is a field chain, not a
+ library qualifier. The class is looked up in the prefixed library and
+ what it re-exports, and must declare the constructor.
+ """
+ module_file = self._module_aliases.get(file_path, {}).get(prefix)
+ if module_file is None or "." in prefix or class_name not in self._known_type_names:
+ return None
+ declaring = self._barrel_origins.get(module_file, {}).get(class_name) or module_file
+ class_id = self._only_type_in(declaring, class_name)
+ if class_id is None or self._declares(class_id, call.target_name) is not None:
+ return None
+ if call.target_name not in self._dart_constructors_of(class_id):
+ return None
+ return ResolvedCall(caller_id, class_id, 0.88, call.line, "module_alias")
+
def _dart_constructors_of(self, class_id: str) -> frozenset[str]:
"""The named constructors the Dart class *class_id* declares, scanned once."""
found = self._dart_constructors.get(class_id)
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
index c4bc7756f..6e526b868 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/__init__.py
@@ -114,7 +114,12 @@ _NOT_A_TYPE = frozenset({"return", "throw", "new", "else", "case", "yield", "ass
# means the caller's own instance; TypeScript's ``self`` is a global, not
# ``this``. Go has no such name: its receiver is a parameter, typed from the
# body, and a ``pkg.Var`` head types nothing, so it cannot pass for ``s.field``.
-_CHAIN_SELF: dict[str, str | None] = {"python": "self", "typescript": "this", "go": None}
+_CHAIN_SELF: dict[str, str | None] = {
+ "python": "self",
+ "typescript": "this",
+ "go": None,
+ "dart": "this",
+}
# Fields walked after the head, at most: ``h.f1.f2.f3.m()``.
_MAX_CHAIN_FIELDS = 3
# A chain is only as scoped as its weakest hop.
@@ -777,7 +782,8 @@ class ReceiverTypingMixin(
"""The class *field* of *found*'s class holds, tiered by the weaker hop.
A Python field no assignment types may be a ``@property``, typed by its
- getter's return annotation.
+ getter's return annotation; a Dart one may be a getter, typed by its
+ declared return type.
"""
class_file, class_id, tier = found
fields = self._field_types_in(class_file, language).get(class_id, {})
@@ -786,12 +792,25 @@ class ReceiverTypingMixin(
hop = None if type_name is None else self._class_named(class_file, type_name, class_id)
elif language == "python":
hop = self._located(class_file, self._property_type_id(class_file, class_id, field))
+ elif language == "dart":
+ hop = self._located(class_file, self._dart_getter_type_id(class_file, class_id, field))
else:
hop = None
if hop is None:
return None
return hop[0], hop[1], max(tier, hop[2], key=_CHAIN_TIER_RANK.__getitem__)
+ def _dart_getter_type_id(self, class_file: str, class_id: str, name: str) -> str | None:
+ """The class the Dart getter *name* of *class_id* is declared to return.
+
+ Only a getter carries a bare ``name -> Type`` signature, with no
+ parameter list; a method of the name is a call, never a field read.
+ """
+ symbol = self._symbols_by_id.get(self._declares(class_id, name) or "")
+ if symbol is None or symbol.language != "dart" or "(" in (symbol.signature or ""):
+ return None
+ return self._written_returned_class(symbol, class_file)
+
def _located(self, file_path: str, type_id: str | None) -> tuple[str, str, str] | None:
"""``(file, class id, tier)`` for a class already known by id, seen from *file_path*."""
if type_id is None:
@@ -830,7 +849,25 @@ class ReceiverTypingMixin(
if type_name in self._externally_bound_names(file_path):
return None
class_id = self._only_type_in(file_path, type_name)
- return None if class_id is None else (file_path, class_id, "same_file")
+ if class_id is None:
+ return self._dart_class_seen(file_path, type_name, scope_id)
+ return file_path, class_id, "same_file"
+
+ def _dart_class_seen(
+ self, file_path: str, type_name: str, scope_id: str | None
+ ) -> tuple[str, str, str] | None:
+ """``_class_named`` for a Dart class a whole-library import brings in.
+
+ ``import 'repo.dart';`` binds no names, so the file's own free-call
+ tiers say which class a written name means. A nullable ``T?`` is the
+ class ``T``; a generic or prefixed spelling types nothing.
+ """
+ scope = self._symbols_by_id.get(scope_id or "")
+ written = type_name.rstrip("?")
+ if scope is None or scope.language != "dart" or not written.isidentifier():
+ return None
+ found = self._class_seen_from(file_path, scope.id, written, scope.start_line)
+ return None if found is None else self._located(file_path, found.callee_id)
def _only_type_in(self, file_path: str, type_name: str) -> str | None:
"""The id of the single type *file_path* declares as *type_name*."""
diff --git a/packages/core/src/repowise/core/ingestion/extractors/signatures.py b/packages/core/src/repowise/core/ingestion/extractors/signatures.py
index c62ad22cc..98911fa4e 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/signatures.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/signatures.py
@@ -54,6 +54,15 @@ def build_signature(node_type: str, name: str, params_text: str, def_node: Node,
break
returns += node_text(child, src)
return f"{name}{params_text} -> {returns}" if returns else f"{name}{params_text}"
+ if node_type == "getter_signature":
+ # Dart: the return type is the nodes ahead of ``get``. A getter takes no
+ # parameters, so it reads ``name -> Type``, with no parameter list.
+ returns = ""
+ for child in def_node.children:
+ if child.type == "get":
+ break
+ returns += node_text(child, src)
+ return f"{name} -> {returns}" if returns else name
if node_type in ("class_definition", "class_declaration", "abstract_class_declaration"):
base = f"class {name}"
if params_text:
diff --git a/packages/core/src/repowise/core/ingestion/parser/calls.py b/packages/core/src/repowise/core/ingestion/parser/calls.py
index 2fe0c5c00..0e51b4c4a 100644
--- a/packages/core/src/repowise/core/ingestion/parser/calls.py
+++ b/packages/core/src/repowise/core/ingestion/parser/calls.py
@@ -171,6 +171,30 @@ def _dart_argument_count(selector: Node | None) -> int | None:
+def _dart_receiver_path(head: Node, target: Node, src: str) -> str | None:
+ """The Dart receiver as a plain dotted path: ``r``, or ``r.item`` for ``r.item.m()``.
+
+ A Dart member access is no node of its own: the head is followed by flat
+ ``selector`` siblings, and the ones between it and the method's selector
+ are the field links. Each must be a plain ``.name``; anything else (a
+ call, an index, a ``?.`` hop) drops the site, as it does for TypeScript
+ and Python, so it never reaches the bare-call tiers.
+ """
+ method_selector = target.parent.parent if target.parent is not None else None
+ parts = [_node_text(head, src).strip()]
+ link = head.next_named_sibling
+ while link is not None and link != method_selector:
+ accessor = link.named_children[0] if link.named_child_count == 1 else None
+ if accessor is None or accessor.type != "unconditional_assignable_selector":
+ return None
+ names = [c for c in accessor.named_children if c.type == "identifier"]
+ if len(names) != 1:
+ return None
+ parts.append(_node_text(names[0], src).strip())
+ link = link.next_named_sibling
+ return ".".join(parts) if link is not None else None
+
+
# The receiver captures that are themselves a member access, by language (the
# queries widen only these two), and what a plain dotted path of names looks
# like once whitespace is gone.
@@ -415,7 +439,11 @@ def _call_names(
return None
receiver_name = None
if receiver_nodes:
- receiver_name = _receiver_text(language, receiver_nodes[0], src)
+ receiver_name = (
+ _dart_receiver_path(receiver_nodes[0], target_node, src)
+ if language == "dart"
+ else _receiver_text(language, receiver_nodes[0], src)
+ )
if receiver_name is None:
return None
if receiver_name and language == "php":
diff --git a/packages/core/src/repowise/core/ingestion/queries/dart.scm b/packages/core/src/repowise/core/ingestion/queries/dart.scm
index a8d1bb70f..b333ba264 100644
--- a/packages/core/src/repowise/core/ingestion/queries/dart.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/dart.scm
@@ -133,6 +133,95 @@
) @call.site
)
+; Method call on a field path: a.f.m(args) / a.f1.f2.m(args) / this.f.m(args),
+; up to three fields (the resolver's chain bound). Every link before the method
+; is a plain `.name` selector, so a call, an index or a `?.` hop in the run
+; matches none of these. The parser reads the field names off the siblings
+; between the head and the method's selector.
+(_
+ [(identifier) (this)] @call.receiver
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier)
+ )
+ )
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier) @call.target
+ )
+ )
+ .
+ (selector
+ (argument_part
+ (arguments) @call.arguments
+ )
+ ) @call.site
+)
+
+(_
+ [(identifier) (this)] @call.receiver
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier)
+ )
+ )
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier)
+ )
+ )
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier) @call.target
+ )
+ )
+ .
+ (selector
+ (argument_part
+ (arguments) @call.arguments
+ )
+ ) @call.site
+)
+
+(_
+ [(identifier) (this)] @call.receiver
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier)
+ )
+ )
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier)
+ )
+ )
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier)
+ )
+ )
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier) @call.target
+ )
+ )
+ .
+ (selector
+ (argument_part
+ (arguments) @call.arguments
+ )
+ ) @call.site
+)
+
; Chained on a call: a.b(args).c(args) / this.b(args).c(args) / a.b(args)?.c(args).
; The inner call's name is the receiver call; the parser reads its receiver
; and arguments off the neighbouring nodes.
diff --git a/tests/unit/ingestion/test_dart_extractors.py b/tests/unit/ingestion/test_dart_extractors.py
index 25f3b5677..a5b30d760 100644
--- a/tests/unit/ingestion/test_dart_extractors.py
+++ b/tests/unit/ingestion/test_dart_extractors.py
@@ -213,3 +213,55 @@ class Foo with M1 {}
result = parser.parse_file(_file(), src)
rels = {(r.child_name, r.kind, r.parent_name) for r in result.heritage}
assert ("Foo", "mixin", "M1") in rels
+
+
+class TestDartFieldPathCalls:
+ """``r.item.save()``: a Dart call on a dotted receiver keeps the path as its receiver."""
+
+ @staticmethod
+ def _calls(parser: ASTParser, body: str) -> list[tuple[str, str | None]]:
+ src = f"void run(Repo r, List<Repo> repos) {{\n{body}\n}}\n".encode()
+ return [(c.target_name, c.receiver_name) for c in parser.parse_file(_file(), src).calls]
+
+ @pytest.mark.parametrize(
+ ("body", "expected"),
+ [
+ ("r.item.save();", ("save", "r.item")),
+ ("this.repo.item.save();", ("save", "this.repo.item")),
+ ("r.a.b.c.save();", ("save", "r.a.b.c")), # the chain bound, three fields
+ ("p.Repo.named();", ("named", "p.Repo")),
+ ("r.close();", ("close", "r")), # a plain member call is unchanged
+ ],
+ )
+ def test_dotted_receiver_yields_one_call_site(
+ self, parser: ASTParser, body: str, expected: tuple[str, str]
+ ) -> None:
+ assert self._calls(parser, body) == [expected]
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ "r.item?.save();", # a null-aware hop
+ "r?.item.save();",
+ "repos[0].item.save();", # an index
+ "r.a.b.c.d.save();", # past the chain bound
+ ],
+ )
+ def test_receiver_that_is_not_a_plain_field_path_is_dropped(
+ self, parser: ASTParser, body: str
+ ) -> None:
+ assert self._calls(parser, body) == []
+
+ def test_call_inside_the_run_is_left_to_the_return_type_lane(self, parser: ASTParser) -> None:
+ assert ("save", "r.item") not in self._calls(parser, "r.item(1).save();")
+
+ def test_getter_signature_carries_the_declared_type(self, parser: ASTParser) -> None:
+ src = (
+ b"class Repo {\n Item get current => Item();\n"
+ b" Item? get maybe => null;\n int get n => 1;\n}\n"
+ )
+ signatures = {s.name: s.signature for s in parser.parse_file(_file(), src).symbols}
+
+ assert signatures["current"] == "current -> Item"
+ assert signatures["maybe"] == "maybe -> Item?"
+ assert signatures["n"] == "n -> int"
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index 4aca1a07b..6fa0d037a 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -1147,3 +1147,109 @@ def test_kotlin_chain_whose_inner_call_cannot_be_described_is_not_a_site(
parsed = _parse(tmp_path, "a.kt", "kotlin", text)
assert not [c for c in parsed["a.kt"].calls if c.target_name == "send"]
+
+
+_DART_FIELD_REPO = (
+ "class Item {\n void save() {}\n}\n"
+ "class Repo {\n"
+ " Repo();\n"
+ " Repo.fromJson(Object json);\n"
+ " factory Repo.load(String path) => Repo();\n"
+ " static Repo parse(String text) => Repo();\n"
+ " final Item item = Item();\n"
+ " Item get current => Item();\n"
+ " void close() {}\n"
+ "}\n"
+ # Same-named free functions: a mis-read of the receiver would land here.
+ "void parse() {}\nvoid save() {}\nvoid close() {}\n"
+)
+_DART_PREFIXED = "import 'repo.dart' as p;"
+
+
+def _dart_field_edges(
+ tmp_path: Path, body: str, imports: str = "import 'repo.dart';"
+) -> set[tuple[int, str, str]]:
+ """``(line, callee, origin)`` for the calls of ``App.run`` holding *body*."""
+ app = (
+ f"{imports}\n"
+ "class App {\n final Repo repo;\n App(this.repo);\n"
+ f" void run(Repo r, List<Repo> repos) {{\n{body}\n }}\n}}\n"
+ )
+ parsed = _parse(tmp_path, "repo.dart", "dart", _DART_FIELD_REPO)
+ parsed |= _parse(tmp_path, "app.dart", "dart", app)
+ for imp in parsed["app.dart"].imports:
+ imp.resolved_file = "repo.dart"
+ resolver = CallResolver(parsed, {"app.dart": {"repo.dart"}, "repo.dart": set()})
+ return {
+ (rc.line - 5, rc.callee_id, rc.origin)
+ for rc in resolver.resolve_file("app.dart", parsed["app.dart"].calls)
+ if rc.caller_id == "app.dart::App::run"
+ }
+
+
+ "body",
+ [
+ "r.item.save();", # a field of a parameter
+ "repo.item.save();", # a field of the caller's class
+ "this.repo.item.save();", # a field of a field
+ "r.current.save();", # a getter, typed by its declared return type
+ "repo.current.save();",
+ ],
+)
+def test_dart_field_path_binds_the_method_of_the_last_fields_class(
+ tmp_path: Path, body: str
+) -> None:
+ edges = _dart_field_edges(tmp_path, body)
+
+ assert (1, "repo.dart::Item::save", "receiver_chain_import") in edges
+
+
+ "body",
+ [
+ "r.item.close();", # the field's class lacks the method
+ "r.unknown.save();", # no such field
+ "r.item.item.save();", # a second hop that is untyped
+ "r.item?.save();", # a null-aware hop is not captured
+ "r?.item.save();",
+ "repos[0].item.save();", # an index is no field
+ "r.close.save();", # a method is not a field
+ "r.parse.save();",
+ ],
+)
+def test_dart_field_path_without_a_typed_hop_binds_nothing(tmp_path: Path, body: str) -> None:
+ """No hop untyped, and no free function of the method's name is a stand-in."""
+ assert _dart_field_edges(tmp_path, body) == set()
+
+
[email protected]("method", ["fromJson", "load"])
+def test_dart_prefixed_named_constructor_binds_its_class(tmp_path: Path, method: str) -> None:
+ edges = _dart_field_edges(tmp_path, f"p.Repo.{method}(1);", _DART_PREFIXED)
+
+ assert edges == {(1, "repo.dart::Repo", "module_alias")}
+
+
+ "body",
+ [
+ "p.Repo.nope();", # no such constructor
+ "q.Repo.fromJson(1);", # ``q`` is neither a prefix nor a typed name
+ "p.Repo.parse('y');", # a static member never binds to the free ``parse``
+ "p.Nope.fromJson(1);", # the prefixed library has no such class
+ "p.item.save();", # a prefix is not a variable the field walk starts from
+ "q.Repo.close();",
+ ],
+)
+def test_dart_prefixed_call_that_names_no_constructor_binds_nothing(
+ tmp_path: Path, body: str
+) -> None:
+ assert _dart_field_edges(tmp_path, body, _DART_PREFIXED) == set()
+
+
+def test_dart_unprefixed_named_constructor_and_prefixed_plain_one_still_bind(
+ tmp_path: Path,
+) -> None:
+ edges = _dart_field_edges(tmp_path, "Repo.fromJson(1);\np.Repo();", _DART_PREFIXED)
+
+ assert (2, "repo.dart::Repo", "module_alias") in edges