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
feat(graph): type Dart call receivers from fields, parameters and locals (#3610)
Swati Ahujad52f2094ccf4
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex f1d56d486..675e6fd9b 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -506,11 +506,12 @@ Pattern families today:| Go | Go | parameters, `name := Type{}`, `var name Type` || Kotlin | Kotlin | `name: Type`, `= Type(...)` || Swift | Swift | `name: Type`, `= Type(...)` |+| Dart | Dart | `Type name`, `Type? name`, `final name = Type(...)` || Python | Python | annotations, `name = Type(...)`, target lists |Two further sets gate the harder half:-- **`IMPLICIT_FIELD_LANGUAGES`** = `{csharp, java, kotlin, swift}`. Only these+- **`IMPLICIT_FIELD_LANGUAGES`** = `{csharp, dart, java, kotlin, swift}`. Only theselook up an unbound receiver among the *enclosing class's fields*. Go isdeliberately excluded even though its locals and parameters are typed: itspackage-level `var` is a wider scope than a field, and the shape is a roundingdiff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.pyindex 2647bbba9..abc832e61 100644--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py@@ -69,10 +69,11 @@ _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 registers the fallback and nothing else: it has no 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 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": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),+ "dart": _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 notdiff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex 4c3bbeef7..d98383dd4 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -23,7 +23,7 @@ from __future__ import annotationsimport refrom bisect import bisect_left, bisect_right-from collections.abc import Iterable, Mapping+from collections.abc import Callable, Iterable, Mappingfrom typing import NamedTuplefrom ..language_data import get_builtin_types@@ -240,6 +240,27 @@ _SWIFT_CONSTRUCTED = re.compile(r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)")+# Dart writes the C family's `Type name`, plus a nullable `Api? api` and a named+# parameter closing on `}`. Fields close on `;` or `=` as Java's do. A+# constructor is no symbol here, so its parameters sit at class scope; nothing+# inside parentheses owns a field (`_PARAMETERS_AT_CLASS_SCOPE`), which keeps+# out `{Dao d = const Dao()}` too. An initialising formal (`Repo(this.api)`)+# spells no type: the field it assigns already carries one.+_DART_TYPED = re.compile(+ rf"(?<![\w.])(?P<type>{_TYPE})\??\s+(?P<name>[a-z_]\w*)\s*(?=(?P<closer>[=;,)}}]))"+)++# `final x = Foo()`, `var`/`const`, with `new`/`const` before the type. The+# `=` closer makes it a field at class scope, as `_TS_CONSTRUCTED`'s does. A+# chain is refused as `_KT_CONSTRUCTED` refuses one, but a cascade+# (`Paint()..color = c`) is still the `Paint`. `Foo.named()` is refused too:+# a named constructor and a static call look the same.+_DART_CONSTRUCTED = re.compile(+ r"(?<![\w.])(?:final|var|const)\s+(?P<name>[a-z_]\w*)\s*(?P<closer>=)\s*"+ r"(?:(?:new|const)\s+)?(?P<type>[A-Z]\w*)\s*(?:<(?:[^<>]|<[^<>]*>)*>)?\s*"+ r"\((?![^()]*\)\s*\.(?!\.))"+)+# C++ writes ``T name`` with differences ``_TYPE`` cannot read: ``::`` qualifies,# ``*``/``&`` bind between type and name, and lowercase heads (the STL) are# ordinary. A keyword head is refused, or ``struct foo {`` would declare ``foo``@@ -297,12 +318,14 @@ _C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)_GO_FAMILY = (_GO_PARAM, _GO_SHORT_DECL, _GO_VAR_DECL, _GO_FIELD, _GO_EMBEDDED_FIELD)_KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED)_SWIFT_FAMILY = (_SWIFT_ANNOTATED, _SWIFT_CONSTRUCTED)+_DART_FAMILY = (_DART_TYPED, _DART_CONSTRUCTED)_PY_FAMILY = (_PY_ANNOTATED, _PY_CONSTRUCTED, _PY_SELF_ANNOTATED, _PY_SELF_CONSTRUCTED)_TS_FAMILY = (_TS_ANNOTATED, _TS_PARAMETER_PROPERTY, _TS_CONSTRUCTED)_LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {"cpp": (_CPP_DECLARATION,),"csharp": _C_FAMILY,+ "dart": _DART_FAMILY,"go": _GO_FAMILY,"java": _C_FAMILY,"kotlin": _KT_FAMILY,@@ -319,7 +342,7 @@ RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)# writes ``self.foo.bar()``, a dotted receiver the grammar mints no call site# for, so class scope could only bind a bare local to a field. Membership rests# on the scan actually finding typed fields in the language's idiom.-IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "java", "kotlin", "swift"})+IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "dart", "java", "kotlin", "swift"})# Languages whose scan keeps a declaration of a builtin type, marked external,# so the resolver can refuse a call on it instead of matching the method name.@@ -499,6 +522,19 @@ _LOCAL_NAME_SHAPES: dict[str, tuple[tuple[re.Pattern[str], ...], ...]] = {),(re.compile(r"\((?P<lhs>[\w\s,]*)\)\s*=>"),),),+ "dart": (+ (+ re.compile(+ r"(?<![\w.])(?:final|var|const)\s+(?P<name>[a-z_]\w*)\b(?=\s*(?:[=;,]|in\b))"+ ),+ ),+ # A function literal's list follows punctuation, never a name or `if`.+ (+ re.compile(+ r"(?m)(?:(?<=[(,=:>])|^)\s*\((?P<lhs>[\w\s,]*)\)\s*(?:async\s*)?(?:=>|\{)"+ ),+ ),+ ),"java": _JAVA_LAMBDA,"kotlin": ((@@ -652,6 +688,7 @@ _LANGUAGE_BLOCK_COMMENTS: dict[str, re.Pattern[str]] = {# C++ needs the block strip for the reason Kotlin does: doxygen writes# `@param Type name`, which is exactly the shape the scan reads."cpp": _BLOCK_COMMENT,+ "dart": _BLOCK_COMMENT,"kotlin": _BLOCK_COMMENT,"typescript": _BLOCK_COMMENT,}@@ -659,6 +696,7 @@ _LANGUAGE_BLOCK_COMMENTS: dict[str, re.Pattern[str]] = {_LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {"cpp": _LINE_COMMENT,"csharp": _LINE_COMMENT,+ "dart": _LINE_COMMENT,"go": _LINE_COMMENT,"java": _LINE_COMMENT,"kotlin": _LINE_COMMENT,@@ -756,6 +794,29 @@ def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:return name, inner is not None+# Languages whose constructor parameter lists sit at class scope, unextracted,+# with defaults closing on `=`: a declaration inside parentheses owns no field.+_PARAMETERS_AT_CLASS_SCOPE = frozenset({"dart"})+_PARENTHESIS = re.compile(r"[()]")+++def _inside_parentheses(cleaned: str) -> Callable[[int], bool]:+ """Is an offset of *cleaned* inside a parenthesis? Strings are not skipped."""+ offsets: list[int] = []+ depths: list[int] = []+ depth = 0+ for match in _PARENTHESIS.finditer(cleaned):+ depth += 1 if match.group() == "(" else -1+ offsets.append(match.start())+ depths.append(depth)++ def inside(offset: int) -> bool:+ index = bisect_left(offsets, offset) - 1+ return index >= 0 and depths[index] > 0++ return inside++def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:"""Every declaration *text* makes, in line order."""patterns = _LANGUAGE_PATTERNS.get(language)@@ -771,6 +832,7 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:# walks the string character by character. Resolve each spelling once.resolved: dict[str, tuple[str | None, bool]] = {}found: list[Declaration] = []+ inside = _inside_parentheses(cleaned) if language in _PARAMETERS_AT_CLASS_SCOPE else Nonefor pattern in patterns:for match in pattern.finditer(cleaned):raw = match.group("type")@@ -787,6 +849,8 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:closer = groups.get("closer") or ""if "keyword" in groups and not groups["keyword"]:closer = ""+ if inside is not None and inside(match.start()):+ closer = ""found.append(Declaration(bisect_right(starts, match.start()),diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.pyindex bac5159a3..08eab532f 100644--- a/tests/unit/ingestion/test_call_resolver_strategies.py+++ b/tests/unit/ingestion/test_call_resolver_strategies.py@@ -508,6 +508,16 @@ class TestFieldTypedReceiver:"class Api { public void Nothing() {} }\n","Nothing",),+ (+ "lib/repo.dart",+ "dart",+ "class Repo {\n final Api api;\n Repo(this.api);\n"+ " void a() { api.nothing(); }\n"+ " void b(List<X> items) { items.map((api) => api.nothing()); }\n"+ " void c() { final api = make();\n api.nothing(); }\n}\n"+ "class Api { void nothing() {} }\n",+ "nothing",+ ),],)def test_an_untyped_local_or_lambda_parameter_shadows_the_field(@@ -538,6 +548,30 @@ class TestFieldTypedReceiver:callers = {e[0] for e in edges if e[3].startswith("receiver_field_")}assert callers == {"Repo.swift::Repo::a", "Repo.swift::Repo::b"}+ def test_a_dart_field_and_local_type_their_receivers(self, tmp_path: Path) -> None:+ """A field set by an initialising formal, and a `final x = Foo()` local."""+ parsed = _parse_all(+ tmp_path,+ {+ "lib/repo.dart": (+ "dart",+ "import 'api.dart';\n\nclass Repo {\n final Api api;\n Repo(this.api);\n\n"+ " void load() {\n api.fetch();\n final store = Store();\n"+ " store.get();\n api.missing();\n }\n}\n",+ ),+ "lib/api.dart": (+ "dart",+ "class Api {\n void fetch() {}\n}\nclass Store {\n void get() {}\n}\n",+ ),+ },+ )+ _link_imports(parsed, {"lib/repo.dart": {"api.dart": "lib/api.dart"}})+ edges = _edges(parsed, tmp_path, {"lib/repo.dart": {"lib/api.dart"}, "lib/api.dart": set()})+ caller = "lib/repo.dart::Repo::load"+ assert (caller, "lib/api.dart::Api::fetch", 0.88, "receiver_field_import") in edges+ assert (caller, "lib/api.dart::Store::get", 0.88, "receiver_typed_import") in edges+ assert not [e for e in edges if e[1].endswith("::missing")]+def test_a_nested_class_field_types_its_receiver(self, tmp_path: Path) -> None:"""A nested class's id carries its outer class; its methods' ids do not."""parsed = _parse_all(diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.pyindex 75bfe630e..1bd605a3a 100644--- a/tests/unit/ingestion/test_receiver_types.py+++ b/tests/unit/ingestion/test_receiver_types.py@@ -540,6 +540,67 @@ class TestSwiftRefusals:assert fields(source, "swift", [])["store"] == "Store"+class TestDartShapes:+ def test_a_typed_local(self) -> None:+ assert declared_types("void f() {\n Cache cache = make();\n}", "dart")["cache"] == "Cache"++ def test_a_parameter_and_a_named_parameter(self) -> None:+ types = declared_types("void f(Api api, {required Dao dao}) { }", "dart")+ assert (types["api"], types["dao"]) == ("Api", "Dao")++ def test_a_nullable_type_keeps_its_type(self) -> None:+ assert declared_types("void f() {\n Api? api;\n}", "dart")["api"] == "Api"++ @pytest.mark.parametrize(+ "line",+ ["final store = Store();", "var store = new Store();", "const store = Store<A>();"],+ )+ def test_a_construction(self, line: str) -> None:+ assert declared_types(f"void f() {{\n {line}\n}}", "dart")["store"] == "Store"++ def test_a_cascade_is_still_the_constructed_type(self) -> None:+ body = "void f() {\n final paint = Paint()..color = c;\n}"+ assert declared_types(body, "dart")["paint"] == "Paint"++ @pytest.mark.parametrize(+ "line", ["final x = Builder().build();", "final x = Store.instance();"]+ )+ def test_a_chain_or_static_call_types_nothing(self, line: str) -> None:+ assert declared_types(f"void f() {{\n {line}\n}}", "dart") == {}++ def test_a_doc_comment_is_not_a_declaration(self) -> None:+ body = "/// Returns Foo instance;\n/* Bar other; */\nvoid f() { }"+ assert declared_types(body, "dart") == {}++ def test_dart_reaches_class_scope(self) -> None:+ assert "dart" in IMPLICIT_FIELD_LANGUAGES+++class TestDartFieldScope:+ def test_fields_and_initialising_formals(self) -> None:+ """`this.api` spells no type; the field it assigns types `api`."""+ source = (+ "class Repo {\n final Api api;\n Dao? _dao;\n final _store = Store();\n"+ " Repo(this.api, Dao dao, {Other other}) : _dao = dao;\n"+ " void load() { api.fetch(); }\n}"+ )+ assert fields(source, "dart", [(6, 6)]) == {"api": "Api", "_dao": "Dao", "_store": "Store"}++ def test_a_method_local_is_not_a_field(self) -> None:+ source = "class C {\n void f() {\n final s = Store();\n }\n}"+ assert fields(source, "dart", [(2, 4)]) == {}++ def test_a_defaulted_constructor_parameter_is_not_a_field(self) -> None:+ """A constructor is no symbol, so `{Dao d = const Dao()}` closes on `=`+ at class scope exactly as a field does. Being inside parentheses is+ what refuses it."""+ source = (+ "class Repo {\n final Api api;\n Repo(this.api, {Dao d = const Dao()});\n"+ " void a() { d.read(); }\n}"+ )+ assert fields(source, "dart", [(4, 4)]) == {"api": "Api"}++class TestGoShapes:"""Go writes ``name T``, which is the reverse of every other shape here.@@ -771,6 +832,7 @@ def test_the_language_set_is_what_the_patterns_declare() -> None:assert set(RECEIVER_TYPE_LANGUAGES) == {"cpp","csharp",+ "dart","go","java","kotlin",