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(dart): type a closure parameter from the Iterable call it is passed to (#3753) (#4528)

Amanac1d75bf3d6e
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 6e526b868..c96191b8d 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
@@ -21,6 +21,7 @@ from ..languages.receiver_types import (
RANGE_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
CallAssignment,
+ DartCallback,
Declaration,
RangeScan,
ScopeMarks,
@@ -58,6 +59,7 @@ from ._shared import ( # noqa: F401
_is_module_level_function,
_store_capped,
)
+from .callbacks import CallbackParameterTypes, _TypedCallback
from .framework import FrameworkReceiverTypes
from .go import GoReturnTypes
from .java import _JAVA_TYPE_PARAMETERS, JavaTypeVisibility, _header_type_parameters # noqa: F401
@@ -188,6 +190,7 @@ class ReceiverTypingMixin(
PythonReturnTypes,
GoReturnTypes,
RangeVariableTypes,
+ CallbackParameterTypes,
FrameworkReceiverTypes,
):
"""Typed-receiver and C# extension strategies, with the source caches they read."""
@@ -205,6 +208,9 @@ class ReceiverTypingMixin(
self._body_types: dict[tuple[str, str], dict[str, str | None]] = {}
self._field_types: dict[str, dict[str, dict[str, str | None]]] = {}
self._range_scans: dict[str, RangeScan] = {}
+ # Dart callbacks per file, and per body once typed from their receivers.
+ self._callback_scans: dict[str, tuple[DartCallback, ...]] = {}
+ self._callback_types: dict[tuple[str, str], tuple[_TypedCallback, ...]] = {}
# {file: {class_id: {field: container spelling}}}
self._container_fields: dict[str, dict[str, dict[str, str | None]]] = {}
self._module_types: dict[str, dict[str, str | None]] = {}
@@ -455,7 +461,7 @@ class ReceiverTypingMixin(
return None
return self._resolve_chained_receiver(file_path, call, caller_id, language)
type_name, scope, typing_file = self._receiver_type_and_scope(
- file_path, caller_id, language, receiver_name
+ file_path, caller_id, language, receiver_name, call.line
)
if type_name is None:
return None
@@ -489,9 +495,15 @@ class ReceiverTypingMixin(
caller_id: str,
language: str,
receiver_name: str,
+ line: int | None = None,
) -> tuple[str | None, str, str]:
"""The receiver's declared type, the scope that declared it, and the file to read it in.
+ A Dart closure parameter answers first, from the ``Iterable`` call that
+ hands it the literal, but only on a *line* inside that literal: it is
+ no local of the body at large. One whose type is unread still hides
+ the locals and fields it shadows.
+
A local shadows a field, so the body answers first and its answer
stands — including when that answer is "declared twice, no usable
type". Only a name the body never mentions reaches class scope, and
@@ -502,6 +514,12 @@ class ReceiverTypingMixin(
neither types nor binds is asked of the function around it, whose
locals it captures and whose class fields it sees.
"""
+ if line is not None and language == "dart":
+ bound, closure_type = self._callback_parameter(
+ file_path, caller_id, language, receiver_name, line
+ )
+ if bound:
+ return closure_type, "body", file_path
caller_id, body_types = self._typing_scope(file_path, caller_id, language, receiver_name)
# A builtin type answers only when nothing else does, so a local
# ``String data`` leaves ``this.data.m()``, which reaches here as
@@ -743,7 +761,7 @@ class ReceiverTypingMixin(
head, *fields = (call.receiver_name or "").split(".")
if len(fields) > _MAX_CHAIN_FIELDS or not all(fields):
return None
- found = self._chain_head(file_path, caller_id, language, head)
+ found = self._chain_head(file_path, caller_id, language, head, call.line)
for field in fields:
if found is None:
return None
@@ -760,9 +778,9 @@ class ReceiverTypingMixin(
return ResolvedCall(caller_id, sym_id, 0.88, call.line, "receiver_chain_import")
def _chain_head(
- self, file_path: str, caller_id: str, language: str, head: str
+ self, file_path: str, caller_id: str, language: str, head: str, line: int
) -> tuple[str, str, str] | None:
- """``(file, class id, tier)`` for a chain's head name."""
+ """``(file, class id, tier)`` for a chain's head name, as bound on *line*."""
if head == _CHAIN_SELF[language]:
class_id = self._caller_class_id(caller_id)
symbol = self._symbols_by_id.get(class_id)
@@ -770,7 +788,7 @@ class ReceiverTypingMixin(
return None
return file_path, class_id, "same_file"
type_name, _, typing_file = self._receiver_type_and_scope(
- file_path, caller_id, language, head
+ file_path, caller_id, language, head, line
)
if type_name is not None and language == "python" and "::" in type_name:
return self._located(file_path, type_name) # typed from a call
@@ -1129,7 +1147,7 @@ class ReceiverTypingMixin(
if language not in EXTERNAL_TYPE_LANGUAGES:
return False
type_name, _, typing_file = self._receiver_type_and_scope(
- file_path, caller_id, language, receiver_name
+ file_path, caller_id, language, receiver_name, call.line
)
if type_name is None or "::" in type_name:
return False
diff --git a/packages/core/src/repowise/core/ingestion/call_receiver_typing/callbacks.py b/packages/core/src/repowise/core/ingestion/call_receiver_typing/callbacks.py
new file mode 100644
index 000000000..773fd0099
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing/callbacks.py
@@ -0,0 +1,157 @@
+"""Closure parameters typed from the ``Iterable`` call they are handed to."""
+
+from __future__ import annotations
+
+from typing import NamedTuple
+
+from ..languages.receiver_types import (
+ DartCallback,
+ RangeClause,
+ callbacks_binding,
+ callbacks_in_span,
+ range_element_types,
+ scan_dart_callbacks,
+ types_in_span,
+)
+from ._shared import _SOURCE_CACHE_FILES, _store_capped
+
+
+class _TypedCallback(NamedTuple):
+ """A callback and the element type its parameter was read as, if any."""
+
+ callback: DartCallback
+ type_name: str | None
+
+
+class CallbackParameterTypes:
+ """Typing of ``items.forEach((p) => p.m())``'s ``p`` from ``items``' element."""
+
+ def _callback_parameter(
+ self, file_path: str, caller_id: str, language: str, name: str, line: int
+ ) -> tuple[bool, str | None]:
+ """``(bound, type)`` for *name* as a closure parameter on *line* of one body.
+
+ ``bound`` is whether a function literal there declares *name*, which
+ then hides a local or field of the same name even where its type is
+ unknown. The type is None unless every literal binding it on that line
+ agrees: the parameter lives only inside its literal's span, so a
+ sibling closure or a later local of the name keeps its own reading.
+ Ceiling: the span is read in lines, so a use of the name on the
+ literal's last line but outside it reads as the parameter.
+ """
+ if language != "dart":
+ return False, None
+ typed = self._callbacks_typed_in(file_path, caller_id, language)
+ binding = callbacks_binding((t.callback for t in typed), name, line)
+ if not binding:
+ return False, None
+ types = {t.type_name for t in typed if t.callback in binding}
+ return True, next(iter(types)) if len(types) == 1 else None
+
+ def _callbacks_typed_in(
+ self, file_path: str, caller_id: str, language: str
+ ) -> tuple[_TypedCallback, ...]:
+ """Every one-element ``Iterable`` callback in one body, typed where it can be.
+
+ In source order, so a callback over an outer callback's parameter
+ (``rs.forEach((r) => r.items.forEach((i) => i.m()))``) sees it typed.
+ """
+ key = (file_path, caller_id)
+ found = self._callback_types.get(key)
+ if found is not None:
+ return found
+
+ span = self._spans_for(file_path).get(caller_id)
+ typed: list[_TypedCallback] = []
+ if span is not None:
+ callbacks = callbacks_in_span(self._callback_scan_for(file_path), *span)
+ if callbacks:
+ body_types = self._declared_types_in(file_path, caller_id, language)
+ containers = types_in_span(
+ self._range_scan_for(file_path, language).containers, *span
+ )
+ for callback in callbacks:
+ scoped = dict(body_types)
+ for outer in typed:
+ if outer.callback.start <= callback.start <= outer.callback.end:
+ scoped[outer.callback.name] = outer.type_name
+ typed.append(
+ _TypedCallback(
+ callback,
+ self._callback_element_type(
+ file_path, caller_id, language, callback, scoped, containers
+ ),
+ )
+ )
+
+ found = tuple(typed)
+ _store_capped(self._callback_types, key, found, _SOURCE_CACHE_FILES)
+ return found
+
+ def _callback_element_type(
+ self,
+ file_path: str,
+ caller_id: str,
+ language: str,
+ callback: DartCallback,
+ types: dict[str, str | None],
+ containers: dict[str, str | None],
+ ) -> str | None:
+ """The element type of the container *callback* walks, or None if unknown.
+
+ The container is read as a for-in clause reads it, so the two agree on
+ what is a container and what is not. ``this.items`` and a bare name
+ the body does not bind are fields of the caller's class. A receiver
+ that is no ``Iterable`` of a known element (a repo class's own
+ ``map``, a ``Map``) yields nothing.
+ """
+ spelling, written_in = self._callback_container(
+ file_path, caller_id, language, callback, types, containers
+ )
+ elements = range_element_types(spelling, language, self._externally_bound_names(written_in))
+ return elements[1] if elements else None
+
+ def _callback_container(
+ self,
+ file_path: str,
+ caller_id: str,
+ language: str,
+ callback: DartCallback,
+ types: dict[str, str | None],
+ containers: dict[str, str | None],
+ ) -> tuple[str | None, str]:
+ """How the container one callback walks is spelled, and in which file."""
+ head, member = callback.head, callback.member
+ if head == "this" and member and not callback.call:
+ return self._caller_field_container(file_path, caller_id, language, member)
+ if head == "this":
+ return None, file_path
+ unbound = head not in types and head not in containers
+ if (
+ not member
+ and unbound
+ and head not in self._bound_names_in(file_path, caller_id, language)
+ ):
+ return self._caller_field_container(file_path, caller_id, language, head)
+ # Not a loop, but the same ``head[.member[()]]`` read as a for-in's.
+ clause = RangeClause(callback.start, "", callback.name, head, member, callback.call)
+ return self._ranged_container(file_path, language, clause, types, containers)
+
+ def _caller_field_container(
+ self, file_path: str, caller_id: str, language: str, name: str
+ ) -> tuple[str | None, str]:
+ """The container spelling of the caller's class field *name*.
+
+ Ceiling: a field an ancestor declares is not found.
+ """
+ class_id = self._caller_class_id(caller_id)
+ fields = self._container_fields_in(file_path, language).get(class_id, {})
+ return fields.get(name), file_path
+
+ def _callback_scan_for(self, file_path: str) -> tuple[DartCallback, ...]:
+ """One file's callbacks, scanned once however many bodies ask."""
+ found = self._callback_scans.get(file_path)
+ if found is None:
+ found = scan_dart_callbacks(self._text_of(file_path))
+ _store_capped(self._callback_scans, file_path, found, _SOURCE_CACHE_FILES)
+ return found
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 7c70567d9..44414cb30 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -1634,3 +1634,154 @@ def clauses_in_span(
first = bisect_left(clauses, start_line, key=lambda c: c.line)
last = bisect_right(clauses, end_line, key=lambda c: c.line)
return clauses[first:last]
+
+
+# Dart's one-element ``Iterable`` callbacks. ``items.forEach((p) => p.m())``
+# binds ``p`` to an element of ``items``, though no type is spelled. ``fold``
+# leads with its accumulator and ``reduce`` and ``sort`` take two parameters,
+# so none of those is read: only a callback of exactly one element is.
+DART_CALLBACK_METHODS = (
+ "forEach",
+ "map",
+ "where",
+ "any",
+ "every",
+ "firstWhere",
+ "lastWhere",
+ "singleWhere",
+ "expand",
+)
+
+# ``head[.member[()]].method((name) => ..)``, or ``((name) { .. })``: the
+# function literal is the call's first argument and its list is one bare name.
+# A written type (``(Repo p) => ..``) is ``_DART_TYPED``'s and never matches
+# here. ``head`` follows no ``.``, so ``a.b.c.forEach`` is refused as the
+# for-in clause refuses ``a.b.c``.
+_DART_CALLBACK = re.compile(
+ rf"(?<![\w.$])(?P<head>{_DART_NAME})"
+ rf"(?:\??\.(?P<member>[A-Za-z_]\w*)(?P<call>\(\))?)?"
+ rf"\??\.(?P<method>{'|'.join(DART_CALLBACK_METHODS)})\s*\(\s*"
+ rf"\(\s*(?P<name>{_DART_NAME})\s*\)\s*(?:async\s*)?(?P<arrow>=>|\{{)"
+)
+
+
+class DartCallback(NamedTuple):
+ """One function literal handed to an ``Iterable`` method, and where it lives.
+
+ ``name`` is the literal's one parameter. ``start`` and ``end`` are the
+ lines the literal covers, and ``begin`` and ``finish`` its offsets, which
+ tell a literal nested in another from one beside it on the same line.
+ ``head``, ``member`` and ``call`` read the receiver as a for-in clause does.
+ """
+
+ start: int
+ end: int
+ begin: int
+ finish: int
+ name: str
+ head: str
+ member: str
+ call: bool
+ method: str
+
+
+def _skip_dart_string(text: str, at: int) -> int:
+ """The offset just past the string literal opening at *at*, or -1 if unterminated.
+
+ Interpolation is skipped with the string. Ceiling: a quote of the string's
+ own kind inside an interpolation (``'${m['k']}'``) ends it early.
+ """
+ quote = text[at]
+ closer = quote * 3 if text.startswith(quote * 3, at) else quote
+ raw = at > 0 and text[at - 1] == "r"
+ index = at + len(closer)
+ while index < len(text):
+ if text[index] == "\\" and not raw:
+ index += 2
+ elif text.startswith(closer, index):
+ return index + len(closer)
+ elif len(closer) == 1 and text[index] == "\n":
+ return -1
+ else:
+ index += 1
+ return -1
+
+
+def _callback_end(cleaned: str, at: int, block: bool) -> int | None:
+ """The offset just past the function literal whose body starts at *at*.
+
+ A block body ends at the brace matching the one before *at*. An expression
+ body ends at the comma or unmatched parenthesis that closes the argument.
+ None where the brackets never balance, so the literal is dropped, not
+ guessed at.
+ """
+ depth = 1 if block else 0
+ index = at
+ while index < len(cleaned):
+ char = cleaned[index]
+ if char in "'\"":
+ index = _skip_dart_string(cleaned, index)
+ if index < 0:
+ return None
+ continue
+ if char in "([{":
+ depth += 1
+ elif char in ")]}":
+ depth -= 1
+ if block and depth == 0:
+ return index + 1
+ if not block and depth < 0:
+ return index
+ elif not block and depth == 0 and char in ",;":
+ return index
+ index += 1
+ return None
+
+
+def scan_dart_callbacks(text: str) -> tuple[DartCallback, ...]:
+ """Every one-element ``Iterable`` callback *text* passes, in source order."""
+ cleaned = _without_comments(text, "dart")
+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+ found: list[DartCallback] = []
+ for match in _DART_CALLBACK.finditer(cleaned):
+ finish = _callback_end(cleaned, match.end(), match.group("arrow") == "{")
+ if finish is None:
+ continue
+ found.append(
+ DartCallback(
+ bisect_right(starts, match.start("name")),
+ bisect_right(starts, max(finish - 1, match.start("name"))),
+ match.start("name"),
+ finish,
+ match.group("name"),
+ match.group("head"),
+ match.group("member") or "",
+ bool(match.group("call")),
+ match.group("method"),
+ )
+ )
+ return tuple(found)
+
+
+def callbacks_in_span(
+ callbacks: tuple[DartCallback, ...], start_line: int, end_line: int
+) -> tuple[DartCallback, ...]:
+ """The callbacks whose parameter sits inside one function body, in source order."""
+ return tuple(c for c in callbacks if start_line <= c.start <= end_line)
+
+
+def callbacks_binding(
+ callbacks: Iterable[DartCallback], name: str, line: int
+) -> tuple[DartCallback, ...]:
+ """The innermost callbacks that bind *name* on *line*.
+
+ A literal nested in another covers the same lines, so the outer one is
+ dropped. Two literals side by side on one line cannot be told apart by
+ line alone, so both stay and the caller must agree between them.
+ """
+ covering = [c for c in callbacks if c.name == name and c.start <= line <= c.end]
+ return tuple(
+ c
+ for c in covering
+ if not any(o is not c and c.begin < o.begin and o.finish <= c.finish for o in covering)
+ )
diff --git a/tests/unit/ingestion/test_dart_range_receivers.py b/tests/unit/ingestion/test_dart_range_receivers.py
index bfc2301d4..f6052e62f 100644
--- a/tests/unit/ingestion/test_dart_range_receivers.py
+++ b/tests/unit/ingestion/test_dart_range_receivers.py
@@ -14,8 +14,12 @@ import pytest
from repowise.core.ingestion.call_resolver import CallResolver
from repowise.core.ingestion.languages.receiver_types import (
+ DART_CALLBACK_METHODS,
+ DartCallback,
RangeClause,
+ callbacks_binding,
range_element_types,
+ scan_dart_callbacks,
scan_declarations,
scan_ranges,
types_in_span,
@@ -142,7 +146,12 @@ _PREFIX = 4 # lines of ``app.dart`` before the body
def _callees(tmp_path: Path, body: str, params: str = "Repo r, List<Repo> repos") -> set[str]:
app = f"import 'repo.dart';\nclass App {{\n void run({params}) {{\n{body}\n }}\n}}\n"
- parsed = _parse_all(tmp_path, {"repo.dart": ("dart", _REPO), "app.dart": ("dart", app)})
+ return _callees_of(tmp_path, app)
+
+
+def _callees_of(tmp_path: Path, app: str, repo: str = _REPO) -> set[str]:
+ """The edges out of ``App.run`` for a whole ``app.dart``."""
+ parsed = _parse_all(tmp_path, {"repo.dart": ("dart", repo), "app.dart": ("dart", app)})
for imp in parsed["app.dart"].imports:
imp.resolved_file = "repo.dart"
resolver = CallResolver(
@@ -216,3 +225,230 @@ class TestResolution:
callees = _callees(tmp_path, body, "Repo r, List<Item> other")
assert CLOSE in callees
assert SAVE not in callees
+
+
+class TestCallbackScan:
+ """``items.forEach((p) => ..)``: the literal, its one parameter, and its span."""
+
+ @staticmethod
+ def _callbacks(text: str) -> list[DartCallback]:
+ return list(scan_dart_callbacks(text))
+
+ @pytest.mark.parametrize("method", DART_CALLBACK_METHODS)
+ def test_every_one_element_method_is_read(self, method: str) -> None:
+ (callback,) = self._callbacks(f"repos.{method}((p) => p.close());")
+ assert (callback.name, callback.head, callback.member, callback.call) == (
+ "p",
+ "repos",
+ "",
+ False,
+ )
+ assert callback.method == method
+
+ def test_a_block_body(self) -> None:
+ (callback,) = self._callbacks("repos.where((p) {\n return p.ok();\n});")
+ assert (callback.start, callback.end) == (1, 3)
+
+ def test_an_async_literal(self) -> None:
+ (callback,) = self._callbacks("repos.forEach((p) async => await p.close());")
+ assert callback.name == "p"
+
+ def test_a_field_and_a_method_result(self) -> None:
+ field, call = self._callbacks("r.items.map((i) => i);\nr.all().map((i) => i);")
+ assert (field.head, field.member, field.call) == ("r", "items", False)
+ assert (call.head, call.member, call.call) == ("r", "all", True)
+
+ def test_this_and_a_null_aware_receiver(self) -> None:
+ this, aware = self._callbacks("this.repos.map((p) => p);\nrepos?.forEach((p) => p);")
+ assert (this.head, this.member) == ("this", "repos")
+ assert (aware.head, aware.member) == ("repos", "")
+
+ def test_an_expression_body_ends_at_its_argument(self) -> None:
+ (callback,) = self._callbacks("repos.firstWhere((p) => p.ok(),\n orElse: () => other);")
+ assert (callback.start, callback.end) == (1, 1)
+
+ @pytest.mark.parametrize(
+ "line",
+ [
+ "repos.forEach((Repo p) => p.close());", # a written type is _DART_TYPED's
+ "repos.forEach((final Repo p) => p.close());",
+ "repos.fold(0, (acc, p) => acc);",
+ "repos.reduce((a, b) => a);",
+ "repos.sort((a, b) => 0);",
+ "repos.forEach((a, b) => a);",
+ "repos.forEach(print);",
+ "repos.forEach(() => 1);",
+ "r.a.b.forEach((p) => p);",
+ "f().forEach((p) => p);",
+ "Repo.forEach((p) => p);",
+ "repos.listen((p) => p);",
+ "// repos.forEach((p) => p.close());",
+ ],
+ )
+ def test_anything_else_is_not_read(self, line: str) -> None:
+ assert self._callbacks(line) == []
+
+ def test_an_unbalanced_literal_is_dropped(self) -> None:
+ assert self._callbacks("repos.forEach((p) => p.close(") == []
+
+ def test_a_bracket_in_a_string_does_not_end_the_literal(self) -> None:
+ (callback,) = self._callbacks("repos.where((p) => p.name == ')' &&\n p.ok());")
+ assert (callback.start, callback.end) == (1, 2)
+
+ def test_a_nested_literal_hides_the_outer_one(self) -> None:
+ text = "a.forEach((p) => b.forEach((p) => p.x()));"
+ callbacks = self._callbacks(text)
+ (inner,) = callbacks_binding(callbacks, "p", 1)
+ assert inner.head == "b"
+
+ def test_literals_side_by_side_are_both_kept(self) -> None:
+ text = "a.forEach((p) => p.x()); b.forEach((p) => p.y());"
+ assert len(callbacks_binding(self._callbacks(text), "p", 1)) == 2
+
+ def test_a_line_outside_the_literal_is_unbound(self) -> None:
+ text = "repos.forEach((p) {\n p.close();\n});\np.save();"
+ assert callbacks_binding(self._callbacks(text), "p", 4) == ()
+
+
+class TestCallbackResolution:
+ def test_for_each_over_a_list_parameter(self, tmp_path: Path) -> None:
+ assert CLOSE in _callees(tmp_path, "repos.forEach((p) => p.close());")
+
+ def test_the_issue_repro(self, tmp_path: Path) -> None:
+ body = "for (final p in repos) {\n p.close();\n}\nrepos.forEach((p) => p.close());\nr.close();"
+ assert _callees(tmp_path, body) == {CLOSE}
+
+ @pytest.mark.parametrize(
+ "method", ["forEach", "map", "where", "any", "every", "firstWhere", "expand"]
+ )
+ def test_each_method_binds(self, tmp_path: Path, method: str) -> None:
+ assert CLOSE in _callees(tmp_path, f"repos.{method}((p) => p.close());")
+
+ def test_a_block_body(self, tmp_path: Path) -> None:
+ body = "repos.where((p) {\n p.close();\n return true;\n});"
+ assert CLOSE in _callees(tmp_path, body)
+
+ def test_over_an_iterable_local(self, tmp_path: Path) -> None:
+ body = "Iterable<Repo> rs = repos;\nrs.forEach((p) => p.close());"
+ assert CLOSE in _callees(tmp_path, body)
+
+ def test_over_a_field_of_a_typed_receiver(self, tmp_path: Path) -> None:
+ assert SAVE in _callees(tmp_path, "r.items.forEach((i) => i.save());")
+
+ def test_over_a_method_result(self, tmp_path: Path) -> None:
+ assert SAVE in _callees(tmp_path, "r.all().forEach((i) => i.save());")
+
+ def test_over_this_field(self, tmp_path: Path) -> None:
+ app = (
+ "import 'repo.dart';\nclass App {\n final List<Repo> repos = [];\n"
+ " void run() {\n this.repos.map((p) => p.close());\n }\n}\n"
+ )
+ assert CLOSE in _callees_of(tmp_path, app)
+
+ def test_over_a_bare_field(self, tmp_path: Path) -> None:
+ app = (
+ "import 'repo.dart';\nclass App {\n final List<Repo> repos = [];\n"
+ " void run() {\n repos.forEach((p) => p.close());\n }\n}\n"
+ )
+ assert CLOSE in _callees_of(tmp_path, app)
+
+ def test_a_local_hides_a_field_of_the_same_name(self, tmp_path: Path) -> None:
+ app = (
+ "import 'repo.dart';\nclass App {\n final List<Repo> repos = [];\n"
+ " void run(List<Item> repos) {\n repos.forEach((p) => p.save());\n }\n}\n"
+ )
+ callees = _callees_of(tmp_path, app)
+ assert SAVE in callees
+ assert CLOSE not in callees
+
+ def test_an_outer_closure_parameter_types_an_inner_receiver(self, tmp_path: Path) -> None:
+ body = "repos.forEach((r2) => r2.items.forEach((i) => i.save()));"
+ assert SAVE in _callees(tmp_path, body)
+
+ def test_a_written_type_still_binds(self, tmp_path: Path) -> None:
+ assert CLOSE in _callees(tmp_path, "repos.forEach((Repo p) => p.close());")
+
+ def test_a_written_type_wins_over_the_container(self, tmp_path: Path) -> None:
+ assert _callees(tmp_path, "repos.forEach((Item p) => p.save());") == {SAVE}
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ "repos.fold(0, (acc, p) => p.close());",
+ "repos.reduce((a, b) => a.close());",
+ "repos.forEach((a, b) => a.close());",
+ ],
+ )
+ def test_a_callback_of_another_shape_binds_nothing(self, tmp_path: Path, body: str) -> None:
+ assert CLOSE not in _callees(tmp_path, body)
+
+ def test_an_unknown_receiver_binds_nothing(self, tmp_path: Path) -> None:
+ assert CLOSE not in _callees(tmp_path, "mystery.forEach((p) => p.close());")
+
+ def test_a_map_binds_nothing(self, tmp_path: Path) -> None:
+ body = "m.forEach((p) => p.close());"
+ assert CLOSE not in _callees(tmp_path, body, "Map<String, Repo> m")
+
+ def test_a_nested_generic_binds_nothing(self, tmp_path: Path) -> None:
+ body = "xs.forEach((p) => p.close());"
+ assert CLOSE not in _callees(tmp_path, body, "List<List<Repo>> xs")
+
+ def test_a_repo_classs_own_map_binds_nothing(self, tmp_path: Path) -> None:
+ """``r.map`` is not ``Iterable.map``: ``r`` is a ``Repo``, not a container."""
+ repo = _REPO.replace(
+ " void close() {}", " void map(void Function(Repo) f) {}\n void close() {}"
+ )
+ app = (
+ "import 'repo.dart';\nclass App {\n void run(Repo r) {\n"
+ " r.map((x) => x.close());\n }\n}\n"
+ )
+ assert CLOSE not in _callees_of(tmp_path, app, repo)
+
+ def test_the_parameter_lives_only_inside_its_literal(self, tmp_path: Path) -> None:
+ """A later local named ``p`` keeps its own reading, not the closure's."""
+ body = "repos.forEach((p) {\n p.close();\n});\nItem p = Item();\np.save();"
+ callees = _callees(tmp_path, body)
+ assert CLOSE in callees
+ assert SAVE in callees
+
+ def test_sibling_closures_each_keep_their_own(self, tmp_path: Path) -> None:
+ body = "repos.forEach((p) {\n p.close();\n});\nr.items.forEach((p) {\n p.save();\n});"
+ assert {CLOSE, SAVE} <= _callees(tmp_path, body)
+
+ def test_a_closure_parameter_hides_a_local_of_its_name(self, tmp_path: Path) -> None:
+ """``p`` is the closure's, even where the body also declares an ``Item p``."""
+ body = "Item p = Item();\nmystery.forEach((p) {\n p.save();\n});"
+ assert SAVE not in _callees(tmp_path, body)
+
+ def test_the_loop_variable_after_it_is_unaffected(self, tmp_path: Path) -> None:
+ body = "repos.forEach((p) => p.close());\nfor (final p in repos) {\n p.close();\n}"
+ assert CLOSE in _callees(tmp_path, body)
+
+
+class TestChainedCallbackHead:
+ """``p.items.save()`` inside ``(p) => ...`` heads the chain with the closure's ``p``."""
+
+ _CLASSES = (
+ "class Item {\n void save() {}\n}\n"
+ "class Box {\n void save() {}\n}\n"
+ "class Holder {\n final Item items = Item();\n}\n"
+ "class Shelf {\n final Box items = Box();\n}\n"
+ )
+
+ def test_an_outer_local_of_the_name_does_not_head_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "import 'repo.dart';\nclass App {\n void run(Shelf p, List<Holder> hs) {\n"
+ " hs.forEach((p) => p.items.save());\n }\n}\n"
+ )
+ callees = _callees_of(tmp_path, app, self._CLASSES)
+ assert "repo.dart::Box::save" not in callees
+ assert "repo.dart::Item::save" in callees
+
+ def test_an_outer_field_of_the_name_does_not_head_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "import 'repo.dart';\nclass App {\n final Shelf p = Shelf();\n"
+ " void run(List<Holder> hs) {\n hs.forEach((p) => p.items.save());\n }\n}\n"
+ )
+ callees = _callees_of(tmp_path, app, self._CLASSES)
+ assert "repo.dart::Box::save" not in callees
+ assert "repo.dart::Item::save" in callees