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 local from the call that declares it (#2777)

Raghav Chamadiya9f143648c163
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 4c0a4aa7b..416c50ded 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import posixpath
from bisect import bisect_left, bisect_right
from dataclasses import replace
from pathlib import Path
@@ -9,9 +10,11 @@ from typing import NamedTuple, TypeVar
from .languages.receiver_types import (
BINDING_LANGUAGES,
+ CALL_TYPED_LANGUAGES,
FRAMEWORK_DECORATOR_LANGUAGES,
IMPLICIT_FIELD_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
+ CallAssignment,
Declaration,
ScopeMarks,
bound_types,
@@ -19,7 +22,9 @@ from .languages.receiver_types import (
in_spans,
merge_spans,
names_in_span,
+ record_type,
scan_bindings,
+ scan_call_assignments,
scan_declarations,
scan_scope_marks,
types_by_class,
@@ -28,7 +33,8 @@ from .languages.receiver_types import (
)
from .models import CallSite, ParsedFile, Symbol
from .resolved_call import ResolvedCall
-from .type_names import POINTER_LIKE_MEMBERS
+from .return_types import declared_return_type, go_first_result
+from .type_names import POINTER_LIKE_MEMBERS, bare_type_name
# Which symbols own a class scope, and which of them swallow one. A class span
# contains every method body inside it, so both sets are needed to tell a field
@@ -127,6 +133,9 @@ class ReceiverTypingMixin:
# Scans are memoised per function, not per reference.
self._source_text: dict[str, str] = {}
self._declarations: dict[str, tuple[Declaration, ...]] = {}
+ self._call_assignments: dict[str, tuple[CallAssignment, ...]] = {}
+ # {file: {(line, receiver, target): call site}}, for the calls above.
+ self._call_sites: dict[str, dict[tuple[int, str | None, str], CallSite]] = {}
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]]] = {}
@@ -294,6 +303,9 @@ class ReceiverTypingMixin:
)
if type_name is None:
return None
+ if "::" in type_name:
+ # A symbol id, recorded by ``_add_call_typed_locals``.
+ return self._call_typed_receiver(file_path, call, caller_id, type_name)
if self._means_the_wrapper(file_path, caller_id, language, call, receiver_name):
return None
@@ -710,8 +722,116 @@ class ReceiverTypingMixin:
types = types_in_span(declarations, *span)
_store_capped(self._body_types, key, types, _BODY_TYPE_CACHE_ENTRIES)
+ if span is not None and language in CALL_TYPED_LANGUAGES:
+ # Stored first and filled in place: typing ``x := y.f()`` resolves
+ # ``y.f()``, which reads this body's types back, including the
+ # locals typed from earlier calls.
+ self._add_call_typed_locals(file_path, language, types, *span)
return types
+ def _add_call_typed_locals(
+ self,
+ file_path: str,
+ language: str,
+ types: dict[str, str | None],
+ start: int,
+ end: int,
+ ) -> None:
+ """Type ``x := f(..)`` locals from the declared return type of ``f``.
+
+ The value recorded is the type's symbol id, not its name: the name is
+ read in the callee's package, and a same-named type elsewhere must
+ not answer for it. Go never retypes a variable after declaring it, so
+ only a second ``:=`` of the name (another block) can disagree, and
+ that makes the name unanswerable, as for any declaration. A name a
+ declaration already types keeps that reading untouched.
+ """
+ assignments = self._call_assignments_for(file_path, language)
+ sites = self._call_sites_for(file_path)
+ declared = frozenset(types)
+ first = bisect_left(assignments, start, key=lambda a: a.line)
+ for assignment in assignments[first:]:
+ if assignment.line > end:
+ break
+ if assignment.name in declared:
+ continue
+ site = sites.get((assignment.line, assignment.receiver, assignment.target))
+ resolved = None if site is None else self._resolve_one(file_path, site)
+ # A repo-wide guess at the callee is not evidence of what it returns.
+ if resolved is None or "global" in resolved.origin:
+ continue
+ type_id = self._returned_type_id(resolved.callee_id)
+ if type_id is not None:
+ record_type(types, assignment.name, type_id)
+
+ def _returned_type_id(self, callee_id: str) -> str | None:
+ """The repository type a go call to *callee_id* yields, as a symbol id.
+
+ ``T`` is looked up in the callee's own package and ``pkg.T`` in the
+ package the callee's file imports as ``pkg``; exactly one type there
+ must carry the name. A slice, map or external type yields None.
+ """
+ symbol = self._symbols_by_id.get(callee_id)
+ path = self._symbol_paths_by_id.get(callee_id)
+ if symbol is None or path is None:
+ return None
+ if symbol.kind in _TYPE_KINDS:
+ return callee_id # a conversion, ``T(x)``
+ raw = declared_return_type(symbol.signature or "")
+ written = go_first_result(raw).lstrip("*") if raw else ""
+ type_name = bare_type_name(written)
+ # The head is the package the callee's file imports, not a type.
+ qualifier = written.rpartition(".")[0]
+ if not type_name.isidentifier() or (qualifier and not qualifier.isidentifier()):
+ return None
+ package = posixpath.dirname(path) if not qualifier else self._imported_dir(path, qualifier)
+ if package is None:
+ return None
+ found = [
+ type_id
+ for type_id in self._global_symbols.get(type_name, ())
+ if self._symbols_by_id[type_id].kind in _TYPE_KINDS
+ and posixpath.dirname(self._symbol_paths_by_id.get(type_id, "")) == package
+ ]
+ return found[0] if len(found) == 1 else None
+
+ def _imported_dir(self, file_path: str, local_name: str) -> str | None:
+ """The directory of the repository package *file_path* imports as *local_name*."""
+ parsed = self._parsed_files.get(file_path)
+ for imp in parsed.imports if parsed else ():
+ if local_name in imp.local_names:
+ bound = imp.resolved_file
+ if not bound or bound.startswith("external:"):
+ return None
+ return posixpath.dirname(bound)
+ return None
+
+ def _call_typed_receiver(
+ self, file_path: str, call: CallSite, caller_id: str, type_id: str
+ ) -> ResolvedCall | None:
+ """``x.m()`` where ``x`` holds the type *type_id*, bound by identity.
+
+ A go method may sit in any file of its type's package, so the method
+ is looked for across that package, not only the type's own file.
+ """
+ type_name = self._symbols_by_id[type_id].name
+ package = posixpath.dirname(self._symbol_paths_by_id[type_id])
+ found = [
+ (path, sym_id)
+ for path, sym_id in self._global_methods.get((type_name, call.target_name), ())
+ if posixpath.dirname(path) == package
+ ]
+ if len(found) != 1 or found[0][1] == caller_id:
+ return None
+ method_file, sym_id = found[0]
+ if method_file == file_path:
+ tier = "same_file"
+ elif package == posixpath.dirname(file_path):
+ tier = "same_package"
+ else:
+ tier = "import"
+ return self._body_typed_call(caller_id, sym_id, tier, call.line)
+
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.
@@ -861,6 +981,25 @@ class ReceiverTypingMixin:
_store_capped(self._declarations, file_path, found, _SOURCE_CACHE_FILES)
return found
+ def _call_assignments_for(self, file_path: str, language: str) -> tuple[CallAssignment, ...]:
+ found = self._call_assignments.get(file_path)
+ if found is None:
+ found = scan_call_assignments(self._text_of(file_path), language)
+ _store_capped(self._call_assignments, file_path, found, _SOURCE_CACHE_FILES)
+ return found
+
+ def _call_sites_for(self, file_path: str) -> dict[tuple[int, str | None, str], CallSite]:
+ sites = self._call_sites.get(file_path)
+ if sites is None:
+ parsed = self._parsed_files.get(file_path)
+ sites = {
+ (c.line, c.receiver_name, c.target_name): c
+ for c in (parsed.calls if parsed else ())
+ if c.caller_symbol_id and c.receiver_call is None
+ }
+ _store_capped(self._call_sites, file_path, sites, _SOURCE_CACHE_FILES)
+ return sites
+
def _spans_for(self, file_path: str) -> dict[str, tuple[int, int]]:
"""``{symbol_id: (start_line, end_line)}`` for one file."""
spans = self._symbol_spans.get(file_path)
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 f909a0f73..b20b60860 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -177,6 +177,14 @@ _GO_EMBEDDED_FIELD = re.compile(
rf"(?m)^[ \t]*\*?(?P<member>(?P<type>(?P<name>{_GO_FIELD_NAME}))){_GO_FIELD_END}"
)
+# ``x := f(..)``, ``x, err := pkg.New(..)``: the head of a call whose return
+# type names the local. Only the head is matched here; ``scan_call_assignments``
+# checks that the call is the whole right-hand side, not ``f().g()``.
+_GO_CALL_DECL = re.compile(
+ rf"(?<![\w.])(?P<name>{_GO_NAME})\s*(?:,\s*{_GO_NAME}\s*)*:="
+ r"[ \t]*(?:(?P<receiver>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\.)?(?P<target>[A-Za-z_]\w*)\s*\("
+)
+
# Kotlin annotates after the name, and `val x: Foo`, `var x: Foo`, parameters
# and `class A(val x: Foo)` are all `name: Type`.
#
@@ -697,6 +705,77 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
return tuple(found)
+class CallAssignment(NamedTuple):
+ """``name := receiver.target(..)`` at one line, typed later by the resolver."""
+
+ line: int
+ name: str
+ receiver: str | None
+ target: str
+
+
+_CALL_ASSIGNMENT_PATTERNS: dict[str, re.Pattern[str]] = {"go": _GO_CALL_DECL}
+
+# Languages whose locals may be typed from a call's declared return type.
+CALL_TYPED_LANGUAGES = frozenset(_CALL_ASSIGNMENT_PATTERNS)
+
+_QUOTES = frozenset("\"'`")
+_STATEMENT_ENDS = frozenset("\n;}")
+
+
+def _call_end(text: str, index: int) -> int:
+ """Index just past the ``)`` closing the ``(`` before *index*, or -1."""
+ depth = 1
+ while index < len(text):
+ char = text[index]
+ if char in _QUOTES:
+ # A backquoted string has no escapes; the other two do.
+ index += 1
+ while index < len(text) and text[index] != char:
+ index += 2 if char != "`" and text[index] == "\\" else 1
+ elif char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ if depth == 0:
+ return index + 1
+ index += 1
+ return -1
+
+
+def scan_call_assignments(text: str, language: str) -> tuple[CallAssignment, ...]:
+ """Every local *text* declares from a single call, in line order.
+
+ The call must be the whole right-hand side: ``x := f().g()`` or
+ ``x := f() + 1`` gives ``x`` no type from ``f``.
+ """
+ pattern = _CALL_ASSIGNMENT_PATTERNS.get(language)
+ if pattern is None:
+ return ()
+ cleaned = _without_comments(text, language)
+ starts = [0, *(newline.end() for newline in _NEWLINE.finditer(cleaned))]
+ found: list[CallAssignment] = []
+ for match in pattern.finditer(cleaned):
+ end = _call_end(cleaned, match.end())
+ rest = cleaned[end:].lstrip(" \t") if end >= 0 else ""
+ if end < 0 or (rest and rest[0] not in _STATEMENT_ENDS):
+ continue
+ found.append(
+ CallAssignment(
+ bisect_right(starts, match.start()),
+ match.group("name"),
+ match.group("receiver"),
+ match.group("target"),
+ )
+ )
+ return tuple(found)
+
+
+def record_type(types: dict[str, str | None], name: str, type_name: str) -> None:
+ """``_record`` for a type found outside ``scan_declarations``."""
+ _record(types, Declaration(0, name, type_name))
+
+
def _record(types: dict[str, str | None], declaration: Declaration) -> None:
"""Add one declaration to a scope, or mark the name unanswerable.
diff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.py
index 8b3ec390a..530f461f2 100644
--- a/packages/core/src/repowise/core/ingestion/return_types.py
+++ b/packages/core/src/repowise/core/ingestion/return_types.py
@@ -46,6 +46,31 @@ def signature_parameter_count(signature: str) -> int | None:
return None
+def go_first_result(value: str) -> str:
+ """The first result's type of a go result list, ``(*T, error)`` -> ``*T``.
+
+ Named results group their names, so ``(a, b *T, err error)`` types ``a``
+ by the first entry that carries a type.
+ """
+ if not value.startswith("(") or not value.endswith(")"):
+ return value
+ entries: list[str] = []
+ depth = 0
+ current = ""
+ for char in value[1:-1]:
+ if char == "," and depth == 0:
+ entries.append(current.strip())
+ current = ""
+ continue
+ depth += (char in "([{") - (char in ")]}")
+ current += char
+ entries.append(current.strip())
+ if not any(" " in entry for entry in entries):
+ return entries[0]
+ typed = next(entry for entry in entries if " " in entry)
+ return typed.split(None, 1)[1]
+
+
def normalize_return_type(raw: str, language: str) -> str | None:
"""Reduce a named return type to the repository's class-name key.
diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.py
index 2fb16985f..b29823f33 100644
--- a/tests/unit/ingestion/test_call_resolver_strategies.py
+++ b/tests/unit/ingestion/test_call_resolver_strategies.py
@@ -515,6 +515,187 @@ class TestFieldTypedReceiver:
assert ("Token.cs::Chars::Clear", "Base.cs::Base::Reset", "self_inherited") in edges
+_GO_DETECT = (
+ "go",
+ "package detect\n\n"
+ "type Detector struct{}\n\n"
+ "type Other struct{}\n\n"
+ "func NewDetector() *Detector { return &Detector{} }\n\n"
+ "func NewPair() (*Detector, error) { return &Detector{}, nil }\n\n"
+ "func NewOther() *Other { return &Other{} }\n\n"
+ "func (d *Detector) Child() *Other { return &Other{} }\n\n"
+ "func (d *Detector) Scan() int { return 1 }\n\n"
+ "func (o *Other) Scan() int { return 2 }\n\n"
+ "func (o *Other) Walk() int { return 3 }\n",
+)
+
+
+def _go_method_edges(tmp_path: Path, body: str) -> list[tuple[str, str, float, str]]:
+ """Method edges from ``cmd/run.go::run`` whose body is *body*."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "detect/detect.go": _GO_DETECT,
+ "cmd/run.go": (
+ "go",
+ 'package cmd\n\nimport "example.com/app/detect"\n\n'
+ f"func run(ok bool) {{\n{body}}}\n",
+ ),
+ },
+ )
+ _link_imports(parsed, {"cmd/run.go": {"example.com/app/detect": "detect/detect.go"}})
+ edges = _edges(
+ parsed, tmp_path, {"cmd/run.go": {"detect/detect.go"}, "detect/detect.go": set()}
+ )
+ return [e for e in edges if e[0] == "cmd/run.go::run" and e[1].count("::") == 2]
+
+
+class TestGoCallTypedLocal:
+ """``x := pkg.New(..)`` types ``x`` from ``New``'s declared return type."""
+
+ def test_a_constructor_result_types_its_receiver(self, tmp_path: Path) -> None:
+ edges = _go_method_edges(tmp_path, "\td := detect.NewDetector()\n\td.Scan()\n")
+ assert [e[1] for e in edges] == ["detect/detect.go::Detector::Scan"]
+ assert edges[0][3].startswith("receiver_typed_")
+
+ def test_the_first_of_several_results_is_the_type(self, tmp_path: Path) -> None:
+ body = "\td, err := detect.NewPair()\n\t_ = err\n\td.Scan()\n"
+ edges = _go_method_edges(tmp_path, body)
+ assert [e[1] for e in edges] == ["detect/detect.go::Detector::Scan"]
+
+ def test_a_local_typed_from_a_method_on_an_earlier_one(self, tmp_path: Path) -> None:
+ body = "\td := detect.NewDetector()\n\tc := d.Child()\n\tc.Walk()\n"
+ assert sorted(e[1] for e in _go_method_edges(tmp_path, body)) == [
+ "detect/detect.go::Detector::Child",
+ "detect/detect.go::Other::Walk",
+ ]
+
+ def test_two_blocks_declaring_different_types_type_neither(self, tmp_path: Path) -> None:
+ """Each ``:=`` is its own block's variable, and which one a call sees
+ is not read from the text, so the name gets no type."""
+ body = (
+ "\tif ok {\n\t\td := detect.NewDetector()\n\t\td.Scan()\n\t} else {\n"
+ "\t\td := detect.NewOther()\n\t\td.Scan()\n\t}\n"
+ )
+ assert _go_method_edges(tmp_path, body) == []
+
+ def test_a_chained_right_hand_side_is_not_the_head_s_type(self, tmp_path: Path) -> None:
+ """``x`` holds ``Child``'s result, never ``NewDetector``'s."""
+ body = "\tx := detect.NewDetector().Child()\n\tx.Scan()\n"
+ targets = [e[1] for e in _go_method_edges(tmp_path, body)]
+ assert "detect/detect.go::Detector::Scan" not in targets
+
+
+ def test_a_declared_name_keeps_its_declaration_s_type(self, tmp_path: Path) -> None:
+ """A call-typed ``:=`` of a name a literal already types adds nothing,
+ so the existing reading is neither changed nor refused."""
+ body = (
+ "\tc := &detect.Other{}\n\tif ok {\n\t\tc := detect.NewOther()\n\t\t_ = c\n\t}\n"
+ "\tc.Walk()\n"
+ )
+ targets = [e[1] for e in _go_method_edges(tmp_path, body)]
+ assert targets == ["detect/detect.go::Other::Walk"]
+
+
+ def test_a_callee_reached_by_a_repo_wide_guess_types_nothing(
+ self, tmp_path: Path
+ ) -> None:
+ """``fs.Open`` on an interface lands on another package's ``Fs`` only
+ by name; its return type must not seed a second guess."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "app/fs.go": (
+ "go",
+ "package app\n\ntype Fs interface {\n\tOpen() File\n}\n\n"
+ "type File interface {\n\tClose() error\n}\n\n"
+ "func Read(fs Fs) {\n\tf := fs.Open()\n\tf.Close()\n}\n",
+ ),
+ "gcs/fs.go": (
+ "go",
+ "package gcs\n\ntype Fs struct{}\n\ntype GcsFile struct{}\n\n"
+ "func (fs *Fs) Open() *GcsFile { return nil }\n\n"
+ "func (f *GcsFile) Close() error { return nil }\n",
+ ),
+ },
+ )
+ edges = _edges(parsed, tmp_path)
+ assert "gcs/fs.go::GcsFile::Close" not in [e[1] for e in edges]
+
+
+ def test_a_method_in_a_sibling_file_of_the_type_s_package(self, tmp_path: Path) -> None:
+ """Go puts methods in any file of the package, not only the type's."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "detect/detect.go": (
+ "go",
+ "package detect\n\ntype Detector struct{}\n\n"
+ "func NewDetector() *Detector { return &Detector{} }\n",
+ ),
+ "detect/baseline.go": (
+ "go",
+ "package detect\n\nfunc (d *Detector) AddBaseline() error { return nil }\n",
+ ),
+ "cmd/run.go": (
+ "go",
+ 'package cmd\n\nimport "example.com/app/detect"\n\n'
+ "func run() {\n\td := detect.NewDetector()\n\td.AddBaseline()\n}\n",
+ ),
+ },
+ )
+ _link_imports(parsed, {"cmd/run.go": {"example.com/app/detect": "detect/detect.go"}})
+ edges = _edges(
+ parsed,
+ tmp_path,
+ {
+ "cmd/run.go": {"detect/detect.go"},
+ "detect/detect.go": set(),
+ "detect/baseline.go": set(),
+ },
+ )
+ assert (
+ "cmd/run.go::run",
+ "detect/baseline.go::Detector::AddBaseline",
+ 0.88,
+ "receiver_typed_import",
+ ) in edges
+
+
+ def test_a_same_named_type_in_another_package_does_not_answer(
+ self, tmp_path: Path
+ ) -> None:
+ """``Open`` returns ``detect``'s own ``Store``; ``other.Store`` shares
+ only the name, and the name is all a repo-wide lookup would see."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "detect/store.go": (
+ "go",
+ "package detect\n\ntype Store interface {\n\tSave() int\n}\n\n"
+ "func Open() Store { return nil }\n",
+ ),
+ "other/store.go": (
+ "go",
+ "package other\n\ntype Store struct{}\n\n"
+ "func (s *Store) Save() int { return 1 }\n",
+ ),
+ "cmd/run.go": (
+ "go",
+ 'package cmd\n\nimport "example.com/app/detect"\n\n'
+ "func run() {\n\ts := detect.Open()\n\ts.Save()\n}\n",
+ ),
+ },
+ )
+ _link_imports(parsed, {"cmd/run.go": {"example.com/app/detect": "detect/store.go"}})
+ edges = _edges(
+ parsed,
+ tmp_path,
+ {"cmd/run.go": {"detect/store.go"}, "detect/store.go": set(), "other/store.go": set()},
+ )
+ assert "other/store.go::Store::Save" not in [e[1] for e in edges]
+
+
class TestPythonTypedReceiver:
"""Python reaches the same strategy through its own declaration shapes."""
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index 2dc2591ce..1f2fc4686 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -11,6 +11,8 @@ import pytest
from repowise.core.ingestion.languages.receiver_types import (
IMPLICIT_FIELD_LANGUAGES,
RECEIVER_TYPE_LANGUAGES,
+ CallAssignment,
+ scan_call_assignments,
scan_declarations,
types_by_class,
types_in_span,
@@ -549,7 +551,7 @@ class TestGoShapes:
def test_a_constructor_call_names_no_type(self) -> None:
"""``x := NewFoo()`` types ``x`` only via the callee's return type,
- which is a second lookup this mechanism does not do."""
+ which the resolver reads from ``scan_call_assignments``, not here."""
assert declared_types("func f() { d := NewDetector() }", "go") == {}
def test_a_slice_literal_does_not_type_its_element(self) -> None:
@@ -638,6 +640,41 @@ class TestGoFields:
assert declared_types(body, "go") == {}
+class TestGoCallAssignments:
+ """``x := f(..)``: the call the resolver reads a return type from."""
+
+ def test_a_qualified_call(self) -> None:
+ body = "func f() {\n\td := detect.NewDetector(ctx, cfg)\n}"
+ assert scan_call_assignments(body, "go") == (
+ CallAssignment(2, "d", "detect", "NewDetector"),
+ )
+
+ def test_a_multiple_result_call_names_its_first_result(self) -> None:
+ body = "func f() {\n\td, err := New()\n}"
+ assert scan_call_assignments(body, "go") == (CallAssignment(2, "d", None, "New"),)
+
+ def test_arguments_may_span_lines_and_quote_parens(self) -> None:
+ body = 'func f() {\n\td := New(\n\t\t")", `(`,\n\t)\n\td.Run()\n}'
+ assert [a.name for a in scan_call_assignments(body, "go")] == ["d"]
+
+ def test_an_if_initialiser_is_a_whole_statement(self) -> None:
+ body = "func f() {\n\tif d, err := New(); err != nil {\n\t}\n}"
+ assert [a.name for a in scan_call_assignments(body, "go")] == ["d"]
+
+ def test_a_chained_call_is_not_the_head_s_result(self) -> None:
+ """``x`` holds what ``g`` returns, not what ``f`` returns."""
+ assert scan_call_assignments("func f() {\n\tx := f().g()\n}", "go") == ()
+
+ def test_an_expression_around_the_call_is_refused(self) -> None:
+ assert scan_call_assignments("func f() {\n\tn := count() + 1\n}", "go") == ()
+
+ def test_a_composite_literal_is_left_to_scan_declarations(self) -> None:
+ assert scan_call_assignments("func f() {\n\tr := Rule{}\n}", "go") == ()
+
+ def test_other_languages_scan_nothing(self) -> None:
+ assert scan_call_assignments("x := f()\n", "java") == ()
+
+
class TestClassScope:
"""What counts as a field, given that a class span contains every method.
diff --git a/tests/unit/ingestion/test_return_types.py b/tests/unit/ingestion/test_return_types.py
index 2ab05ddb0..961a4ae55 100644
--- a/tests/unit/ingestion/test_return_types.py
+++ b/tests/unit/ingestion/test_return_types.py
@@ -4,6 +4,7 @@ import pytest
from repowise.core.ingestion.return_types import (
declared_return_type,
+ go_first_result,
normalize_return_type,
signature_parameter_count,
)
@@ -42,3 +43,17 @@ def test_normalize_return_type_keeps_the_declared_wrapper(
raw: str, language: str, expected: str
) -> None:
assert normalize_return_type(raw, language) == expected
+
+
+ ("raw", "expected"),
+ [
+ ("*zerolog.Event", "*zerolog.Event"),
+ ("(*Detector, error)", "*Detector"),
+ ("(d *Detector, err error)", "*Detector"),
+ ("(a, b *Pair, err error)", "*Pair"),
+ ("(map[string]int, error)", "map[string]int"),
+ ],
+)
+def test_go_first_result(raw: str, expected: str) -> None:
+ assert go_first_result(raw) == expected
diff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.py
index 1b29f0b78..738d7c3d9 100644
--- a/tests/unit/test_no_bare_type_name_copies.py
+++ b/tests/unit/test_no_bare_type_name_copies.py
@@ -79,9 +79,11 @@ _KNOWN: dict[str, int] = {
# its head, to ask whether the package it names is one of ours. The rest
# 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.
+ # segment is a variable or a field and none is discarded, and one that
+ # reads the head of a go return type (`pkg.T`) to find the package the
+ # callee's file imports as `pkg`; its tail comes from the shared helper.
_PREFIX + "call_resolver.py": 6,
- _PREFIX + "call_receiver_typing.py": 3,
+ _PREFIX + "call_receiver_typing.py": 4,
_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.