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): bind Dart named constructors and type chained calls by return type (#3701)

Swati Ahuja13df59a4cd4c
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 35b80fa5d..8b5746058 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -10,8 +10,14 @@ import re
from dataclasses import dataclass, replace
from typing import Any
-from .call_receiver_typing import _FUNCTION_KINDS, _TYPE_KINDS
+from .call_receiver_typing import (
+ _BODY_TYPE_CACHE_ENTRIES,
+ _FUNCTION_KINDS,
+ _TYPE_KINDS,
+ _store_capped,
+)
from .lang_helpers.kotlin_lambdas import in_lambda
+from .languages.receiver_types import dart_named_constructors
from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
from .symbol_identity import outer_scope
@@ -25,7 +31,9 @@ class _LanguageCallStrategies:
``free`` runs after the same-file tier and before the import tiers;
``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.
+ claimed and can only add an edge. ``constructor`` runs ahead of ``member``,
+ even for a name no symbol carries, since a named constructor is no symbol.
+ All four stop at the first hit.
Strategies are named rather than bound so a probe can substitute one.
``member_bare_fallback`` lets a member or chained call nothing claimed fall
@@ -35,6 +43,7 @@ class _LanguageCallStrategies:
"""
free: tuple[str, ...] = ()
+ constructor: tuple[str, ...] = ()
member: tuple[str, ...] = ()
member_fallback: tuple[str, ...] = ()
member_bare_fallback: bool = True
@@ -97,11 +106,18 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
"kotlin": replace(_JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER),
"csharp": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
"python": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
- # Swift and Dart register the fallback and nothing else: neither has a
- # package tier of its own, so a typed receiver is looked for in the
- # caller's file, in what the file imports, and then in the global pair index.
+ # Swift and Dart register the fallback: neither has a package tier of its
+ # own, so a typed receiver is looked for in the caller's file, in what the
+ # file imports, and then in the global pair index. A Dart chained call is
+ # resolved by its inner call's return type or not at all: on pub its bare
+ # name bound `File(p).statSync()` and `.then()` to repo functions. The
+ # flag reaches chains only, since no Dart member call has a bare twin.
"swift": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
- "dart": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
+ "dart": _LanguageCallStrategies(
+ constructor=("_resolve_dart_named_constructor",),
+ member_fallback=_TYPED_RECEIVER,
+ member_bare_fallback=False,
+ ),
# 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
@@ -128,6 +144,8 @@ class LanguageStrategiesMixin:
# {Kotlin function id: the type it extends, or None}
self._kotlin_receivers: dict[str, str | None] = {}
+ # {Dart class id: the named constructors its body declares}
+ self._dart_constructors: dict[str, frozenset[str]] = {}
# JVM same-package resolution (lazy JvmWorkspaceIndex)
self._jvm_index: Any = None
@@ -518,6 +536,38 @@ class LanguageStrategiesMixin:
return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")
return None
+ def _resolve_dart_named_constructor(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ ) -> ResolvedCall | None:
+ """``Foo.named(..)``: the class, when its body declares that constructor.
+
+ 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.
+ """
+ class_name = call.receiver_name or ""
+ if class_name not in self._known_type_names:
+ return None
+ hit = self._class_seen_from(file_path, caller_id, class_name, call.line)
+ if hit is None or self._declares(hit.callee_id, call.target_name) is not None:
+ return None
+ return hit if call.target_name in self._dart_constructors_of(hit.callee_id) else None
+
+ 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)
+ if found is None:
+ class_file = self._symbol_paths_by_id.get(class_id, "")
+ start, end = self._spans_for(class_file).get(class_id, (1, 0))
+ body = "\n".join(self._text_of(class_file).splitlines()[start - 1 : end])
+ found = dart_named_constructors(body, self._symbols_by_id[class_id].name)
+ _store_capped(self._dart_constructors, class_id, found, _BODY_TYPE_CACHE_ENTRIES)
+ return found
+
def _lacks_extension_receiver(self, file_path: str, call: CallSite, callee_id: str) -> bool:
"""Is *callee_id* a Kotlin extension this bare call has no receiver for?
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
index a94638c49..e03cad8c0 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -1335,16 +1335,17 @@ class ReceiverTypingMixin:
return self._returned_type_id(resolved.callee_id, awaited)
def _returned_type_id(self, callee_id: str, awaited: bool = False) -> str | None:
- """The repository type a go call to *callee_id* yields, as a symbol id.
+ """The repository type a call to *callee_id* yields, as a symbol id.
- ``T`` is looked up in the callee's own package and ``pkg.T`` in the
+ A go ``T`` is looked up in the callee's own package and ``pkg.T`` in the
package the callee's file imports as ``pkg``; exactly one type there
must carry the name. A slice, map or external type yields None.
A Python return annotation must be one bare class name, quoted or not,
read in the callee's file as a chain hop reads a field's type. A
property is read, not called, and an ``async def`` returns a coroutine
- unless the call is *awaited*.
+ unless the call is *awaited*. Any other language's declared return
+ type is read by ``_written_returned_class``.
"""
symbol = self._symbols_by_id.get(callee_id)
path = self._symbol_paths_by_id.get(callee_id)
@@ -1352,8 +1353,17 @@ class ReceiverTypingMixin:
return None
if symbol.kind in _TYPE_KINDS:
return callee_id # a conversion, ``T(x)``
- if symbol.language != "python":
+ if symbol.language == "go":
return self._go_returned_type_id(symbol, path)
+ if symbol.language == "python":
+ return self._python_call_returns(symbol, path, awaited)
+ return self._written_returned_class(symbol, path)
+
+ def _python_call_returns(self, symbol: Symbol, path: str, awaited: bool) -> str | None:
+ """``_returned_type_id`` for a Python function.
+
+ A property or an unawaited coroutine types nothing.
+ """
if is_property_accessor(symbol.decorators) or (symbol.is_async and not awaited):
return None
return self._python_returned_class(symbol, path)
@@ -1380,6 +1390,39 @@ class ReceiverTypingMixin:
]
return found[0] if len(found) == 1 else None
+ def _written_returned_class(self, symbol: Symbol, path: str) -> str | None:
+ """The class *symbol*'s declared return type names, as its file *path* sees it.
+
+ One unqualified class name, nullable or not. Ceiling: a generic
+ (``Result<T>``) or prefixed (``p.Foo``) return type types nothing.
+ """
+ raw = declared_return_type(symbol.signature or "")
+ written = raw.rstrip("?") if raw else ""
+ if not written.isidentifier():
+ return None
+ found = self._class_seen_from(path, symbol.id, written, symbol.start_line)
+ return None if found is None else found.callee_id
+
+ def _class_seen_from(
+ self, file_path: str, scope_id: str, name: str, line: int
+ ) -> ResolvedCall | None:
+ """The edge a bare ``name(..)`` in *scope_id* draws, when it lands on a class.
+
+ The tiers a constructor call takes say which class a name means in a
+ file. A repository-wide guess is no evidence of that and is not taken.
+ """
+ probe = CallSite(
+ target_name=name,
+ receiver_name=None,
+ caller_symbol_id=scope_id,
+ line=line,
+ argument_count=None,
+ )
+ hit = self._resolve_free_call(file_path, probe, scope_id)
+ if hit is None or "global" in hit.origin:
+ return None
+ return hit if self._symbols_by_id[hit.callee_id].kind in _TYPE_KINDS else None
+
def _python_returned_class(self, symbol: Symbol, path: str) -> str | None:
"""The class id *symbol*'s return annotation names, read in *path*.
@@ -1420,11 +1463,11 @@ class ReceiverTypingMixin:
"""``x.m()`` where ``x`` holds the type *type_id*, bound by identity.
A go method may sit in any file of its type's package, so the method
- is looked for across that package, not only the type's own file. A
- Python method is the one its class declares.
+ is looked for across that package, not only the type's own file. Any
+ other language's method is the one its class declares.
"""
- if self._symbols_by_id[type_id].language == "python":
- return self._python_typed_call(file_path, call, caller_id, type_id)
+ if self._symbols_by_id[type_id].language != "go":
+ return self._class_typed_call(file_path, call, caller_id, type_id)
hit = self._package_method(type_id, call.target_name)
if hit is None or hit[1] == caller_id:
return None
@@ -1438,10 +1481,10 @@ class ReceiverTypingMixin:
tier = "import"
return self._body_typed_call(caller_id, sym_id, tier, call.line)
- def _python_typed_call(
+ def _class_typed_call(
self, file_path: str, call: CallSite, caller_id: str, type_id: str
) -> ResolvedCall | None:
- """``_call_typed_receiver`` for a Python class: no package tier."""
+ """``_call_typed_receiver`` for a class: no package tier."""
hit = self._located(file_path, self._declares(type_id, call.target_name))
if hit is None or hit[1] == caller_id:
return None
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 6eb52b4cb..5fd6e6a51 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -160,9 +160,13 @@ _EXTENSION_KINDS = frozenset({"impl"})
# Languages admitted to the full return-type chain lane; each is admitted
# explicitly, once measured.
PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset(
- {"cpp", "csharp", "go", "java", "python"}
+ {"cpp", "csharp", "dart", "go", "java", "python"}
)
+# Chain languages that type the inner call by the identity of the type it
+# returns (``_returned_type_id``); the rest read its type name.
+_RETURNED_TYPE_ID_LANGUAGES = frozenset({"dart", "go", "python"})
+
# Chain lanes that need a file or import/re-export identity for the head type:
# a repository-global simple type name is not a language binding.
_BOUND_CHAIN_LANGUAGES = frozenset({"java", "csharp", "typescript", "go"})
@@ -1270,10 +1274,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if tabled is not None
else self._chain_inner_callee(file_path, call, inner, caller_id, language)
)
- if language in ("go", "python") and inner_callee is not None:
+ if language in _RETURNED_TYPE_ID_LANGUAGES and inner_callee is not None:
# A go method may sit in any file of its type's package, so the
# type is read by identity and the method asked for across it.
- # Python reads its annotation in the callee's file the same way.
+ # Python and Dart read the return type in the callee's file the same way.
type_id = self._returned_type_id(inner_callee)
hit = (
None
@@ -1283,9 +1287,10 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if hit is not None:
tier = hit.origin.removeprefix("receiver_typed_")
return True, self._return_typed_call(caller_id, hit.callee_id, tier, call.line)
- if language == "python":
+ if language in ("python", "dart"):
# A type name read in the caller's file is not evidence, and an
- # inherited method is not a refusal: the bare name keeps the site.
+ # inherited method is not a refusal: the bare name keeps the site
+ # where the language allows one.
return False, None
type_name = (
tabled
@@ -1889,6 +1894,12 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
method_name = call.target_name
assert receiver_name is not None
+ hit = self._first_strategy_hit(
+ self._strategies_for(file_path).constructor, file_path, call, caller_id
+ )
+ if hit is not None:
+ return True, hit
+
# Every strategy below ends in a lookup keyed on the method name, so a
# name the repo declares nowhere cannot resolve.
if method_name not in self._global_symbols:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/signatures.py b/packages/core/src/repowise/core/ingestion/extractors/signatures.py
index d59369f3e..480752712 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/signatures.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/signatures.py
@@ -44,6 +44,15 @@ def build_signature(node_type: str, name: str, params_text: str, def_node: Node,
):
# TS/JS use return_type; Go uses result
return f"function {name}{params_text}{_ret(('return_type', 'result'))}"
+ if node_type == "function_signature":
+ # Dart: the return type is the unfielded nodes ahead of the name.
+ name_node = def_node.child_by_field_name("name")
+ returns = ""
+ for child in def_node.children if name_node is not None else ():
+ if child == name_node:
+ break
+ returns += node_text(child, src)
+ return f"{name}{params_text} -> {returns}" if returns else f"{name}{params_text}"
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/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index 871be4183..947b4ea6b 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -722,6 +722,20 @@ def scan_call_shadows(text: str, language: str) -> tuple[tuple[int, str], ...]:
return tuple(sorted(lines))
+def dart_named_constructors(body: str, class_name: str) -> frozenset[str]:
+ """The names *class_name*'s Dart *body* declares constructors under: ``Foo.named(``.
+
+ Read where a declaration starts a line, with comments blanked. Ceiling: a
+ body-internal ``Foo.x(..)`` call at a line's start reads as one, which a
+ valid program only writes for a constructor or a static of the class.
+ """
+ declared = re.compile(
+ rf"^[ \t]*(?:(?:const|factory|external)\s+)*{re.escape(class_name)}\s*\.\s*(\w+)\s*\(",
+ re.MULTILINE,
+ )
+ return frozenset(declared.findall(_without_comments(body, "dart")))
+
+
# What a scope binds beyond its positional bindings. A TypeScript/JavaScript
# ``function`` declaration is hoisted, so it binds from the top of its scope
# whatever its line. A Python ``global`` name is the module's in that scope,
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 02b0a1522..4b6bd0331 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -194,6 +194,8 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
which call is carried into resolution.
"""
+ if node.type == "identifier":
+ return _dart_call_receiver(node, src)
arguments = node.child_by_field_name("arguments")
argument_count = _count_arguments(arguments) if arguments is not None else None
@@ -249,6 +251,30 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
return CallReceiver(target_name, receiver_name, argument_count)
+def _dart_call_receiver(name: Node, src: str) -> CallReceiver | None:
+ """The Dart call whose *name* the query captured: ``a.b(..)``, ``B(..)``.
+
+ A Dart call is a flat selector run with no call node, so the name's
+ siblings are read: the selector after it holds the arguments, and the
+ node before a ``.b`` selector is its receiver.
+ """
+ if name.parent.type == "unconditional_assignable_selector":
+ head = name.parent.parent
+ receiver: str | None = _node_text(head.prev_named_sibling, src).strip()
+ else:
+ head, receiver = name, None
+ return CallReceiver(
+ _node_text(name, src).strip(), receiver, _dart_argument_count(head.next_named_sibling)
+ )
+
+
+def _dart_argument_count(selector: Node | None) -> int | None:
+ """The arguments a Dart ``(selector (argument_part (arguments)))`` passes."""
+ parts = selector.named_children if selector is not None else ()
+ found = [arg for part in parts for arg in part.named_children if arg.type == "arguments"]
+ return _count_arguments(found[0]) if found else None
+
+
@cache
def _compile_query(lang: str, grammar_tag: str | None = None) -> tuple[object | None, str | None]:
"""Compile and return (Query, None) or (None, error_str).
diff --git a/packages/core/src/repowise/core/ingestion/queries/dart.scm b/packages/core/src/repowise/core/ingestion/queries/dart.scm
index ca1c05fd1..f6425cc05 100644
--- a/packages/core/src/repowise/core/ingestion/queries/dart.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/dart.scm
@@ -84,8 +84,8 @@
; ---------------------------------------------------------------------------
; Calls — Dart calls are selector chains: ``foo(x)`` is an identifier followed
; by a sibling (selector (argument_part)); ``obj.method(x)`` inserts a
-; ``.method`` selector between them. Only the first link of a chain is
-; captured (chained calls are best-effort, like Kotlin/Swift).
+; ``.method`` selector between them. A chain is captured to its second link,
+; which carries the first as its receiver call.
; ---------------------------------------------------------------------------
; Bare call / constructor call: foo(args) / HttpClient()
@@ -132,3 +132,55 @@
)
) @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.
+(_
+ [(identifier) (this)]
+ .
+ (selector
+ (unconditional_assignable_selector
+ (identifier) @call.receiver_call
+ )
+ )
+ .
+ (selector
+ (argument_part)
+ )
+ .
+ (selector
+ [
+ (unconditional_assignable_selector (identifier) @call.target)
+ (conditional_assignable_selector (identifier) @call.target)
+ ]
+ )
+ .
+ (selector
+ (argument_part
+ (arguments) @call.arguments
+ )
+ ) @call.site
+)
+
+; Chained on a constructor or function call: B(args).c(args).
+(_
+ (identifier) @call.receiver_call
+ .
+ (selector
+ (argument_part)
+ )
+ .
+ (selector
+ [
+ (unconditional_assignable_selector (identifier) @call.target)
+ (conditional_assignable_selector (identifier) @call.target)
+ ]
+ )
+ .
+ (selector
+ (argument_part
+ (arguments) @call.arguments
+ )
+ ) @call.site
+)
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index 3a5145fc2..2781e4abe 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -85,6 +85,8 @@ STORE_FORMAT_VERSION: int = 2
#: a type body holding ``#if`` keeps its members.
#: A Python call chained on a method call (``a.get().close()``) carries that
#: inner call.
+#: A Dart call chained on a call (``a.b().c()``) carries that inner call too,
+#: and a Dart function's signature carries its declared return type.
PARSER_SCHEMA_VERSION: int = 8
#: state.json key holding the store format version that wrote the store.
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index c07ebd841..9633ba556 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -215,7 +215,10 @@ def test_unbound_global_return_type_preserves_legacy_fallback(
def test_only_audited_lanes_are_enabled_by_default() -> None:
- assert frozenset({"cpp", "csharp", "go", "java", "python"}) == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
+ assert (
+ frozenset({"cpp", "csharp", "dart", "go", "java", "python"})
+ == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES
+ )
def test_module_level_chain_keeps_structural_receiver(tmp_path: Path) -> None:
@@ -727,3 +730,128 @@ def test_csharp_chain_link_whose_declarations_disagree_has_no_type(tmp_path: Pat
)
assert ("WithMessage", 1) in edges
+
+
+_DART_REPO = (
+ "class Item {\n void save() {}\n}\n"
+ "class Repo {\n"
+ " Repo();\n"
+ " // Repo.ghost(1) is only a comment.\n"
+ " Repo.fromJson(Object json);\n"
+ " factory Repo.load(String path) => Repo();\n"
+ " factory Repo.copy() {\n return Repo.other();\n }\n"
+ " static Repo parse(String text) => Repo();\n"
+ " Item item(int i) => Item();\n"
+ " Item? maybe() => null;\n"
+ " Future<Item> later() async => Item();\n"
+ " void close() {}\n"
+ "}\n"
+)
+
+# The methods a wrongly typed chain could land on.
+_DART_OUTER = frozenset({"repo.dart::Item::save", "repo.dart::Repo::close"})
+
+
+def _dart_edges(tmp_path: Path, body: str) -> set[tuple[int, str, str]]:
+ """``(line, callee, origin)`` for the calls of ``App.run`` holding *body*."""
+ app = (
+ "import 'repo.dart';\n"
+ "class App {\n final Repo repo;\n App(this.repo);\n"
+ f" void run(Repo r) {{\n{body}\n }}\n"
+ " Repo helper() => Repo();\n}\n"
+ )
+ parsed = _parse(tmp_path, "repo.dart", "dart", _DART_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"
+ }
+
+
+def test_dart_signature_carries_the_declared_return_type(tmp_path: Path) -> None:
+ parsed = _parse(tmp_path, "repo.dart", "dart", _DART_REPO)
+ signatures = {s.name: s.signature for s in parsed["repo.dart"].symbols}
+
+ assert signatures["item"] == "item(int i) -> Item"
+ assert signatures["maybe"] == "maybe() -> Item?"
+ assert signatures["close"] == "close() -> void"
+
+
+def test_dart_named_and_factory_constructors_bind_their_class(tmp_path: Path) -> None:
+ edges = _dart_edges(tmp_path, "Repo.fromJson(1);\nRepo.load('x');\nRepo.parse('y');")
+
+ assert edges == {
+ (1, "repo.dart::Repo", "import_merged"),
+ (2, "repo.dart::Repo", "import_merged"),
+ (3, "repo.dart::Repo::parse", "receiver_import"),
+ }
+
+
+ "body",
+ [
+ "Repo.nope();", # declared nowhere
+ "Repo.ghost(1);", # named only in a comment
+ "Repo.other();", # called in the class body, never declared
+ ],
+)
+def test_dart_constructor_the_class_does_not_declare_binds_nothing(
+ tmp_path: Path, body: str
+) -> None:
+ assert _dart_edges(tmp_path, body) == set()
+
+
+def test_dart_untyped_member_call_binds_no_bare_name(tmp_path: Path) -> None:
+ """A Dart member call has no bare-name reading: an untyped receiver draws no edge."""
+ assert _dart_edges(tmp_path, "var a = unknown();\na.save();") == set()
+
+
+ ("body", "callee"),
+ [
+ ("r.item(1).save();", "repo.dart::Item::save"), # a parameter
+ ("repo.item(1).save();", "repo.dart::Item::save"), # a field
+ ("r.maybe()?.save();", "repo.dart::Item::save"), # a nullable return
+ ("this.helper().close();", "repo.dart::Repo::close"), # on this
+ ("Repo().close();", "repo.dart::Repo::close"), # on a constructor
+ ("Repo.fromJson(2).close();", "repo.dart::Repo::close"), # on a named one
+ ],
+)
+def test_dart_chain_binds_the_method_of_the_inner_return_type(
+ tmp_path: Path, body: str, callee: str
+) -> None:
+ assert (1, callee, "return_type_import") in _dart_edges(tmp_path, body)
+
+
+ "body",
+ [
+ "r.later().save();", # a Future is not the class it wraps
+ "r.item(1).close();", # the returned class lacks the method
+ "unknown().save();", # nothing types the inner call
+ "r..item(1)..close();", # a cascade is not a chain
+ "r?.item(1).save();", # a null-aware first link is not captured
+ ],
+)
+def test_dart_chain_without_a_typed_method_binds_no_bare_name(tmp_path: Path, body: str) -> None:
+ assert {e for e in _dart_edges(tmp_path, body) if e[1] in _DART_OUTER} == set()
+
+
+def test_dart_third_link_of_a_chain_is_dropped_not_misbound(tmp_path: Path) -> None:
+ edges = _dart_edges(tmp_path, "r.item(1).save().close();")
+
+ assert {e[1] for e in edges if e[1] in _DART_OUTER} == {"repo.dart::Item::save"}
+
+
+def test_dart_constructor_initializers_are_not_calls(tmp_path: Path) -> None:
+ source = (
+ "class A {\n A.named(int x);\n}\n"
+ "class B extends A {\n B.x() : super.named(1);\n B.y() : this.x();\n}\n"
+ )
+ parsed = _parse(tmp_path, "b.dart", "dart", source)
+
+ assert parsed["b.dart"].calls == []