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(go): type a range loop variable from the container it walks (#2778)

Raghav Chamadiya303f55f1785c
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 416c50ded..4c19351c4 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -13,25 +13,31 @@ from .languages.receiver_types import (
CALL_TYPED_LANGUAGES,
FRAMEWORK_DECORATOR_LANGUAGES,
IMPLICIT_FIELD_LANGUAGES,
+ RANGE_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
CallAssignment,
Declaration,
+ RangeClause,
+ RangeScan,
ScopeMarks,
bound_types,
+ clauses_in_span,
framework_decorated_type,
in_spans,
merge_spans,
names_in_span,
+ range_element_types,
record_type,
scan_bindings,
scan_call_assignments,
scan_declarations,
+ scan_ranges,
scan_scope_marks,
types_by_class,
types_in_span,
unwrapped_names_in_span,
)
-from .models import CallSite, ParsedFile, Symbol
+from .models import CallSite, ParsedFile, Symbol, symbol_id_language
from .resolved_call import ResolvedCall
from .return_types import declared_return_type, go_first_result
from .type_names import POINTER_LIKE_MEMBERS, bare_type_name
@@ -139,6 +145,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._range_scans: dict[str, RangeScan] = {}
+ # {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]] = {}
# {file: {type name: [type symbol ids]}}, built once on first use.
self._type_ids: dict[str, dict[str, list[str]]] | None = None
@@ -720,6 +729,8 @@ class ReceiverTypingMixin:
)
else:
types = types_in_span(declarations, *span)
+ if language in RANGE_LANGUAGES:
+ self._type_range_variables(file_path, language, span, types)
_store_capped(self._body_types, key, types, _BODY_TYPE_CACHE_ENTRIES)
if span is not None and language in CALL_TYPED_LANGUAGES:
@@ -879,21 +890,131 @@ class ReceiverTypingMixin:
) -> dict[str, dict[str, str | None]]:
"""``{class_id: {name: type}}`` for the fields one file's classes declare."""
by_class = self._field_types.get(file_path)
- if by_class is not None:
- return by_class
+ if by_class is None:
+ by_class = self._class_scope_types(
+ file_path, self._declarations_for(file_path, language), language
+ )
+ _store_capped(self._field_types, file_path, by_class, _SOURCE_CACHE_FILES)
+ return by_class
+ def _class_scope_types(
+ self, file_path: str, declarations: tuple[Declaration, ...], language: str
+ ) -> dict[str, dict[str, str | None]]:
+ """*declarations* grouped by the class in *file_path* each is a field of."""
parsed = self._parsed_files.get(file_path)
symbols = parsed.symbols if parsed else ()
- class_spans = {s.id: (s.start_line, s.end_line) for s in symbols if s.kind in _TYPE_KINDS}
- by_class = types_by_class(
- self._declarations_for(file_path, language),
- class_spans,
+ return types_by_class(
+ declarations,
+ {s.id: (s.start_line, s.end_line) for s in symbols if s.kind in _TYPE_KINDS},
[(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)
+
+ def _type_range_variables(
+ self,
+ file_path: str,
+ language: str,
+ span: tuple[int, int],
+ types: dict[str, str | None],
+ ) -> None:
+ """Add each ``range`` variable in one body to *types*, the body's own.
+
+ In line order, so a loop over an outer loop's variable sees it typed.
+ A body is one flat scope and a loop variable lives only in its block,
+ so one reusing a name the body already declares (``for _, cmd := range``
+ inside a ``cmd`` method) is skipped rather than let it retype or
+ refuse the name body-wide. Two loops typing one name differently
+ refuse it, as a name declared twice does.
+ """
+ scan = self._range_scan_for(file_path, language)
+ clauses = clauses_in_span(scan.clauses, *span)
+ if not clauses:
+ return
+ containers = types_in_span(scan.containers, *span)
+ declared = frozenset(types)
+ for clause in clauses:
+ spelling, written_in = self._ranged_container(
+ file_path, language, clause, types, containers
+ )
+ external = self._externally_bound_names(written_in)
+ elements = range_element_types(spelling, language, external) or (None, None)
+ for name, type_name in zip((clause.key, clause.value), elements, strict=True):
+ if name and name != "_" and name not in declared:
+ types[name] = type_name if types.get(name, type_name) == type_name else None
+
+ def _ranged_container(
+ self,
+ file_path: str,
+ language: str,
+ clause: RangeClause,
+ types: dict[str, str | None],
+ containers: dict[str, str | None],
+ ) -> tuple[str | None, str]:
+ """How the container one range clause walks is spelled, and in which file.
+
+ The file is where the spelling's package qualifiers are imported. A
+ bare name is a container the body declares, and never one it also
+ typed as a value. ``h.field`` and ``h.Method()`` are read off the one
+ class ``h``'s type names: the field's declaration, or the method's
+ declared return type. Ceiling: a method declared in another file of
+ the class's package is not found, which costs the edge.
+ """
+ if not clause.member:
+ return (None if clause.head in types else containers.get(clause.head)), file_path
+ head_type = types.get(clause.head)
+ class_id = None if head_type is None else self._range_class(file_path, head_type, language)
+ if class_id is None:
+ return None, file_path
+ class_file = self._symbol_paths_by_id.get(class_id, file_path)
+ if clause.call:
+ sym_id = self._declares(class_id, clause.member)
+ symbol = None if sym_id is None else self._symbols_by_id.get(sym_id)
+ spelling = None if symbol is None else declared_return_type(symbol.signature or "")
+ return spelling, class_file
+ fields = self._container_fields_in(class_file, language).get(class_id, {})
+ return fields.get(clause.member), class_file
+
+ def _range_class(self, file_path: str, type_name: str, language: str) -> str | None:
+ """The id of the one class *type_name* names, seen from *file_path*.
+
+ Go qualifies a type by its package, never by an imported name, so past
+ this file the one type of that name in the language answers, and two
+ refuse.
+ """
+ found = self._class_named(file_path, type_name)
+ if found is not None:
+ return found[1]
+ if type_name in self._externally_bound_names(file_path):
+ return None
+ ids = [
+ sym_id
+ for sym_id in self._global_symbols.get(type_name, ())
+ if (symbol := self._symbols_by_id.get(sym_id)) is not None
+ and symbol.kind in _TYPE_KINDS
+ and symbol_id_language(self._parsed_files, sym_id) == language
+ ]
+ return ids[0] if len(ids) == 1 else None
+
+ def _container_fields_in(
+ self, file_path: str, language: str
+ ) -> dict[str, dict[str, str | None]]:
+ """``{class_id: {field: container spelling}}`` for one file's classes."""
+ by_class = self._container_fields.get(file_path)
+ if by_class is None:
+ by_class = self._class_scope_types(
+ file_path, self._range_scan_for(file_path, language).containers, language
+ )
+ _store_capped(self._container_fields, file_path, by_class, _SOURCE_CACHE_FILES)
return by_class
+ def _range_scan_for(self, file_path: str, language: str) -> RangeScan:
+ """One file's range clauses and containers, scanned once however many bodies ask."""
+ found = self._range_scans.get(file_path)
+ if found is None:
+ found = scan_ranges(self._text_of(file_path), language)
+ _store_capped(self._range_scans, file_path, found, _SOURCE_CACHE_FILES)
+ return found
+
def _bound_names_in(self, file_path: str, caller_id: str, language: str) -> frozenset[str]:
"""Every name the calling body binds, however it was bound."""
key = (file_path, caller_id)
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 b20b60860..9245a7d20 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -31,6 +31,7 @@ from ..type_names import (
bare_type_name,
is_resolvable_type_name,
strip_type_arguments,
+ type_qualifier,
unwrap_pointer_like,
)
@@ -913,3 +914,137 @@ def types_by_class(
break
return by_class
+
+
+# ``for k, v := range expr`` declares ``k`` and ``v`` with no type spelled: each
+# is whatever ranging over ``expr``'s container yields in its position. Two
+# scans feed it, the clauses and the containers they may range over, and the
+# resolver joins them, since only it can type ``expr`` itself.
+RANGE_LANGUAGES = frozenset({"go"})
+
+# What ranging over each container shape yields, the group name giving the
+# position: ``[]T``, ``[N]T`` and a variadic ``...T`` an int index, then a
+# ``T``; ``map[K]V`` a ``K``, then a ``V``; ``chan T`` a ``T`` alone. A pointer
+# element is still a ``T``. Anything else, a named container type included,
+# yields nothing, so its range variables stay untyped. Ceiling: a pointer to an
+# array (``*[N]T``, rangeable in Go) is not a shape here either.
+_GO_ELEMENT_SHAPES = (
+ re.compile(rf"(?:\[\d*\]|\.\.\.)\*?(?P<value>{_GO_TYPE})"),
+ re.compile(rf"map\[\*?(?P<key>{_GO_TYPE})\]\*?(?P<value>{_GO_TYPE})"),
+ re.compile(rf"(?:<-\s*)?chan(?:\s*<-)?\s+\*?(?P<key>{_GO_TYPE})"),
+)
+
+# Any one of those spellings, for the declaration scans to capture whole.
+_GO_CONTAINER = (
+ rf"(?:\[\d*\]|\.\.\.|map\[\*?{_GO_TYPE}\]|(?:<-\s*)?chan(?:\s*<-)?\s+)\*?{_GO_TYPE}"
+)
+
+_GO_CONTAINER_DECLARATIONS = (
+ # A parameter or named result, as ``_GO_PARAM``. Only the last name of
+ # ``a, b []T`` is read: a missed declaration, never a wrong one.
+ re.compile(rf"(?<![\w.])(?P<name>{_GO_NAME})\s+(?P<type>{_GO_CONTAINER})\s*(?=[,)])"),
+ # ``var xs []T``.
+ re.compile(rf"(?m)(?<![\w.])var\s+(?P<name>{_GO_NAME})\s+(?P<type>{_GO_CONTAINER})\s*(?=[=;)]|$)"),
+ # ``xs := []T{}`` and ``xs := make([]T, n)``.
+ re.compile(
+ rf"(?<![\w.])(?P<name>{_GO_NAME})\s*:=\s*(?:make\(\s*)?(?P<type>{_GO_CONTAINER})\s*(?=[{{,)])"
+ ),
+ # A struct field is the whole line, tag aside. ``member`` keeps it out of
+ # every body and admits it at class scope, where no closer marks it.
+ re.compile(
+ rf"(?m)^[ \t]*(?P<member>(?P<name>[A-Za-z_]\w*))[ \t]+(?P<type>{_GO_CONTAINER})"
+ r"[ \t]*(?:`[^`\n]*`)?[ \t]*$"
+ ),
+)
+
+# The range expression is a name, ``h.field`` or ``h.Method()``, closed by the
+# loop's brace. Anything longer (``h.a.b``, ``f().x``, ``xs[1:]``) is refused.
+_GO_RANGE = re.compile(
+ rf"\bfor\s+(?P<key>{_GO_NAME})(?:\s*,\s*(?P<value>{_GO_NAME}))?\s*:=\s*range\s+"
+ rf"(?P<head>{_GO_NAME})(?:\.(?P<member>[A-Za-z_]\w*)(?P<call>\(\))?)?\s*\{{"
+)
+
+
+class RangeClause(NamedTuple):
+ """One ``for key, value := range head[.member[()]]`` at one line.
+
+ ``value`` is empty when only one variable is declared; ``_`` names none.
+ """
+
+ line: int
+ key: str
+ value: str
+ head: str
+ member: str
+ call: bool
+
+
+class RangeScan(NamedTuple):
+ """A file's range clauses, and its container declarations typed by spelling."""
+
+ clauses: tuple[RangeClause, ...]
+ containers: tuple[Declaration, ...]
+
+
+def scan_ranges(text: str, language: str) -> RangeScan:
+ """Every range clause and container declaration *text* makes, in line order."""
+ if language not in RANGE_LANGUAGES:
+ return RangeScan((), ())
+ cleaned = _without_comments(text, language)
+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+ clauses = tuple(
+ RangeClause(
+ bisect_right(starts, match.start()),
+ match.group("key"),
+ match.group("value") or "",
+ match.group("head"),
+ match.group("member") or "",
+ bool(match.group("call")),
+ )
+ for match in _GO_RANGE.finditer(cleaned)
+ )
+ containers = sorted(
+ Declaration(
+ bisect_right(starts, match.start()),
+ match.group("name"),
+ match.group("type"),
+ member=bool(match.groupdict().get("member")),
+ )
+ for pattern in _GO_CONTAINER_DECLARATIONS
+ for match in pattern.finditer(cleaned)
+ )
+ return RangeScan(clauses, tuple(containers))
+
+
+def range_element_types(
+ spelling: str | None, language: str, external: frozenset[str] = frozenset()
+) -> tuple[str | None, str | None] | None:
+ """``(key type, value type)`` for ranging over *spelling*, or None if unknown.
+
+ A position holding a predeclared type (an index's ``int``), or a type
+ qualified by an *external* package (``os.FileInfo``, whose bare name a
+ repo type may share), is None within a known shape.
+ """
+ if not spelling or language not in RANGE_LANGUAGES:
+ return None
+
+ def element(raw: str | None) -> str | None:
+ if not raw or type_qualifier(raw) in external:
+ return None
+ return _usable_type_name(raw, language)[0]
+
+ for shape in _GO_ELEMENT_SHAPES:
+ match = shape.fullmatch(spelling)
+ if match is not None:
+ groups = match.groupdict()
+ return element(groups.get("key")), element(groups.get("value"))
+ return None
+
+
+def clauses_in_span(
+ clauses: tuple[RangeClause, ...], start_line: int, end_line: int
+) -> tuple[RangeClause, ...]:
+ """The range clauses inside one function body, in line order."""
+ 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]
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
index 238ff0f8e..ea462392c 100644
--- a/packages/core/src/repowise/core/ingestion/type_names.py
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -94,6 +94,16 @@ def bare_type_name(raw: str) -> str:
return text.strip()
+def type_qualifier(raw: str) -> str:
+ """Return what ``bare_type_name`` drops from the front of *raw*, or ``""``.
+
+ ``os.FileInfo`` → ``os``; ``Plain`` → ``""``.
+ """
+ text = strip_type_arguments(raw.strip())
+ head = text[: len(text) - len(bare_type_name(text))]
+ return head.rstrip("".join(_QUALIFIER_SEPARATORS))
+
+
# C++ template heads whose ``operator->`` forwards to their argument, so
# ``shared_ptr<Foo> p`` makes ``p->m()`` a call on ``Foo``. Only these: a
# container holds a ``T`` without being one, and unwrapping ``vector<Foo>``
diff --git a/tests/unit/ingestion/test_go_range_receivers.py b/tests/unit/ingestion/test_go_range_receivers.py
new file mode 100644
index 000000000..8e126afaa
--- /dev/null
+++ b/tests/unit/ingestion/test_go_range_receivers.py
@@ -0,0 +1,219 @@
+"""Go ``range`` variables typed from the container they walk.
+
+``for _, sub := range c.commands`` spells no type for ``sub``: it is whatever
+the container yields in that position. The scan reads the clauses and the
+container declarations; the resolver joins them. Every negative removes one
+proof, and must leave the variable untyped rather than guessed.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.languages.receiver_types import (
+ RangeClause,
+ range_element_types,
+ scan_ranges,
+ types_in_span,
+)
+from tests.unit.ingestion.test_chained_receiver_calls import _edges
+
+
+def _clauses(text: str) -> list[RangeClause]:
+ return list(scan_ranges(text, "go").clauses)
+
+
+def _containers(text: str) -> dict[str, str | None]:
+ return types_in_span(scan_ranges(text, "go").containers, 1, 10_000)
+
+
+class TestElementTypes:
+ """The container table: which position gets which type."""
+
+ @pytest.mark.parametrize(
+ ("spelling", "expected"),
+ [
+ ("[]*Command", (None, "Command")),
+ ("[]Rule", (None, "Rule")),
+ ("[4]Rule", (None, "Rule")),
+ ("...*Command", (None, "Command")),
+ ("[]report.Finding", (None, "Finding")),
+ ("map[string]*Group", (None, "Group")),
+ ("map[Key]Value", ("Key", "Value")),
+ ("chan *Job", ("Job", None)),
+ ("<-chan Job", ("Job", None)),
+ ("chan<- Job", ("Job", None)),
+ ("[]string", (None, None)),
+ ],
+ )
+ def test_a_known_shape(self, spelling: str, expected: tuple[str | None, str | None]) -> None:
+ assert range_element_types(spelling, "go") == expected
+
+ @pytest.mark.parametrize(
+ "spelling",
+ ["Commands", "*Command", "[][]Rule", "map[string][]Rule", "[]func()", "string", ""],
+ )
+ def test_an_unknown_shape_is_refused(self, spelling: str) -> None:
+ """A named container, a nested one or a non-container yields nothing."""
+ assert range_element_types(spelling, "go") is None
+
+ def test_an_externally_qualified_element_is_refused(self) -> None:
+ """``os.FileInfo`` bares to a name a repo type may share."""
+ assert range_element_types("[]os.FileInfo", "go", frozenset({"os"})) == (None, None)
+ assert range_element_types("[]report.Finding", "go", frozenset({"os"})) == (
+ None,
+ "Finding",
+ )
+
+ def test_other_languages_have_no_table(self) -> None:
+ assert range_element_types("[]Rule", "java") is None
+
+
+class TestClauses:
+ def test_both_variables_and_a_field(self) -> None:
+ (clause,) = _clauses("for i, sub := range c.commands {")
+ assert (clause.key, clause.value, clause.head, clause.member, clause.call) == (
+ "i", "sub", "c", "commands", False
+ )
+
+ def test_a_single_variable_over_a_name(self) -> None:
+ (clause,) = _clauses("for job := range jobs {")
+ assert (clause.key, clause.value, clause.head, clause.member) == ("job", "", "jobs", "")
+
+ def test_a_zero_argument_method(self) -> None:
+ (clause,) = _clauses("for _, cmd := range c.Commands() {")
+ assert (clause.member, clause.call) == ("Commands", True)
+
+ @pytest.mark.parametrize(
+ "line",
+ [
+ "for _, x := range c.a.b {",
+ "for _, x := range f().items {",
+ "for _, x := range c.Items(1) {",
+ "for _, x := range xs[1:] {",
+ "for _, x = range xs {",
+ "// for _, x := range xs {",
+ ],
+ )
+ def test_a_longer_expression_or_an_assignment_is_not_read(self, line: str) -> None:
+ assert _clauses(line) == []
+
+
+class TestContainers:
+ def test_a_parameter_and_a_variadic(self) -> None:
+ text = "func f(findings []report.Finding, cmds ...*Command) {"
+ assert _containers(text) == {"findings": "[]report.Finding", "cmds": "...*Command"}
+
+ def test_a_var_a_literal_and_a_make(self) -> None:
+ text = "var jobs chan *Job\nrs := []Rule{}\nmatches := make([]*Command, 0)\n"
+ assert _containers(text) == {"jobs": "chan *Job", "rs": "[]Rule", "matches": "[]*Command"}
+
+ def test_a_struct_field_belongs_to_no_body(self) -> None:
+ """A field line is a ``member``: class scope only, never a local."""
+ scan = scan_ranges("type C struct {\n\tcommands []*Command `json:\"c\"`\n}\n", "go")
+ (field,) = scan.containers
+ assert (field.name, field.type_name, field.member) == ("commands", "[]*Command", True)
+
+
+_COMMAND = (
+ "go",
+ "package main\n\n"
+ "type Group struct{}\n\n"
+ "func (g *Group) Title() string { return \"\" }\n\n"
+ "type Command struct {\n"
+ "\tcommands []*Command\n"
+ "\tgroups map[string]*Group\n"
+ "\tnamed Commands\n"
+ "}\n\n"
+ "type Commands []*Command\n\n"
+ "func (c *Command) Commands() []*Command { return c.commands }\n"
+ "func (c *Command) Named() Commands { return c.named }\n"
+ "func (c *Command) HasAlias(s string) bool { return false }\n\n",
+)
+
+
+def _range_edges(tmp_path: Path, body: str) -> set[tuple[str, str]]:
+ lang, head = _COMMAND
+ edges = _edges(tmp_path, {"a.go": (lang, head + body)})
+ return {(caller, callee) for caller, callee, _, _ in edges}
+
+
+def _callees(tmp_path: Path, body: str) -> set[str]:
+ return {callee for _, callee in _range_edges(tmp_path, body)}
+
+
+class TestResolution:
+ def test_a_range_over_a_field(self, tmp_path: Path) -> None:
+ body = "func (c *Command) find() {\n\tfor _, sub := range c.commands {\n\t\tsub.HasAlias(\"x\")\n\t}\n}\n"
+ assert ("a.go::Command::find", "a.go::Command::HasAlias") in _range_edges(tmp_path, body)
+
+ def test_a_range_over_a_method_result(self, tmp_path: Path) -> None:
+ body = "func (c *Command) find() {\n\tfor _, sub := range c.Commands() {\n\t\tsub.HasAlias(\"x\")\n\t}\n}\n"
+ assert ("a.go::Command::find", "a.go::Command::HasAlias") in _range_edges(tmp_path, body)
+
+ def test_a_map_value_takes_the_second_variable(self, tmp_path: Path) -> None:
+ body = "func (c *Command) find() {\n\tfor k, g := range c.groups {\n\t\tg.Title()\n\t\tk.Title()\n\t}\n}\n"
+ assert _range_edges(tmp_path, body) == {("a.go::Command::find", "a.go::Group::Title")}
+
+ def test_a_parameter_slice(self, tmp_path: Path) -> None:
+ body = "func filter(cmds []*Command) {\n\tfor i, x := range cmds {\n\t\tx.HasAlias(\"x\")\n\t}\n}\n"
+ assert ("a.go::filter", "a.go::Command::HasAlias") in _range_edges(tmp_path, body)
+
+ def test_a_nested_range_over_an_outer_variable(self, tmp_path: Path) -> None:
+ body = (
+ "func (c *Command) walk() {\n\tfor _, sub := range c.commands {\n"
+ "\t\tfor _, leaf := range sub.commands {\n\t\t\tleaf.HasAlias(\"x\")\n\t\t}\n\t}\n}\n"
+ )
+ assert ("a.go::Command::walk", "a.go::Command::HasAlias") in _range_edges(tmp_path, body)
+
+ def test_the_index_is_not_the_element(self, tmp_path: Path) -> None:
+ body = "func filter(cmds []*Command) {\n\tfor i := range cmds {\n\t\ti.HasAlias(\"x\")\n\t}\n}\n"
+ assert not _callees(tmp_path, body) & {"a.go::Command::HasAlias"}
+
+ def test_a_named_container_type_is_refused(self, tmp_path: Path) -> None:
+ """``Commands`` is a slice, but only a type checker would say so."""
+ body = (
+ "func (c *Command) find() {\n\tfor _, sub := range c.named {\n\t\tsub.HasAlias(\"x\")\n\t}\n"
+ "\tfor _, sub := range c.Named() {\n\t\tsub.HasAlias(\"x\")\n\t}\n}\n"
+ )
+ assert not _callees(tmp_path, body) & {"a.go::Command::HasAlias"}
+
+ def test_a_loop_variable_does_not_retype_the_receiver_body_wide(self, tmp_path: Path) -> None:
+ """A body is one scope, so the loop's ``c`` must not cost the method's."""
+ body = (
+ "func (c *Command) run(xs Commands) {\n\tfor _, c := range xs {\n\t\t_ = c\n\t}\n"
+ "\tc.HasAlias(\"x\")\n}\n"
+ )
+ assert ("a.go::Command::run", "a.go::Command::HasAlias") in _range_edges(tmp_path, body)
+
+ def test_two_loops_typing_one_name_differently_refuse_it(self, tmp_path: Path) -> None:
+ body = (
+ "func (c *Command) find() {\n\tfor _, x := range c.commands {\n\t}\n"
+ "\tfor _, x := range c.groups {\n\t\tx.HasAlias(\"x\")\n\t}\n}\n"
+ )
+ assert not _callees(tmp_path, body) & {"a.go::Command::HasAlias"}
+
+ def test_an_external_element_does_not_bind_a_repo_type_of_its_name(
+ self, tmp_path: Path
+ ) -> None:
+ files = {
+ "a.go": (
+ "go",
+ "package main\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\n"
+ "type FileInfo struct{}\n\nfunc (f FileInfo) IsDir() bool { return false }\n\n"
+ "func list(infos []os.FileInfo, more []filepath.FileInfo) {\n"
+ "\tfor _, i := range infos {\n\t\ti.IsDir()\n\t}\n"
+ "\tfor _, m := range more {\n\t\tm.IsDir()\n\t}\n}\n",
+ )
+ }
+ callees = {callee for _, callee, _, _ in _edges(tmp_path, files)}
+ assert "a.go::FileInfo::IsDir" not in callees
+
+ def test_two_hops_are_refused(self, tmp_path: Path) -> None:
+ body = (
+ "func origin() *Command { return nil }\n"
+ "func find() {\n\tfor _, sub := range origin().commands {\n\t\tsub.HasAlias(\"x\")\n\t}\n}\n"
+ )
+ assert not _callees(tmp_path, body) & {"a.go::Command::HasAlias"}