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 call through a struct field from the field's declaration (#2767)

Raghav Chamadiya7df0488e1d59
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 f9e80798f..934f65e69 100644
--- a/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
+++ b/packages/core/src/repowise/core/ingestion/call_receiver_typing.py
@@ -36,11 +36,11 @@ _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"}
+# receiver, every segment after the head a field. Each maps to the name that
+# means the caller's own instance; TypeScript's ``self`` is a global, not
+# ``this``. Go has no such name: its receiver is a parameter, typed from the
+# body, and a ``pkg.Var`` head types nothing, so it cannot pass for ``s.field``.
+_CHAIN_SELF: dict[str, str | None] = {"python": "self", "typescript": "this", "go": None}
# 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.
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 e7a2aff7a..f2f340d53 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -148,6 +148,35 @@ _GO_SHORT_DECL = re.compile(
# ``var x Foo`` / ``var x *Foo``: rare, but no pattern above reaches it.
_GO_VAR_DECL = re.compile(rf"(?<![\w.])var\s+(?P<name>{_GO_NAME})\s+\*?(?P<type>{_GO_TYPE})")
+# A struct field is the rest of its line: a type, its type arguments (two levels,
+# the ``_TYPE`` ceiling) and a tag. A field is typed only as ``T`` or ``*T``, as
+# ``_GO_SHORT_DECL`` types a value: ``[]T``, ``map[K]T`` and ``chan T`` hold a
+# ``T`` but are not one. Exported fields are capitalised, so the name is too.
+#
+# The type is unqualified: ``fd *sftp.File`` is never the ``File`` the file
+# itself declares, and a chain hop can only look a type up in its own file.
+# Ceiling: a field typed from another repo package stays untyped until a hop
+# can follow a Go import to a package.
+_GO_FIELD_NAME = r"[A-Za-z_]\w*"
+_GO_FIELD_END = r"(?:\[(?:[^\[\]\n]|\[[^\[\]\n]*\])*\])?[ \t]*(?:`[^`\n]*`?)?[ \t]*$"
+
+# ``parent *Command``, and each name of ``a, b Foo``: a name opens the line or
+# follows a comma, and the lookahead leaves the next name unconsumed. Both field
+# shapes set ``member`` to their whole match, so they reach class scope whatever
+# closed them and never type a local: a body line such as ``return err`` matches
+# too, but lies in no struct. That holds while a Go struct span never contains a
+# function body; ``test_a_field_never_types_a_local`` guards it.
+_GO_FIELD = re.compile(
+ rf"(?m)(?:^[ \t]*|,[ \t]*)(?P<member>(?P<name>{_GO_FIELD_NAME}))"
+ rf"(?=(?:[ \t]*,[ \t]*{_GO_FIELD_NAME})*[ \t]+\*?(?P<type>{_GO_FIELD_NAME}){_GO_FIELD_END})"
+)
+
+# An embedded ``Base`` or ``*Base`` is a field named ``Base``, the name
+# ``c.Base.Method()`` reads it by.
+_GO_EMBEDDED_FIELD = re.compile(
+ rf"(?m)^[ \t]*\*?(?P<member>(?P<type>(?P<name>{_GO_FIELD_NAME}))){_GO_FIELD_END}"
+)
+
# Kotlin annotates after the name, and `val x: Foo`, `var x: Foo`, parameters
# and `class A(val x: Foo)` are all `name: Type`.
#
@@ -230,9 +259,10 @@ _CPP_DECLARATION = re.compile(
_C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)
-# No Go shape captures a closer, so class scope drops every Go declaration:
-# intended, since Go is not in IMPLICIT_FIELD_LANGUAGES.
-_GO_FAMILY = (_GO_PARAM, _GO_SHORT_DECL, _GO_VAR_DECL)
+# Only the field shapes reach class scope. Go is still not in
+# IMPLICIT_FIELD_LANGUAGES: a field is read through its receiver (``c.parent``),
+# so it types a chain hop and never a bare name.
+_GO_FAMILY = (_GO_PARAM, _GO_SHORT_DECL, _GO_VAR_DECL, _GO_FIELD, _GO_EMBEDDED_FIELD)
_KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED)
_SWIFT_FAMILY = (_SWIFT_ANNOTATED, _SWIFT_CONSTRUCTED)
_PY_FAMILY = (_PY_ANNOTATED, _PY_CONSTRUCTED, _PY_SELF_ANNOTATED, _PY_SELF_CONSTRUCTED)
@@ -468,7 +498,8 @@ class Declaration(NamedTuple):
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
+ method (``self.x = T()``, a constructor parameter property) or, in Go, a
+ struct field, which no closer tells from a local. It belongs
to the class wherever it sits, and never to the body.
"""
diff --git a/tests/unit/ingestion/test_chained_receiver_calls.py b/tests/unit/ingestion/test_chained_receiver_calls.py
index 538c7e2c9..a2d8bd6d9 100644
--- a/tests/unit/ingestion/test_chained_receiver_calls.py
+++ b/tests/unit/ingestion/test_chained_receiver_calls.py
@@ -427,3 +427,66 @@ class TestPyChainedFieldCalls:
},
)
assert [(c.receiver_name, c.target_name) for c in parsed["m.py"].calls] == [(None, "make")]
+
+
+# --- go_chained_field_calls --------------------------------------------------
+
+_GO_COMMAND = (
+ "package cmd\n\n"
+ "type GitCmd struct{}\n\n"
+ "func (g *GitCmd) DiffFilesCh() {}\n\n"
+ "type Base struct{}\n\n"
+ "func (b *Base) Close() {}\n\n"
+ "type Command struct {\n"
+ "\t*Base\n"
+ "\tCmd *GitCmd `json:\"cmd\"`\n"
+ "\tcommands []*GitCmd\n"
+ "}\n\n"
+)
+
+
+class TestGoChainedFieldCalls:
+ """Go names its receiver, so the head is a parameter; each hop a struct field."""
+
+ def _edges(self, tmp_path: Path, body: str) -> list[tuple[str, str, float, str]]:
+ return _chained(_edges(tmp_path, {"cmd/command.go": ("go", _GO_COMMAND + body)}))
+
+ def test_a_field_types_the_chain(self, tmp_path: Path) -> None:
+ body = "func (c *Command) Run() {\n\tc.Cmd.DiffFilesCh()\n}\n"
+ assert self._edges(tmp_path, body) == [
+ (
+ "cmd/command.go::Command::Run",
+ "cmd/command.go::GitCmd::DiffFilesCh",
+ 0.93,
+ "receiver_chain_same_file",
+ )
+ ]
+
+ def test_an_embedded_field_is_read_by_its_type_name(self, tmp_path: Path) -> None:
+ body = "func (c *Command) Run() {\n\tc.Base.Close()\n}\n"
+ assert [e[:2] for e in self._edges(tmp_path, body)] == [
+ ("cmd/command.go::Command::Run", "cmd/command.go::Base::Close")
+ ]
+
+ def test_a_slice_field_yields_no_edge(self, tmp_path: Path) -> None:
+ body = "func (c *Command) Run() {\n\tc.commands.DiffFilesCh()\n}\n"
+ assert self._edges(tmp_path, body) == []
+
+ def test_a_method_missing_on_the_field_type_yields_no_edge(self, tmp_path: Path) -> None:
+ body = "func (c *Command) Run() {\n\tc.Cmd.Close()\n}\n"
+ assert self._edges(tmp_path, body) == []
+
+ def test_a_package_qualified_head_yields_no_edge(self, tmp_path: Path) -> None:
+ """``pkg.Var.M()`` has the same shape as ``c.field.M()``, but ``pkg`` types nothing."""
+ body = "func run() {\n\tconfig.Cmd.DiffFilesCh()\n}\n"
+ assert self._edges(tmp_path, body) == []
+
+ def test_a_package_qualified_field_type_is_not_the_local_type(self, tmp_path: Path) -> None:
+ """``fd *sftp.File`` wraps a foreign ``File``; its ``Write`` is not this file's."""
+ source = (
+ "package sftpfs\n\n"
+ "type File struct {\n\tfd *sftp.File\n}\n\n"
+ "func (f *File) Write(b []byte) {}\n\n"
+ "func (f *File) WriteString(s string) {\n\tf.fd.Write([]byte(s))\n}\n"
+ )
+ assert _chained(_edges(tmp_path, {"sftpfs/file.go": ("go", source)})) == []
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index ce06e130f..2dc2591ce 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -572,6 +572,72 @@ class TestGoShapes:
assert declared_types(body, "go")["r"] is None
+def go_fields(source: str) -> dict[str, str | None]:
+ """The fields of one struct spanning the whole text; Go methods sit outside it."""
+ lines = source.count("\n") + 1
+ return types_by_class(
+ scan_declarations(source, "go"), {"f.go::C": (1, lines)}, [], "go"
+ ).get("f.go::C", {})
+
+
+class TestGoFields:
+ """A struct field ends at its line, so no closer marks it: it is a ``member``."""
+
+ def test_a_pointer_and_a_value_field(self) -> None:
+ source = "type C struct {\n\tparent *Command\n\tcfg Config\n}"
+ assert go_fields(source) == {"parent": "Command", "cfg": "Config"}
+
+ def test_an_exported_field(self) -> None:
+ assert go_fields("type C struct {\n\tCmd *GitCmd\n}") == {"Cmd": "GitCmd"}
+
+ def test_every_name_of_a_shared_type(self) -> None:
+ source = "type C struct {\n\tleft, right *Node\n}"
+ assert go_fields(source) == {"left": "Node", "right": "Node"}
+
+ def test_a_tag_is_not_part_of_the_type(self) -> None:
+ source = 'type C struct {\n\tCmd GitCmd `json:"cmd,omitempty"`\n}'
+ assert go_fields(source) == {"Cmd": "GitCmd"}
+
+ def test_a_generic_keeps_its_head(self) -> None:
+ source = "type C struct {\n\tstore Store[K, V]\n\tdeep Store[Pair[K, V]]\n}"
+ assert go_fields(source) == {"store": "Store", "deep": "Store"}
+
+ def test_an_embedded_type_is_a_field_of_its_own_name(self) -> None:
+ source = "type C struct {\n\t*Base\n\tLogger\n}"
+ assert go_fields(source) == {"Base": "Base", "Logger": "Logger"}
+
+ def test_a_package_qualified_type_is_refused(self) -> None:
+ """``sftp.File`` is not the ``File`` this file declares, so it types nothing."""
+ source = "type C struct {\n\tfd *sftp.File\n\tsync.Mutex\n}"
+ assert go_fields(source) == {}
+
+ def test_a_trailing_comment_is_ignored(self) -> None:
+ assert go_fields("type C struct {\n\tcfg Config // the config\n}") == {"cfg": "Config"}
+
+ def test_a_container_does_not_type_its_element(self) -> None:
+ """``c.commands`` is a slice of Command, not a Command."""
+ source = (
+ "type C struct {\n\tcommands []*Command\n\tbyName map[string]*Command\n"
+ "\tch chan Command\n\tgen map[string]Store[K]\n}"
+ )
+ assert go_fields(source) == {}
+
+ def test_a_predeclared_type_is_refused(self) -> None:
+ assert go_fields("type C struct {\n\tname string\n\terr error\n}") == {}
+
+ def test_an_interface_method_is_not_a_field(self) -> None:
+ source = "type C interface {\n\tDo(a, b Command) error\n\tClose() error\n}"
+ assert go_fields(source) == {}
+
+ def test_a_function_typed_field_is_not_typed_by_its_parameters(self) -> None:
+ assert go_fields("type C struct {\n\tcb func(a, b Command) error\n}") == {}
+
+ def test_a_field_never_types_a_local(self) -> None:
+ """A body line of the same shape (``return err``) must not bind a local."""
+ body = "func f() {\n\tcfg Config\n\treturn err\n}"
+ assert declared_types(body, "go") == {}
+
+
class TestClassScope:
"""What counts as a field, given that a class span contains every method.
@@ -639,11 +705,11 @@ def test_the_language_set_is_what_the_patterns_declare() -> None:
def test_go_is_not_a_field_language() -> None:
- """Go declares no field this mechanism can read, and must not claim to.
+ """A Go field is read through its receiver, never as a bare name.
- Its shapes capture no closer, so class scope would drop every one of them
- anyway — but the set is the contract, and a package-level ``var`` is a
- wider scope than a field rather than the same one.
+ Its struct fields reach class scope, where only a chain hop
+ (``c.parent.M()``) reads them; the set is the contract that a bare
+ ``parent.M()`` does not.
"""
assert "go" not in IMPLICIT_FIELD_LANGUAGES