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(core): resolve calls on a chained field receiver (#2703)

Swati Ahujaf7a59146989a
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 69180f8e9..3c0001c04 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -73,6 +73,8 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {
# 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),
+ # TypeScript's typed fallback also walks a dotted receiver's fields.
+ "typescript": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),
"cpp": _CPP_STRATEGIES,
"c": _CPP_STRATEGIES,
}
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 9dce9a94d..f9e80798f 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -7,11 +7,15 @@ from pathlib import Path
from typing import TypeVar
from .languages.receiver_types import (
+ BINDING_LANGUAGES,
FRAMEWORK_DECORATOR_LANGUAGES,
IMPLICIT_FIELD_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
Declaration,
+ bound_types,
framework_decorated_type,
+ in_spans,
+ merge_spans,
names_in_span,
scan_bindings,
scan_declarations,
@@ -19,7 +23,7 @@ from .languages.receiver_types import (
types_in_span,
unwrapped_names_in_span,
)
-from .models import CallSite, Symbol
+from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
from .type_names import POINTER_LIKE_MEMBERS
@@ -30,6 +34,17 @@ _TYPE_KINDS = frozenset({"class", "struct", "interface", "enum", "trait", "impl"
_FUNCTION_KINDS = frozenset({"function", "method"})
_SOURCE_CACHE_FILES = 4
+
+# Languages whose grammar mints ``a.b.c.m()`` with the dotted path as its
+# receiver, every segment after the head a field. Go's selector receiver is
+# absent: ``pkg.Var`` and ``s.field`` are one shape there. Each maps to the
+# name that means the caller's own instance; TypeScript's ``self`` is a
+# global, not ``this``.
+_CHAIN_SELF = {"python": "self", "typescript": "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.
+_CHAIN_TIER_RANK = {"same_file": 0, "import": 1}
_BODY_TYPE_CACHE_ENTRIES = 2048
_K = TypeVar("_K")
@@ -47,6 +62,21 @@ def _is_module_level_function(symbol: Symbol) -> bool:
return symbol.kind in _FUNCTION_KINDS and not symbol.parent_name
+def _enclosing_id(symbol_id: str) -> str:
+ """The id of the symbol enclosing *symbol_id*: a method's class."""
+ # Our own ``path::Class::method`` ID separator, not a type qualifier.
+ return symbol_id.rpartition("::")[0]
+
+
+def _types_by_name(parsed: ParsedFile) -> dict[str, list[str]]:
+ """``{name: [type symbol ids]}`` for the types one file declares."""
+ by_name: dict[str, list[str]] = {}
+ for symbol in parsed.symbols:
+ if symbol.kind in _TYPE_KINDS:
+ by_name.setdefault(symbol.name, []).append(symbol.id)
+ return by_name
+
+
class ReceiverTypingMixin:
"""Typed-receiver and C# extension strategies, with the source caches they read."""
@@ -59,6 +89,9 @@ class ReceiverTypingMixin:
self._symbol_spans: dict[str, dict[str, tuple[int, int]]] = {}
self._body_types: dict[tuple[str, str], dict[str, str | None]] = {}
self._field_types: dict[str, dict[str, dict[str, str | None]]] = {}
+ self._module_types: dict[str, dict[str, str | None]] = {}
+ # {file: {type name: [type symbol ids]}}, built once on first use.
+ self._type_ids: dict[str, dict[str, list[str]]] | None = None
self._bindings: dict[str, tuple[tuple[int, str], ...]] = {}
self._bound_names: dict[tuple[str, str], frozenset[str]] = {}
# {file: {name: type}} — module-level defs a framework decorator retyped.
@@ -210,6 +243,10 @@ class ReceiverTypingMixin:
return None
receiver_name = call.receiver_name or ""
+ if "." in receiver_name:
+ if language not in _CHAIN_SELF:
+ return None
+ return self._resolve_chained_receiver(file_path, call, caller_id, language)
type_name, scope = self._receiver_type_and_scope(
file_path, caller_id, language, receiver_name
)
@@ -240,26 +277,150 @@ class ReceiverTypingMixin:
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.
+ type". Only a name the body never mentions reaches class scope, and
+ only a name neither binds reaches module scope.
"""
body_types = self._declared_types_in(file_path, caller_id, language)
if receiver_name in body_types:
return body_types[receiver_name], "body"
- type_name, scope = None, "body"
if language in IMPLICIT_FIELD_LANGUAGES:
- class_id = caller_id.rpartition("::")[0]
- type_name = (
- self._field_types_in(file_path, language).get(class_id, {}).get(receiver_name)
- )
- scope = "field"
+ class_id = _enclosing_id(caller_id)
+ fields = self._field_types_in(file_path, language).get(class_id, {})
+ if receiver_name in fields:
+ return fields[receiver_name], "field"
# Third scope: a module-level def a framework decorator turned into an
# instance, which is neither in the body nor a field.
- if type_name is None and language in FRAMEWORK_DECORATOR_LANGUAGES:
- return (
- self._framework_receiver_type(file_path, caller_id, language, receiver_name),
- "framework",
- )
- return type_name, scope
+ if language in FRAMEWORK_DECORATOR_LANGUAGES:
+ type_name = self._framework_receiver_type(file_path, caller_id, language, receiver_name)
+ if type_name is not None:
+ return type_name, "framework"
+ return self._module_receiver_type(file_path, caller_id, language, receiver_name), "body"
+
+ def _module_receiver_type(
+ self,
+ file_path: str,
+ caller_id: str,
+ language: str,
+ receiver_name: str,
+ ) -> str | None:
+ """The type a module-scope declaration gives *receiver_name*, if unshadowed.
+
+ Asked only where a binding scan can prove the name is not a local:
+ every function enclosing the caller is checked, since a closure's
+ parameter shadows the module name just as the caller's own does.
+ """
+ if language not in BINDING_LANGUAGES:
+ return None
+ type_name = self._module_types_in(file_path, language).get(receiver_name)
+ if type_name is None:
+ return None
+ span = self._spans_for(file_path).get(caller_id)
+ if span is not None:
+ bindings = self._bindings_for(file_path, language)
+ for start, end in (span, *self._enclosing_function_spans(file_path, span)):
+ if receiver_name in names_in_span(bindings, start, end):
+ return None
+ return type_name
+
+ def _enclosing_function_spans(
+ self, file_path: str, span: tuple[int, int]
+ ) -> list[tuple[int, int]]:
+ parsed = self._parsed_files.get(file_path)
+ return [
+ (s.start_line, s.end_line)
+ for s in (parsed.symbols if parsed else ())
+ if s.kind in _FUNCTION_KINDS and s.start_line <= span[0] and span[1] <= s.end_line
+ ]
+
+ def _resolve_chained_receiver(
+ self,
+ file_path: str,
+ call: CallSite,
+ caller_id: str,
+ language: str,
+ ) -> ResolvedCall | None:
+ """Resolve ``h.f1…fn.m()`` by typing ``h``, then each field in turn.
+
+ ``this`` (Python's ``self``) is the caller's own class. Every hop must name
+ exactly one class, bound by an import or declared in the file that
+ wrote the type, and the last class must itself declare the method: a
+ field whose type is a union, a builtin, a bare type parameter or
+ missing refuses the whole chain.
+ """
+ # An instance path, not a type name: the head is a variable and every
+ # later segment a field, so each is walked, none discarded.
+ 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)
+ for field in fields:
+ if found is None:
+ return None
+ found = self._chain_hop(found, field, language)
+ if found is None:
+ return None
+
+ _, class_id, tier = found
+ sym_id = self._declares(class_id, call.target_name)
+ if sym_id is None or sym_id == caller_id:
+ return None
+ if tier == "same_file":
+ return ResolvedCall(caller_id, sym_id, 0.93, call.line, "receiver_chain_same_file")
+ 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
+ ) -> tuple[str, str, str] | None:
+ """``(file, class id, tier)`` for a chain's head name."""
+ if head == _CHAIN_SELF[language]:
+ class_id = _enclosing_id(caller_id)
+ symbol = self._symbols_by_id.get(class_id)
+ if symbol is None or symbol.kind not in _TYPE_KINDS:
+ return None
+ return file_path, class_id, "same_file"
+ type_name, _ = self._receiver_type_and_scope(file_path, caller_id, language, head)
+ return None if type_name is None else self._class_named(file_path, type_name)
+
+ def _chain_hop(
+ self, found: tuple[str, str, str], field: str, language: str
+ ) -> tuple[str, str, str] | None:
+ """The class *field* of *found*'s class holds, tiered by the weaker hop."""
+ class_file, class_id, tier = found
+ type_name = self._field_types_in(class_file, language).get(class_id, {}).get(field)
+ hop = None if type_name is None else self._class_named(class_file, type_name)
+ if hop is None:
+ return None
+ return hop[0], hop[1], max(tier, hop[2], key=_CHAIN_TIER_RANK.__getitem__)
+
+ def _class_named(self, file_path: str, type_name: str) -> tuple[str, str, str] | None:
+ """``(file, class id, tier)`` for the one class *type_name* names in *file_path*.
+
+ The name must be imported (a re-export followed to its declaration)
+ or declared in *file_path* itself, and name exactly one type there:
+ no repo-wide guess, since every hop of a chain rests on this.
+ """
+ bound = self._import_names.get(file_path, {}).get(type_name)
+ if bound is not None:
+ if bound.startswith("external:"):
+ return None
+ binding = self._import_bindings.get(file_path, {}).get(type_name)
+ exported = (binding.exported_name if binding else None) or type_name
+ declaring = self._barrel_origins.get(bound, {}).get(exported) or bound
+ class_id = self._only_type_in(declaring, exported)
+ return None if class_id is None else (declaring, class_id, "import")
+ 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")
+
+ 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*."""
+ if self._type_ids is None:
+ self._type_ids = {
+ path: _types_by_name(parsed) for path, parsed in self._parsed_files.items()
+ }
+ ids = self._type_ids.get(file_path, {}).get(type_name, ())
+ return ids[0] if len(ids) == 1 else None
def _framework_receiver_type(
self,
@@ -319,7 +480,7 @@ class ReceiverTypingMixin:
)
def _body_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:
- """Stamp an edge whose receiver was typed from the calling body."""
+ """Stamp an edge whose receiver was typed from the calling body or module scope."""
if tier == "same_file":
return ResolvedCall(caller_id, sym_id, 0.93, line, "receiver_typed_same_file")
if tier == "same_package":
@@ -427,14 +588,62 @@ class ReceiverTypingMixin:
return types
span = self._spans_for(file_path).get(caller_id)
+ declarations = self._declarations_for(file_path, language)
if span is None:
types = {}
+ elif language in BINDING_LANGUAGES:
+ start, end = span
+ types = bound_types(
+ (d for d in declarations if start <= d.line <= end),
+ (b for b in self._bindings_for(file_path, language) if start <= b[0] <= end),
+ language,
+ )
else:
- types = types_in_span(self._declarations_for(file_path, language), *span)
+ types = types_in_span(declarations, *span)
_store_capped(self._body_types, key, types, _BODY_TYPE_CACHE_ENTRIES)
return types
+ def _module_types_in(self, file_path: str, language: str) -> dict[str, str | None]:
+ """``{name: type}`` for the declarations one file makes at module scope.
+
+ A line is at module scope when no function or type encloses it and
+ any other symbol enclosing it is the declared name itself (the
+ ``const client = …`` it sits in). That keeps an object literal's keys
+ and a type alias's members out.
+ """
+ types = self._module_types.get(file_path)
+ if types is not None:
+ return types
+ parsed = self._parsed_files.get(file_path)
+ symbols = parsed.symbols if parsed else ()
+ blocked = merge_spans(
+ (s.start_line, s.end_line)
+ for s in symbols
+ if s.kind in _FUNCTION_KINDS or s.kind in _TYPE_KINDS
+ )
+ owners: dict[int, str] = {}
+ for s in symbols:
+ if s.kind not in _FUNCTION_KINDS and s.kind not in _TYPE_KINDS:
+ for line in range(s.start_line, s.end_line + 1):
+ owners[line] = s.name
+
+ def at_module_scope(line: int, name: str) -> bool:
+ return not in_spans(blocked, line) and owners.get(line, name) == name
+
+ types = bound_types(
+ (
+ d
+ for d in self._declarations_for(file_path, language)
+ if at_module_scope(d.line, d.name)
+ ),
+ (b for b in self._bindings_for(file_path, language) if at_module_scope(*b)),
+ language,
+ rebinding_refuses=True,
+ )
+ _store_capped(self._module_types, file_path, types, _SOURCE_CACHE_FILES)
+ return types
+
def _field_types_in(
self,
file_path: str,
@@ -452,6 +661,7 @@ class ReceiverTypingMixin:
self._declarations_for(file_path, language),
class_spans,
[(s.start_line, s.end_line) for s in symbols if s.kind in _FUNCTION_KINDS],
+ language,
)
_store_capped(self._field_types, file_path, by_class, _SOURCE_CACHE_FILES)
return by_class
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 0ddb6b140..e7a2aff7a 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -82,6 +82,46 @@ _PY_CONSTRUCTED = re.compile(
r"(?m)^[ \t]*(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\("
)
+# ``self.x: T`` and ``self.x = T(...)`` in a method: the fields a Python class
+# gives its instances. The ``member`` group marks a declaration of the
+# enclosing class wherever it sits, never of the body that makes it. A chain
+# is refused as ``_KT_CONSTRUCTED`` refuses one.
+_PY_SELF_ANNOTATED = re.compile(
+ rf"(?m)^[ \t]*(?P<member>self)\.(?P<name>[a-z_]\w*)\s*:\s*(?P<type>{_PY_TYPE})\s*(?=[=\n])"
+)
+_PY_SELF_CONSTRUCTED = re.compile(
+ r"(?m)^[ \t]*(?P<member>self)\.(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*"
+ r"\((?![^()]*\)\s*\.)"
+)
+
+# TypeScript annotates after the name: parameters, fields, ``const x: T``. An
+# optional or definite marker (``x?: T``, ``x!: T``) still leaves a ``T``. The
+# type is bare or generic and must be followed by a closer at once, which
+# refuses a union (``T | null``), an array (``T[]``), a qualified name and a
+# function type. A ternary's ``a ? b : C`` is refused by the lookbehinds.
+_TS_NAME = r"[a-z_$][\w$]*"
+_TS_TYPE = r"[A-Z][\w$]*(?:<(?:[^<>]|<[^<>]*>)*>)?"
+_TS_ANNOTATED = re.compile(
+ rf"(?<![\w$.?])(?<!\?\s)(?P<name>{_TS_NAME})\s*[?!]?\s*:\s*(?P<type>{_TS_TYPE})"
+ rf"\s*(?=(?P<closer>[=;,)\n]))"
+)
+
+# An accessibility modifier makes a constructor parameter a field of its class
+# as well (``constructor(private readonly svc: Svc)``). ``_TS_ANNOTATED`` still
+# reads the same text as the parameter.
+_TS_PARAMETER_PROPERTY = re.compile(
+ rf"(?<![\w$.])(?P<member>private|protected|public|readonly)\s+(?:readonly\s+)?"
+ rf"(?P<name>{_TS_NAME})\s*[?!]?\s*:\s*(?P<type>{_TS_TYPE})\s*(?=[=,)])"
+)
+
+# ``x = new T(...)``, declared or assigned, a field initialiser included. The
+# ``=`` is the closer, so at class scope it is a field. Refuses a chain as
+# ``_KT_CONSTRUCTED`` does: ``new Builder().build()`` is not a ``Builder``.
+_TS_CONSTRUCTED = re.compile(
+ rf"(?<![\w$.])(?P<name>{_TS_NAME})\s*(?P<closer>=)\s*new\s+(?P<type>[A-Z][\w$]*)\s*"
+ r"(?:<(?:[^<>]|<[^<>]*>)*>)?\s*\((?![^()]*\)\s*\.)"
+)
+
# Go writes the name before the type. A type may be lowercase (unexported);
# that is safe only because ``builtin_types`` carries every predeclared
# identifier, so ``string`` and ``error`` are refused downstream. A method's
@@ -195,6 +235,8 @@ _C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)
_GO_FAMILY = (_GO_PARAM, _GO_SHORT_DECL, _GO_VAR_DECL)
_KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED)
_SWIFT_FAMILY = (_SWIFT_ANNOTATED, _SWIFT_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,),
@@ -202,8 +244,9 @@ _LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
"go": _GO_FAMILY,
"java": _C_FAMILY,
"kotlin": _KT_FAMILY,
- "python": (_PY_ANNOTATED, _PY_CONSTRUCTED),
+ "python": _PY_FAMILY,
"swift": _SWIFT_FAMILY,
+ "typescript": _TS_FAMILY,
}
RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)
@@ -253,26 +296,80 @@ _PY_BINDINGS = (
re.compile(r"\bas\s+(?P<name>[a-z_]\w*)\b"),
re.compile(r"\b(?P<name>[a-z_]\w*)\s*:="),
re.compile(r"\b(?:global|nonlocal)\s+(?P<name>[a-z_]\w*)"),
- # A parameter of any `def` or `lambda` in the span, the enclosing one
- # included: its signature line is the first line of its own span.
- re.compile(r"\b(?:def\s+\w+\s*\(|lambda\s+)[^)\n:]*?\b(?P<name>[a-z_]\w*)\s*(?=[,=)\n:])"),
)
+# Every parameter of any `def` or `lambda` in the span, the enclosing one
+# included: its signature starts its own span. Each lowercase identifier in the
+# list counts, a default's names too, since over-matching only refuses.
+# Ceiling: a `def` list ends at its first `)`, so a default that calls hides
+# the parameters after it.
+_PY_PARAMETER_LISTS = (
+ re.compile(r"\bdef\s+\w+\s*\((?P<lhs>[^)]*)\)"),
+ re.compile(r"\blambda\b(?P<lhs>[^:\n]*):"),
+)
+_PY_NAME = re.compile(r"(?<![\w.])[a-z_]\w*")
+
# A plain `import` in a body is deliberately absent: it names the same module
# symbol this scope resolves against (`from .tasks import ping`; `ping.delay()`).
_PY_IDENTIFIER = re.compile(r"^[a-z_]\w*$")
-
-def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:
- """Every ``(line, name)`` *text* binds, in line order."""
- if language != "python":
- return ()
- cleaned = _DOCSTRING.sub(lambda m: "\n" * m.group(0).count("\n"), text)
- cleaned = _HASH_COMMENT.sub("", cleaned)
- starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+# The TypeScript shapes that bind a name, typed or not. Over-matching only
+# refuses, so every identifier in a destructuring pattern or a parameter list
+# counts, a type name or a renamed key included. Ceiling: a parameter list
+# holding parentheses (a default that calls, a function type) is not read.
+_TS_IDENTIFIER = re.compile(r"[A-Za-z_$][\w$]*")
+_TS_BINDINGS = (
+ re.compile(r"(?<![\w$.])(?:const|let|var)\s+(?P<name>[A-Za-z_$][\w$]*)"),
+ re.compile(r"(?<![\w$.])(?:function\*?|class)\s+(?P<name>[A-Za-z_$][\w$]*)"),
+ re.compile(r"(?<![\w$.])(?P<name>[A-Za-z_$][\w$]*)\s*=>"),
+ # An assignment at the start of a statement, plain or compound.
+ re.compile(
+ r"(?m)^[ \t]*(?P<name>[A-Za-z_$][\w$]*)\s*"
+ r"(?:[-+*/%|&^]|\*\*|\?\?|\|\||&&|<<|>>>?)?=(?![=>])"
+ ),
+)
+_TS_TARGET_LISTS = (
+ re.compile(r"(?<![\w$.])(?:const|let|var)\s*(?P<lhs>\{[^;=]*\}|\[[^;=]*\])\s*(?:=|of\b|in\b)"),
+ # A parameter list: a function, a method, an arrow, a catch clause.
+ re.compile(r"(?P<head>[\w$]*)\s*(?P<lhs>\([^()]*\))\s*(?::[^=;{}()]*?)?\s*(?:=>|\{)"),
+)
+# Heads whose parenthesised part is a condition, not a parameter list.
+_TS_CONDITION_HEADS = frozenset({"if", "for", "while", "switch", "with", "return", "await"})
+
+
+def _named_bindings(
+ patterns: Iterable[re.Pattern[str]], cleaned: str, starts: list[int]
+) -> set[tuple[int, str]]:
+ """``(line, name)`` for each pattern's ``name`` group."""
+ return {
+ (bisect_right(starts, match.start("name")), match.group("name"))
+ for pattern in patterns
+ for match in pattern.finditer(cleaned)
+ }
+
+
+def _listed_bindings(
+ patterns: Iterable[re.Pattern[str]],
+ identifier: re.Pattern[str],
+ cleaned: str,
+ starts: list[int],
+) -> set[tuple[int, str]]:
+ """``(line, name)`` for every identifier in each pattern's ``lhs`` list."""
found: set[tuple[int, str]] = set()
+ for pattern in patterns:
+ for match in pattern.finditer(cleaned):
+ # Only TypeScript's lists carry a ``head`` to refuse.
+ if match.groupdict().get("head") in _TS_CONDITION_HEADS:
+ continue
+ offset = match.start("lhs")
+ for name in identifier.finditer(match.group("lhs")):
+ found.add((bisect_right(starts, offset + name.start()), name.group()))
+ return found
+
+def _python_target_bindings(cleaned: str, starts: list[int]) -> set[tuple[int, str]]:
+ found: set[tuple[int, str]] = set()
for pattern in _PY_TARGET_LISTS:
for match in pattern.finditer(cleaned):
line = bisect_right(starts, match.start("lhs"))
@@ -281,10 +378,27 @@ def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:
name = target.strip()
if _PY_IDENTIFIER.match(name):
found.add((line, name))
+ return found
- for pattern in _PY_BINDINGS:
- for match in pattern.finditer(cleaned):
- found.add((bisect_right(starts, match.start("name")), match.group("name")))
+
+# The languages ``scan_bindings`` reads: only there can a scope be shown not
+# to bind a name.
+BINDING_LANGUAGES = frozenset({"python", "typescript"})
+
+
+def scan_bindings(text: str, language: str) -> tuple[tuple[int, str], ...]:
+ """Every ``(line, name)`` *text* binds, in line order."""
+ if language not in BINDING_LANGUAGES:
+ return ()
+ cleaned = _without_comments(text, language)
+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+ if language == "typescript":
+ found = _named_bindings(_TS_BINDINGS, cleaned, starts)
+ found |= _listed_bindings(_TS_TARGET_LISTS, _TS_IDENTIFIER, cleaned, starts)
+ else:
+ found = _python_target_bindings(cleaned, starts)
+ found |= _named_bindings(_PY_BINDINGS, cleaned, starts)
+ found |= _listed_bindings(_PY_PARAMETER_LISTS, _PY_NAME, cleaned, starts)
return tuple(sorted(found))
@@ -314,6 +428,7 @@ _LANGUAGE_BLOCK_COMMENTS: dict[str, re.Pattern[str]] = {
# `@param Type name`, which is exactly the shape the scan reads.
"cpp": _BLOCK_COMMENT,
"kotlin": _BLOCK_COMMENT,
+ "typescript": _BLOCK_COMMENT,
}
_LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {
@@ -324,9 +439,24 @@ _LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {
"kotlin": _LINE_COMMENT,
"swift": _LINE_COMMENT,
"python": _HASH_COMMENT,
+ "typescript": _LINE_COMMENT,
}
+def _without_comments(text: str, language: str) -> str:
+ """*text* with its comments (and Python docstrings) blanked, newlines kept."""
+ cleaned = text
+ if language == "python":
+ cleaned = _DOCSTRING.sub(lambda m: "\n" * m.group(0).count("\n"), cleaned)
+ block = _LANGUAGE_BLOCK_COMMENTS.get(language)
+ if block is not None:
+ cleaned = block.sub(lambda m: "\n" * m.group(0).count("\n"), cleaned)
+ comment = _LANGUAGE_COMMENTS.get(language)
+ if comment is not None:
+ cleaned = comment.sub("", cleaned)
+ return cleaned
+
+
class Declaration(NamedTuple):
"""One name given one type, at one line.
@@ -336,6 +466,10 @@ class Declaration(NamedTuple):
``unwrapped`` marks a type taken from inside a pointer-like wrapper, which
answers differently by call operator; a caller that cannot see the
operator refuses these names.
+
+ ``member`` marks a field of the enclosing class declared from inside a
+ method (``self.x = T()``, a constructor parameter property). It belongs
+ to the class wherever it sits, and never to the body.
"""
line: int
@@ -343,12 +477,20 @@ class Declaration(NamedTuple):
type_name: str
closer: str = ""
unwrapped: bool = False
+ member: bool = False
# What can end a field. `var` has no place here at all: it is a local-only
# shape in both languages, so it carries no closer and class scope drops it.
_FIELD_CLOSERS = frozenset({";", "="})
+# Where a class-scope annotation may end its line: Python's ``x: T`` and a
+# semicolon-free TypeScript ``x: T`` are fields too.
+_LANGUAGE_FIELD_CLOSERS: dict[str, frozenset[str]] = {
+ "python": frozenset({"=", "\n"}),
+ "typescript": frozenset({";", "=", "\n"}),
+}
+
def _nests_in_a_builtin(raw: str, language: str) -> bool:
"""True for ``Map.Entry`` and its kind — a member type of a builtin.
@@ -384,15 +526,7 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
if not patterns:
return ()
- cleaned = text
- if language == "python":
- cleaned = _DOCSTRING.sub(lambda m: "\n" * m.group(0).count("\n"), cleaned)
- block = _LANGUAGE_BLOCK_COMMENTS.get(language)
- if block is not None:
- cleaned = block.sub(lambda m: "\n" * m.group(0).count("\n"), cleaned)
- comment = _LANGUAGE_COMMENTS.get(language)
- if comment is not None:
- cleaned = comment.sub("", cleaned)
+ cleaned = _without_comments(text, language)
# Scanned by the regex engine rather than a Python loop over characters:
# the loop costs more than the declaration scan it exists to serve.
starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
@@ -422,6 +556,7 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
type_name,
closer,
unwrapped,
+ bool(groups.get("member")),
)
)
@@ -455,8 +590,42 @@ def types_in_span(
for declaration in declarations[first:]:
if declaration.line > end_line:
break
- _record(types, declaration)
+ if not declaration.member:
+ _record(types, declaration)
+
+ return types
+
+def bound_types(
+ declarations: Iterable[Declaration],
+ bindings: Iterable[tuple[int, str]],
+ language: str,
+ *,
+ rebinding_refuses: bool = False,
+) -> dict[str, str | None]:
+ """``{name: type}`` for one scope, read against every name it binds.
+
+ In TypeScript a declaration must itself be a binding (``const``, ``let``,
+ a parameter, an assignment), which keeps an object literal's
+ ``key: Value`` from declaring ``key``. Under *rebinding_refuses* a name the
+ scope also binds untyped on another line maps to ``None``: asked of module
+ scope, where the rebinding can run anywhere before the call. A body keeps
+ its first reading, as ``types_in_span`` does.
+ """
+ bound = set(bindings)
+ types: dict[str, str | None] = {}
+ typed: set[tuple[int, str]] = set()
+ for declaration in declarations:
+ if declaration.member:
+ continue
+ spot = (declaration.line, declaration.name)
+ if language == "typescript" and spot not in bound:
+ continue
+ _record(types, declaration)
+ typed.add(spot)
+ for spot in bound - typed if rebinding_refuses else ():
+ if spot[1] in types:
+ types[spot[1]] = None
return types
@@ -478,7 +647,7 @@ def unwrapped_names_in_span(
)
-def _merged(spans: Iterable[tuple[int, int]]) -> tuple[tuple[int, int], ...]:
+def merge_spans(spans: Iterable[tuple[int, int]]) -> tuple[tuple[int, int], ...]:
"""The spans as non-overlapping, ascending intervals."""
merged: list[list[int]] = []
for start, end in sorted(spans):
@@ -489,33 +658,43 @@ def _merged(spans: Iterable[tuple[int, int]]) -> tuple[tuple[int, int], ...]:
return tuple((start, end) for start, end in merged)
+def in_spans(merged: tuple[tuple[int, int], ...], line: int) -> bool:
+ """Is *line* inside one of ``merge_spans``' intervals?"""
+ index = bisect_right(merged, (line, float("inf"))) - 1
+ return index >= 0 and line <= merged[index][1]
+
+
def types_by_class(
declarations: tuple[Declaration, ...],
class_spans: Mapping[str, tuple[int, int]],
function_spans: Iterable[tuple[int, int]],
+ language: str = "",
) -> dict[str, dict[str, str | None]]:
"""``{class_id: {name: type}}`` for the fields each class declares.
A class span contains every method body inside it, so a declaration is a
field only if it lies inside the class and inside none of the file's
- functions. Nested classes go to the innermost class containing them, so an
- inner class's fields never answer for the outer one.
+ functions, unless it is a ``member``. Nested classes go to the innermost
+ class containing them, so an inner class's fields never answer for the
+ outer one.
"""
+ closers = _LANGUAGE_FIELD_CLOSERS.get(language, _FIELD_CLOSERS)
if not class_spans:
return {}
- bodies = _merged(function_spans)
+ bodies = merge_spans(function_spans)
body_starts = [start for start, _ in bodies]
# Innermost first, so the first containing span is the owner.
ordered = sorted(class_spans.items(), key=lambda item: item[1][1] - item[1][0])
by_class: dict[str, dict[str, str | None]] = {}
for declaration in declarations:
- if declaration.closer not in _FIELD_CLOSERS:
- continue
- index = bisect_right(body_starts, declaration.line) - 1
- if index >= 0 and declaration.line <= bodies[index][1]:
- continue
+ if not declaration.member:
+ if declaration.closer not in closers:
+ continue
+ index = bisect_right(body_starts, declaration.line) - 1
+ if index >= 0 and declaration.line <= bodies[index][1]:
+ continue
for class_id, (start, end) in ordered:
if start <= declaration.line <= end:
_record(by_class.setdefault(class_id, {}), declaration)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index a6ca55247..107fe78e5 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -466,6 +466,12 @@ ResolutionOrigin = Literal[
"receiver_extension_same_file", # 0.93
"receiver_extension_import", # 0.88 — the holder class's file is imported
"receiver_extension_global", # 0.75 — declared somewhere; a name match
+ # A dotted receiver (`this.a.b.m()`) typed hop by hop through each class's
+ # declared fields. No global tier: every hop's type must be bound by an
+ # import or declared in the file that wrote it, and the tier is the
+ # weakest hop's.
+ "receiver_chain_same_file", # 0.93
+ "receiver_chain_import", # 0.88
# Chained receiver typed from the inner callee's declared return type.
"return_type_same_file", # 0.93
"return_type_same_package", # 0.90 (JVM)
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index a31501c9f..bcc8ffca1 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -414,6 +414,27 @@ def grammar_tag_for(language: str, path: str) -> str:
_node_text = node_text
+# 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.
+_PATH_RECEIVERS = frozenset({("typescript", "member_expression"), ("python", "attribute")})
+_DOTTED_PATH = re.compile(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+")
+
+
+def _receiver_text(language: str, node: Node, src: str) -> str | None:
+ """The receiver's text, or None to drop the site.
+
+ A dotted receiver (``this.a.b.m()``) is kept only as a plain path of
+ names: a call, subscript or optional hop inside it types nothing, and
+ dropping the site keeps it off the bare-call tiers.
+ """
+ text = _node_text(node, src).strip()
+ if (language, node.type) not in _PATH_RECEIVERS:
+ return text
+ path = "".join(text.split())
+ return path if _DOTTED_PATH.fullmatch(path) else None
+
+
def _normalize_php_receiver(text: str) -> str:
"""Spell PHP's receiver the way the resolver's strategies expect.
@@ -1734,7 +1755,11 @@ class ASTParser:
continue
line = site_node.start_point[0] + 1
- receiver_name = _node_text(receiver_nodes[0], src).strip() if receiver_nodes else None
+ receiver_name = None
+ if receiver_nodes:
+ receiver_name = _receiver_text(file_info.language, receiver_nodes[0], src)
+ if receiver_name is None:
+ continue
if receiver_name and file_info.language == "php":
receiver_name = _normalize_php_receiver(receiver_name)
# F#: a dotted static path (``Path.Combine(a, b)``) collapses into
diff --git a/packages/core/src/repowise/core/ingestion/queries/python.scm b/packages/core/src/repowise/core/ingestion/queries/python.scm
index 9966f585b..4a928f737 100644
--- a/packages/core/src/repowise/core/ingestion/queries/python.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/python.scm
@@ -82,10 +82,11 @@
arguments: (argument_list) @call.arguments
) @call.site
-; Method call: obj.method(arg1, arg2)
+; Method call: obj.method(arg1, arg2), and obj.a.b.method() -- an attribute
+; receiver is kept only when it is a plain dotted path, which the parser checks.
(call
function: (attribute
- object: (identifier) @call.receiver
+ object: [(identifier) (attribute)] @call.receiver
attribute: (identifier) @call.target
)
arguments: (argument_list) @call.arguments
diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
index 50fe47749..5f953542f 100644
--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
@@ -265,9 +265,12 @@
; parse time on angular for the two-pattern form, ~0% for this one), and there
; is no duplicate rule to keep in sync. ``receiver_name`` then reads "this",
; which call_resolver Strategy 3 already resolves against the caller's class.
+; A member_expression receiver (``this.a.b.m()``) is kept only when it is a
+; plain dotted path, which the parser checks; the resolver types it field by
+; field.
(call_expression
function: (member_expression
- object: [(identifier) (this)] @call.receiver
+ object: [(identifier) (this) (member_expression)] @call.receiver
property: [(property_identifier) (private_property_identifier)] @call.target
)
arguments: (arguments) @call.arguments
diff --git a/packages/types/src/graph.ts b/packages/types/src/graph.ts
index f3fcabc5c..fd777bf50 100644
--- a/packages/types/src/graph.ts
+++ b/packages/types/src/graph.ts
@@ -313,6 +313,8 @@ export type ResolutionOrigin =
| "receiver_extension_same_file"
| "receiver_extension_import"
| "receiver_extension_global"
+ | "receiver_chain_same_file"
+ | "receiver_chain_import"
| "return_type_same_file"
| "return_type_same_package"
| "return_type_import"
diff --git a/packages/ui/__tests__/graph/edge-provenance.test.ts b/packages/ui/__tests__/graph/edge-provenance.test.ts
index 61d39f93f..09ecf6790 100644
--- a/packages/ui/__tests__/graph/edge-provenance.test.ts
+++ b/packages/ui/__tests__/graph/edge-provenance.test.ts
@@ -54,6 +54,8 @@ const ALL_ORIGINS: ResolutionOrigin[] = [
"receiver_extension_same_file",
"receiver_extension_import",
"receiver_extension_global",
+ "receiver_chain_same_file",
+ "receiver_chain_import",
"return_type_same_file",
"return_type_same_package",
"return_type_import",
diff --git a/packages/ui/src/graph/edge-provenance.ts b/packages/ui/src/graph/edge-provenance.ts
index edba2f034..68cbc52cc 100644
--- a/packages/ui/src/graph/edge-provenance.ts
+++ b/packages/ui/src/graph/edge-provenance.ts
@@ -71,6 +71,11 @@ const ORIGINS = {
because: "an extension method in this file extends the receiver's type",
tier: "direct",
},
+ receiver_chain_same_file: {
+ label: "Field chain, same file",
+ because: "each field on the receiver's path has a declared type, all in this file",
+ tier: "direct",
+ },
return_type_same_file: {
label: "Return type, same file",
because: "the inner call's declared return type is a class in this file",
@@ -163,6 +168,11 @@ const ORIGINS = {
because: "a framework decorator retyped the receiver, and that class was found in an imported file",
tier: "scoped",
},
+ receiver_chain_import: {
+ label: "Field chain, imported",
+ because: "each field on the receiver's path has a declared type, bound by an import",
+ tier: "scoped",
+ },
return_type_same_package: {
label: "Return type, same package",
because: "the inner call's declared return type is a class in the same package",
diff --git a/tests/unit/ingestion/test_chained_receiver_calls.py b/tests/unit/ingestion/test_chained_receiver_calls.py
new file mode 100644
index 000000000..538c7e2c9
--- /dev/null
+++ b/tests/unit/ingestion/test_chained_receiver_calls.py
@@ -0,0 +1,429 @@
+"""Chained member calls: ``h.f1…fn.m()`` typed hop by hop.
+
+The head is typed from the calling body, the enclosing class (``this`` /
+``self``) or module scope; each field from the declaring class's own fields.
+An edge is emitted only when every hop names exactly one class and the last
+one declares the method, so each negative below removes one of those proofs.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import parse_file
+
+
+def _parse_all(tmp_path: Path, files: dict[str, tuple[str, str]]) -> dict[str, ParsedFile]:
+ out: dict[str, ParsedFile] = {}
+ for rel, (lang, content) in files.items():
+ abs_ = tmp_path / rel
+ abs_.parent.mkdir(parents=True, exist_ok=True)
+ abs_.write_text(content)
+ info = FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language=lang, # type: ignore[arg-type]
+ size_bytes=abs_.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ out[rel] = parse_file(info, content.encode("utf-8"))
+ return out
+
+
+def _edges(
+ tmp_path: Path,
+ files: dict[str, tuple[str, str]],
+ links: dict[str, dict[str, str]] | None = None,
+) -> list[tuple[str, str, float, str]]:
+ """Resolve *files*, with *links* standing in for import resolution."""
+ parsed = _parse_all(tmp_path, files)
+ for path, module_to_file in (links or {}).items():
+ for imp in parsed[path].imports:
+ target = module_to_file.get(imp.module_path)
+ if target is not None:
+ imp.resolved_file = target
+ resolver = CallResolver(parsed, {p: set() for p in parsed}, repo_path=str(tmp_path))
+ return [
+ (rc.caller_id, rc.callee_id, rc.confidence, rc.origin)
+ for path, pf in parsed.items()
+ for rc in resolver.resolve_file(path, pf.calls)
+ ]
+
+
+def _chained(edges: list[tuple[str, str, float, str]]) -> list[tuple[str, str, float, str]]:
+ return [e for e in edges if e[3].startswith("receiver_chain_")]
+
+
+# --- ts_chained_field_calls --------------------------------------------------
+
+_TS_USERS = (
+ "typescript",
+ "export class Users {\n get(slug: string): number { return 1; }\n}\n",
+)
+
+
+def _ts_chained_field_calls(app: str) -> dict[str, tuple[str, str]]:
+ return {
+ "src/users.ts": _TS_USERS,
+ "src/store.ts": (
+ "typescript",
+ "import { Users } from './users';\n"
+ "export class Store {\n"
+ " users: Users;\n"
+ " constructor() { this.users = new Users(); }\n"
+ "}\n",
+ ),
+ "src/app.ts": ("typescript", app),
+ }
+
+
+_TS_LINKS = {
+ "src/store.ts": {"./users": "src/users.ts"},
+ "src/app.ts": {"./store": "src/store.ts"},
+}
+
+
+class TestTsChainedFieldCalls:
+ def test_a_parameter_property_and_a_field_type_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "export class App {\n"
+ " constructor(private readonly store: Store) {}\n"
+ " run() { return this.store.users.get('x'); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, _ts_chained_field_calls(app), _TS_LINKS)
+ assert (
+ "src/app.ts::App::run",
+ "src/users.ts::Users::get",
+ 0.88,
+ "receiver_chain_import",
+ ) in edges
+
+ def test_a_typed_parameter_heads_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "export function run(store: Store) {\n"
+ " return store.users.get('x');\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, _ts_chained_field_calls(app), _TS_LINKS)
+ assert ("src/app.ts::run", "src/users.ts::Users::get") in {e[:2] for e in edges}
+
+ def test_a_same_file_chain_is_same_file(self, tmp_path: Path) -> None:
+ source = (
+ "class Engine { start(): void {} }\n"
+ "class Car { engine = new Engine(); }\n"
+ "class Garage {\n"
+ " car: Car;\n"
+ " open() { this.car.engine.start(); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"garage.ts": ("typescript", source)})
+ assert (
+ "garage.ts::Garage::open",
+ "garage.ts::Engine::start",
+ 0.93,
+ "receiver_chain_same_file",
+ ) in edges
+
+ def test_an_untyped_field_yields_no_edge(self, tmp_path: Path) -> None:
+ source = (
+ "class Engine { start(): void {} }\n"
+ "class Car { engine = makeEngine(); }\n"
+ "class Garage {\n"
+ " car: Car;\n"
+ " open() { this.car.engine.start(); }\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, {"garage.ts": ("typescript", source)}))
+
+ def test_a_union_field_yields_no_edge(self, tmp_path: Path) -> None:
+ source = (
+ "class Engine { start(): void {} }\n"
+ "class Car { engine: Engine | null; }\n"
+ "class Garage {\n"
+ " car: Car;\n"
+ " open() { this.car.engine.start(); }\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, {"garage.ts": ("typescript", source)}))
+
+ def test_self_is_not_this(self, tmp_path: Path) -> None:
+ source = (
+ "class Engine {\n start(): void {}\n}\n"
+ "class Car {\n engine: Engine;\n}\n"
+ "class Garage {\n car: Car;\n"
+ " open() {\n self.car.engine.start();\n }\n}\n"
+ )
+ assert not _chained(_edges(tmp_path, {"garage.ts": ("typescript", source)}))
+
+ def test_a_type_parameter_field_yields_no_edge(self, tmp_path: Path) -> None:
+ source = (
+ "class Engine {\n start(): void {}\n}\n"
+ "class Car<T> {\n engine: T;\n}\n"
+ "class Garage {\n car: Car<Engine>;\n"
+ " open() {\n this.car.engine.start();\n }\n}\n"
+ )
+ assert not _chained(_edges(tmp_path, {"garage.ts": ("typescript", source)}))
+
+ def test_a_method_missing_on_the_final_type_yields_no_edge(self, tmp_path: Path) -> None:
+ source = (
+ "class Engine { start(): void {} }\n"
+ "class Wheel { start(): void {} }\n"
+ "class Car { engine: Engine; }\n"
+ "class Garage {\n"
+ " car: Car;\n"
+ " open() { this.car.engine.stop(); }\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, {"garage.ts": ("typescript", source)})
+ assert not [e for e in edges if e[0] == "garage.ts::Garage::open"]
+
+ def test_a_chain_deeper_than_three_fields_yields_no_edge(self, tmp_path: Path) -> None:
+ source = (
+ "class Leaf { go(): void {} }\n"
+ "class Twig { leaf: Leaf; }\n"
+ "class Branch { twig: Twig; }\n"
+ "class Bough { branch: Branch; }\n"
+ "class Tree {\n"
+ " bough: Bough;\n"
+ " run() { this.bough.branch.twig.leaf.go(); }\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, {"deep.ts": ("typescript", source)}))
+
+ def test_three_fields_are_walked(self, tmp_path: Path) -> None:
+ source = (
+ "class Leaf { go(): void {} }\n"
+ "class Twig { leaf: Leaf; }\n"
+ "class Branch { twig: Twig; }\n"
+ "class Tree {\n"
+ " branch: Branch;\n"
+ " run() { this.branch.twig.leaf.go(); }\n"
+ "}\n"
+ )
+ edges = _chained(_edges(tmp_path, {"deep.ts": ("typescript", source)}))
+ assert [e[:2] for e in edges] == [("deep.ts::Tree::run", "deep.ts::Leaf::go")]
+
+
+# --- ts_module_scope_receiver ------------------------------------------------
+
+
+class TestTsModuleScopeReceiver:
+ def _files(self, app: str) -> dict[str, tuple[str, str]]:
+ return _ts_chained_field_calls(app)
+
+ def test_a_module_scope_instance_heads_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "const store = new Store();\n"
+ "export async function main() {\n"
+ " return store.users.get('x');\n"
+ "}\n"
+ )
+ edges = _edges(tmp_path, self._files(app), _TS_LINKS)
+ assert (
+ "src/app.ts::main",
+ "src/users.ts::Users::get",
+ 0.88,
+ "receiver_chain_import",
+ ) in edges
+
+ def test_a_call_at_module_scope_reads_module_scope(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "const store: Store = make();\n"
+ "store.users.get('x');\n"
+ )
+ edges = _edges(tmp_path, self._files(app), _TS_LINKS)
+ assert ("src/app.ts::__module__", "src/users.ts::Users::get") in {e[:2] for e in edges}
+
+ def test_a_shadowing_local_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "const store = new Store();\n"
+ "export function main() {\n"
+ " const store = other();\n"
+ " return store.users.get('x');\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, self._files(app), _TS_LINKS))
+
+ def test_a_shadowing_parameter_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "const store = new Store();\n"
+ "export function main(store) {\n"
+ " return store.users.get('x');\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, self._files(app), _TS_LINKS))
+
+ def test_a_module_name_rebound_untyped_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "let store = new Store();\n"
+ "store = other();\n"
+ "export function main() {\n"
+ " return store.users.get('x');\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, self._files(app), _TS_LINKS))
+
+ def test_an_object_literal_key_declares_nothing(self, tmp_path: Path) -> None:
+ app = (
+ "import { Store } from './store';\n"
+ "export function main() {\n"
+ " const opts = { store: Store, };\n"
+ " return store.users.get('x');\n"
+ "}\n"
+ )
+ assert not _chained(_edges(tmp_path, self._files(app), _TS_LINKS))
+
+
+# --- py_chained_field_calls --------------------------------------------------
+
+
+def _py_chained_field_calls(app: str) -> dict[str, tuple[str, str]]:
+ return {
+ "pkg/users.py": (
+ "python",
+ "class Users:\n def get(self, slug):\n return slug\n",
+ ),
+ "pkg/store.py": (
+ "python",
+ "from pkg.users import Users\n\n"
+ "class Store:\n"
+ " def __init__(self):\n"
+ " self.users = Users()\n",
+ ),
+ "pkg/app.py": ("python", app),
+ }
+
+
+_PY_LINKS = {
+ "pkg/store.py": {"pkg.users": "pkg/users.py"},
+ "pkg/app.py": {"pkg.store": "pkg/store.py"},
+}
+
+
+class TestPyChainedFieldCalls:
+ def test_self_fields_type_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "from pkg.store import Store\n\n"
+ "class App:\n"
+ " def __init__(self):\n"
+ " self.store = Store()\n\n"
+ " def run(self):\n"
+ " return self.store.users.get('x')\n"
+ )
+ edges = _edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS)
+ assert (
+ "pkg/app.py::App::run",
+ "pkg/users.py::Users::get",
+ 0.88,
+ "receiver_chain_import",
+ ) in edges
+
+ def test_a_class_level_annotation_is_a_field(self, tmp_path: Path) -> None:
+ app = (
+ "from pkg.store import Store\n\n"
+ "class App:\n"
+ " store: Store\n\n"
+ " def run(self):\n"
+ " return self.store.users.get('x')\n"
+ )
+ edges = _edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS)
+ assert ("pkg/app.py::App::run", "pkg/users.py::Users::get") in {e[:2] for e in edges}
+
+ def test_a_module_scope_instance_heads_the_chain(self, tmp_path: Path) -> None:
+ app = (
+ "from pkg.store import Store\n\n"
+ "store = Store()\n\n"
+ "def main():\n"
+ " return store.users.get('x')\n"
+ )
+ edges = _edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS)
+ assert ("pkg/app.py::main", "pkg/users.py::Users::get") in {e[:2] for e in edges}
+
+ def test_a_shadowing_parameter_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "from pkg.store import Store\n\n"
+ "store = Store()\n\n"
+ "def main(verbose, store):\n"
+ " return store.users.get('x')\n"
+ )
+ assert not _chained(_edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS))
+
+ def test_an_untyped_field_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "class App:\n"
+ " def __init__(self, store):\n"
+ " self.store = store\n\n"
+ " def run(self):\n"
+ " return self.store.users.get('x')\n"
+ )
+ assert not _chained(_edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS))
+
+ def test_an_optional_field_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "from typing import Optional\n"
+ "from pkg.store import Store\n\n"
+ "class App:\n"
+ " def __init__(self):\n"
+ " self.store: Optional[Store] = None\n\n"
+ " def run(self):\n"
+ " return self.store.users.get('x')\n"
+ )
+ assert not _chained(_edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS))
+
+ def test_a_field_typed_twice_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "from pkg.store import Store\n"
+ "from pkg.users import Users\n\n"
+ "class App:\n"
+ " def __init__(self):\n"
+ " self.store = Store()\n\n"
+ " def reset(self):\n"
+ " self.store = Users()\n\n"
+ " def run(self):\n"
+ " return self.store.users.get('x')\n"
+ )
+ links = {
+ **_PY_LINKS,
+ "pkg/app.py": {"pkg.store": "pkg/store.py", "pkg.users": "pkg/users.py"},
+ }
+ assert not _chained(_edges(tmp_path, _py_chained_field_calls(app), links))
+
+ def test_a_method_missing_on_the_final_type_yields_no_edge(self, tmp_path: Path) -> None:
+ app = (
+ "from pkg.store import Store\n\n"
+ "class App:\n"
+ " def __init__(self):\n"
+ " self.store = Store()\n\n"
+ " def run(self):\n"
+ " return self.store.users.post('x')\n"
+ )
+ assert not _chained(_edges(tmp_path, _py_chained_field_calls(app), _PY_LINKS))
+
+ def test_a_non_path_receiver_mints_no_site(self, tmp_path: Path) -> None:
+ """``a[0].b.m()`` and ``f().b.m()`` stay off every tier, bare ones included."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "m.py": (
+ "python",
+ "def run(items):\n items[0].users.get(1)\n make().users.get(2)\n",
+ )
+ },
+ )
+ assert [(c.receiver_name, c.target_name) for c in parsed["m.py"].calls] == [(None, "make")]
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index 1d8ea570e..ce06e130f 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -634,6 +634,7 @@ def test_the_language_set_is_what_the_patterns_declare() -> None:
"kotlin",
"python",
"swift",
+ "typescript",
}
diff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.py
index 8954a1870..1b29f0b78 100644
--- a/tests/unit/test_no_bare_type_name_copies.py
+++ b/tests/unit/test_no_bare_type_name_copies.py
@@ -77,9 +77,11 @@ _KNOWN: dict[str, int] = {
# one site is an import's module path, which is a module name and not a
# type: `call_receiver_typing.py` takes its tail and `call_resolver.py`
# its head, to ask whether the package it names is one of ours. The rest
- # are symbol IDs.
+ # are symbol IDs, except one `call_receiver_typing.py` site that walks a
+ # dotted receiver (`this.a.b`) hop by hop: an instance path, where every
+ # segment is a variable or a field and none is discarded.
_PREFIX + "call_resolver.py": 6,
- _PREFIX + "call_receiver_typing.py": 2,
+ _PREFIX + "call_receiver_typing.py": 3,
_PREFIX + "models.py": 1,
# Reads the head to decide whether taking a bare name is safe at all: a
# qualifier that is a type rather than a package must not be discarded.