fix(go): resolve same-file member calls through receiver types
Resolve same-file member calls through declared receiver types, preserve lexical receiver bindings, and keep bare package calls distinct from methods.
Refs #4962
(cherry picked from commit 4872e284df)
This commit is contained in:
1 parent
d7bff93019
commit
8ed0f30698
6 files changed
+383
-82
No files matched your search
@@ -117,6 +117,11 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
|
||||
| `INFERRED` | Relationship is a reasonable deduction (e.g., call-graph second pass, co-occurrence in context) |
|
||||
| `AMBIGUOUS` | Relationship is uncertain; flagged for human review in GRAPH_REPORT.md |
|
||||
|
||||
Go member calls, including same-file calls, resolve through declared receiver types and
|
||||
carry `INFERRED` confidence. Bare calls to package-level functions remain `EXTRACTED`;
|
||||
unknown or ambiguous receivers do not bind by method name alone. AST cache schema 37
|
||||
retires Go entries created before these receiver-binding rules.
|
||||
|
||||
## Adding a new language extractor
|
||||
|
||||
1. Add an `extract_<lang>(path: Path) -> dict` function following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges). New languages go in their own module under `graphify/extractors/` - see `graphify/extractors/MIGRATION.md`; `extract.py` re-exports them while the existing ones are ported out of it.
|
||||
|
||||
+20
-18
@@ -7676,12 +7676,9 @@ def _resolve_go_member_calls(
|
||||
) -> None:
|
||||
"""Resolve Go member calls (``g.Greet()``) through the receiver's declared type.
|
||||
|
||||
The shared cross-file pass skips member calls, so a method call on a receiver whose
|
||||
type is declared in another file resolved to nothing. The per-file ``go_type_table``
|
||||
names the declared type of every struct field, parameter (the method receiver
|
||||
included), ``var x T`` and ``x := T{}`` binding; this pass looks the receiver up
|
||||
there, takes the single declaration of that type, and emits the ``calls`` edge to its
|
||||
method. Always INFERRED: the type comes from a declaration, never from the call site.
|
||||
Local bindings carry their receiver type; only unbound names may fall back to
|
||||
package variables. Fields resolve through their owning struct. Always INFERRED:
|
||||
the method target comes from the receiver's declared type.
|
||||
|
||||
Names are matched case-sensitively, unlike the sibling resolvers. Go exports by
|
||||
capitalisation, so `Run` and `run` on one type are two different methods with two
|
||||
@@ -7699,11 +7696,11 @@ def _resolve_go_member_calls(
|
||||
]
|
||||
if not raw:
|
||||
return
|
||||
type_table_by_file: dict[str, dict[str, str]] = {}
|
||||
package_vars_by_file: dict[str, dict[str, str | None]] = {}
|
||||
for result in per_file:
|
||||
tt = result.get("go_type_table")
|
||||
if tt and tt.get("path"):
|
||||
type_table_by_file[tt["path"]] = tt.get("table", {})
|
||||
package_vars_by_file[tt["path"]] = tt.get("package_vars", {})
|
||||
|
||||
def _key(label: object) -> str:
|
||||
return str(label or "").strip().removeprefix(".").removesuffix("()")
|
||||
@@ -7715,10 +7712,8 @@ def _resolve_go_member_calls(
|
||||
# class would both answer a Go receiver and hide that nothing local declares it.
|
||||
type_def_nids: dict[str, list[str]] = {}
|
||||
node_by_id: dict[str, dict] = {}
|
||||
# A struct's fields, by struct id, from the file node that declares it: a method in
|
||||
# one file of the package and the struct in another is the common Go layout, and the
|
||||
# caller's flat table holds only what its own file declares. An id two files declare
|
||||
# has no single answer.
|
||||
# Owner fields may be declared in a sibling file. Duplicate owner declarations
|
||||
# provide no unique field type.
|
||||
fields_by_type: dict[str, list[dict[str, str]]] = {}
|
||||
for n in all_nodes:
|
||||
node_by_id[n.get("id")] = n
|
||||
@@ -7737,17 +7732,18 @@ def _resolve_go_member_calls(
|
||||
(e.get("source"), _key(tnode.get("label", ""))), []).append(e["target"])
|
||||
|
||||
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
|
||||
for rc in raw:
|
||||
# One edge survives per pair, so direct calls must take priority over method values.
|
||||
for rc in sorted(raw, key=lambda call: bool(call.get("indirect"))):
|
||||
receiver, callee, caller = rc["member_receiver"], rc["callee"], rc["caller_nid"]
|
||||
# The enclosing method's own receiver is typed by its declaration, which beats the
|
||||
# flat table: two types in one file may both name their receiver `s`.
|
||||
type_name = rc.get("receiver_type") or type_table_by_file.get(
|
||||
rc.get("source_file", ""), {}).get(receiver)
|
||||
if not type_name and rc.get("field_owner"):
|
||||
type_name = rc.get("receiver_type")
|
||||
if rc.get("field_owner"):
|
||||
type_name = None
|
||||
owner_defs = type_def_nids.get(_key(rc["field_owner"]), [])
|
||||
declared = fields_by_type.get(owner_defs[0], []) if len(owner_defs) == 1 else []
|
||||
if len(declared) == 1:
|
||||
type_name = declared[0].get(receiver)
|
||||
elif not type_name and not rc.get("receiver_bound"):
|
||||
type_name = package_vars_by_file.get(rc.get("source_file", ""), {}).get(receiver)
|
||||
if not type_name or type_name in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
continue
|
||||
type_defs = type_def_nids.get(_key(type_name), [])
|
||||
@@ -11194,6 +11190,10 @@ def extract(
|
||||
_member_nids = {
|
||||
e.get("target") for e in all_edges if e.get("relation") in ("case_of", "defines")
|
||||
}
|
||||
_method_nids = {
|
||||
e.get("target") for e in all_edges + list(resolution_context_edges or [])
|
||||
if e.get("relation") == "method"
|
||||
}
|
||||
# Top-level Elixir module names per file, for scoping unqualified Elixir
|
||||
# calls below. Read from `resolution_nodes` so an unchanged file's modules
|
||||
# stay visible on an incremental rebuild (`_elixir_module` is carried by the
|
||||
@@ -11303,6 +11303,8 @@ def extract(
|
||||
candidates = global_label_to_nids.get(callee, [])
|
||||
if not candidates and _lang_is_case_insensitive(rc.get("source_file")):
|
||||
candidates = global_label_to_nids_ci.get(callee.lower(), [])
|
||||
if rc.get("language") == "go":
|
||||
candidates = [candidate for candidate in candidates if candidate not in _method_nids]
|
||||
if not candidates:
|
||||
continue
|
||||
if rc.get("lang") == "csharp" and not rc.get("csharp_new") and len(candidates) > 1:
|
||||
|
||||
+90
-55
@@ -175,12 +175,13 @@ def _go_strip_generic_args(type_text: str) -> str:
|
||||
def _go_single_type_name(node, source: bytes) -> str | None:
|
||||
"""The one declared type a Go type expression names, or None.
|
||||
|
||||
Only `Greeter` and `*Greeter` qualify. A slice, map or channel element is not the
|
||||
receiver of `x.M()`, and a `qualified_type` (`pkg.Greeter`) names a type no bare
|
||||
local name can stand for.
|
||||
Generic arguments do not change the receiver's base type. A slice, map or channel
|
||||
element is not the receiver, and a qualified type cannot bind by bare local name.
|
||||
"""
|
||||
if node is not None and node.type == "pointer_type":
|
||||
node = next((c for c in node.children if c.is_named), None)
|
||||
while node is not None and node.type in ("pointer_type", "parenthesized_type", "generic_type"):
|
||||
node = node.child_by_field_name("type") or next(
|
||||
(c for c in node.children if c.is_named), None,
|
||||
)
|
||||
if node is None or node.type != "type_identifier":
|
||||
return None
|
||||
name = _read_text(node, source)
|
||||
@@ -205,46 +206,56 @@ def _go_inferred_composite_bindings(names, values, source: bytes):
|
||||
yield _read_text(name_node, source), type_name
|
||||
|
||||
|
||||
def _go_receiver_type_table(root, source: bytes) -> dict[str, str]:
|
||||
"""Collect ``name -> TypeName`` for every Go receiver whose type is written down.
|
||||
def _go_receiver_type_table(
|
||||
root, source: bytes, *, package_only: bool = False,
|
||||
) -> dict[str, str | None]:
|
||||
"""Collect declared or composite-literal receiver types, preserving unknown bindings.
|
||||
|
||||
Five sources: a struct field, a parameter (which covers the method receiver
|
||||
`func (s *Server)`), `var x T`, `x := T{}` / `x := &T{}`, and `var x = T{}` /
|
||||
`var x = &T{}` (the same composite-literal inference, spelled with `var`
|
||||
instead of `:=`). Flat over the subtree it is given, first binding wins —
|
||||
run over one function it is that function's own scope, and over the file it
|
||||
is the fallback for a struct field. Children are pushed reversed so the
|
||||
walk yields document order and "first" means first in the source.
|
||||
Unknown local bindings shadow package variables. Package-only tables exclude
|
||||
fields and function bodies so unrelated scopes cannot supply a receiver type.
|
||||
"""
|
||||
table: dict[str, str] = {}
|
||||
table: dict[str, str | None] = {}
|
||||
stack = [root]
|
||||
while stack:
|
||||
n = stack.pop()
|
||||
t = n.type
|
||||
if t in ("field_declaration", "parameter_declaration", "var_spec"):
|
||||
type_name = _go_single_type_name(n.child_by_field_name("type"), source)
|
||||
if type_name:
|
||||
for c in n.children:
|
||||
if c.type in ("field_identifier", "identifier"):
|
||||
table.setdefault(_read_text(c, source), type_name)
|
||||
elif t == "var_spec":
|
||||
if t == "block" or (t == "func_literal" and n != root):
|
||||
continue
|
||||
if package_only and t in (
|
||||
"function_declaration", "method_declaration", "func_literal", "type_declaration",
|
||||
):
|
||||
continue
|
||||
if t in (
|
||||
"field_declaration", "parameter_declaration",
|
||||
"variadic_parameter_declaration", "var_spec",
|
||||
):
|
||||
names = [c for c in n.children if c.type in ("field_identifier", "identifier")]
|
||||
type_name = (None if t == "variadic_parameter_declaration"
|
||||
else _go_single_type_name(n.child_by_field_name("type"), source))
|
||||
inferred = {}
|
||||
if t == "var_spec" and not type_name:
|
||||
value = n.child_by_field_name("value")
|
||||
if value is not None:
|
||||
names = [c for c in n.children if c.type == "identifier"]
|
||||
values = [c for c in value.children if c.is_named]
|
||||
for name_text, inferred in _go_inferred_composite_bindings(
|
||||
names, values, source
|
||||
):
|
||||
table.setdefault(name_text, inferred)
|
||||
inferred = dict(_go_inferred_composite_bindings(
|
||||
names, [c for c in value.children if c.is_named], source,
|
||||
))
|
||||
for name_node in names:
|
||||
name = _read_text(name_node, source)
|
||||
table.setdefault(name, type_name or inferred.get(name))
|
||||
elif t == "short_var_declaration":
|
||||
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
|
||||
if left is not None and right is not None:
|
||||
names = [c for c in left.children if c.type == "identifier"]
|
||||
values = [c for c in right.children if c.is_named]
|
||||
for name_text, inferred in _go_inferred_composite_bindings(
|
||||
names, values, source
|
||||
):
|
||||
table.setdefault(name_text, inferred)
|
||||
inferred = dict(_go_inferred_composite_bindings(names, values, source))
|
||||
for name_node in names:
|
||||
name = _read_text(name_node, source)
|
||||
table.setdefault(name, inferred.get(name))
|
||||
elif t == "range_clause" and any(c.type == ":=" for c in n.children):
|
||||
left = n.child_by_field_name("left")
|
||||
for name_node in left.named_children if left is not None else ():
|
||||
if name_node.type == "identifier":
|
||||
table.setdefault(_read_text(name_node, source), None)
|
||||
stack.extend(reversed(n.children))
|
||||
return table
|
||||
|
||||
@@ -309,11 +320,9 @@ def extract_go(path: Path) -> dict:
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
# `(caller nid, body, receiver variable name, receiver type, own-scope types)` — the
|
||||
# receiver name is what makes `s.logger.Log()` readable as a call on the `logger` field
|
||||
# rather than on `s`, and the scope types are the bindings the file-flat table can get
|
||||
# wrong: every function in a file is free to name a parameter `s` after its own type.
|
||||
function_bodies: list[tuple[str, object, str | None, str | None, dict[str, str]]] = []
|
||||
# The receiver name identifies `s.field` as an owned field; scope bindings keep
|
||||
# parameters and locals distinct from package variables, even with unknown types.
|
||||
function_bodies: list[tuple[str, object, str | None, str | None, dict[str, str | None]]] = []
|
||||
# Fed to the `_callable` / `_callable_class` stamp below (#2438): the indirect-call
|
||||
# guard and the cross-repo member-call pass both read them off the node.
|
||||
callable_nids: set[str] = set()
|
||||
@@ -803,9 +812,14 @@ def extract_go(path: Path) -> dict:
|
||||
file_node["_go_fields"] = dict(sorted(struct_fields.items()))
|
||||
|
||||
type_table = _go_receiver_type_table(root, source)
|
||||
package_types = _go_receiver_type_table(root, source, package_only=True)
|
||||
local_type_names = {n["label"] for n in nodes if n["id"] in callable_class_nids}
|
||||
|
||||
method_nids = {e["target"] for e in edges if e["relation"] == "method"}
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
if n["id"] in method_nids:
|
||||
continue
|
||||
raw = n["label"]
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
@@ -814,9 +828,17 @@ def extract_go(path: Path) -> dict:
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def walk_calls(node, caller_nid: str, self_name: str | None,
|
||||
self_type: str | None, scope_types: dict[str, str]) -> None:
|
||||
self_type: str | None, scope_types: dict[str, str | None]) -> None:
|
||||
if node.type in ("function_declaration", "method_declaration"):
|
||||
return
|
||||
if node.type in (
|
||||
"block", "if_statement", "for_statement", "expression_switch_statement",
|
||||
"type_switch_statement", "select_statement", "expression_case", "type_case",
|
||||
"communication_case", "default_case", "func_literal",
|
||||
):
|
||||
scope_types = scope_types.copy()
|
||||
if node.type == "func_literal":
|
||||
scope_types.update(_go_receiver_type_table(node, source))
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
@@ -843,17 +865,29 @@ def extract_go(path: Path) -> dict:
|
||||
import_path = go_imported_pkgs[receiver_name]
|
||||
elif operand is not None and operand.type == "identifier":
|
||||
member_receiver = receiver_name
|
||||
if self_name and receiver_name == self_name:
|
||||
member_receiver_type = self_type
|
||||
else:
|
||||
member_receiver_type = scope_types.get(receiver_name)
|
||||
member_receiver_type = scope_types.get(receiver_name)
|
||||
if receiver_name not in scope_types and receiver_name in local_type_names:
|
||||
member_receiver_type = receiver_name
|
||||
elif operand is not None and operand.type == "parenthesized_expression":
|
||||
expression = operand
|
||||
while (expression.type == "parenthesized_expression"
|
||||
and expression.named_children):
|
||||
expression = expression.named_children[0]
|
||||
if (expression.type == "unary_expression"
|
||||
and _read_text(expression, source).startswith("*")):
|
||||
expression = expression.child_by_field_name("operand")
|
||||
name = _read_text(expression, source) if expression is not None else ""
|
||||
if name in local_type_names and name not in scope_types:
|
||||
member_receiver = name
|
||||
member_receiver_type = name
|
||||
elif operand is not None and operand.type == "selector_expression":
|
||||
# `s.logger.Log()` names the receiver by the field only when `s` is
|
||||
# this method's own receiver; any other head could be a package or
|
||||
# a variable whose type the flat table does not know.
|
||||
inner = operand.child_by_field_name("operand")
|
||||
if (self_name and inner is not None and inner.type == "identifier"
|
||||
and _read_text(inner, source) == self_name):
|
||||
and _read_text(inner, source) == self_name
|
||||
and scope_types.get(self_name) == self_type):
|
||||
member_receiver = _read_text(
|
||||
operand.child_by_field_name("field"), source)
|
||||
field_owner = self_type
|
||||
@@ -866,8 +900,9 @@ def extract_go(path: Path) -> dict:
|
||||
# of raw_calls, so the cross-file pass cannot bind it either.
|
||||
callee_name = None
|
||||
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
# Never resolve an imported selector through a bare local name.
|
||||
tgt_nid = None if import_path else label_to_nid.get(callee_name)
|
||||
# 成员调用必须按接收者类型解析;裸名不能证明方法属于该接收者。
|
||||
tgt_nid = (None if import_path or is_member_call
|
||||
else label_to_nid.get(callee_name))
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
@@ -895,13 +930,10 @@ def extract_go(path: Path) -> dict:
|
||||
# `is_member_call` plus `receiver` without checking the language,
|
||||
# so a Go name placed there binds to their types in a mixed corpus.
|
||||
"member_receiver": member_receiver,
|
||||
# The enclosing function's own receiver and parameters/locals, whose
|
||||
# declarations are in scope here; the flat table is the fallback for
|
||||
# a struct field, and must not answer a name this scope rebinds.
|
||||
"receiver_type": member_receiver_type,
|
||||
# The struct whose field `member_receiver` is, for `s.field.M()`:
|
||||
# the struct may be declared in another file of the package, where
|
||||
# this file's flat table cannot see its fields.
|
||||
"receiver_bound": not field_owner and member_receiver in scope_types,
|
||||
# Field ownership remains explicit when the struct is declared
|
||||
# in a sibling file of the package.
|
||||
"field_owner": field_owner,
|
||||
"import_path": import_path,
|
||||
"source_file": str_path,
|
||||
@@ -927,12 +959,12 @@ def extract_go(path: Path) -> dict:
|
||||
name = _read_text(operand, source)
|
||||
if name in go_imported_pkgs:
|
||||
continue
|
||||
arg_receiver_type = (self_type if self_name and name == self_name
|
||||
else scope_types.get(name))
|
||||
arg_receiver_type = scope_types.get(name)
|
||||
elif operand.type == "selector_expression":
|
||||
inner = operand.child_by_field_name("operand")
|
||||
if not (self_name and inner is not None and inner.type == "identifier"
|
||||
and _read_text(inner, source) == self_name):
|
||||
and _read_text(inner, source) == self_name
|
||||
and scope_types.get(self_name) == self_type):
|
||||
continue
|
||||
name = _read_text(operand.child_by_field_name("field"), source)
|
||||
arg_receiver_type = None
|
||||
@@ -949,6 +981,7 @@ def extract_go(path: Path) -> dict:
|
||||
"receiver": None,
|
||||
"member_receiver": name,
|
||||
"receiver_type": arg_receiver_type,
|
||||
"receiver_bound": name in scope_types if not arg_field_owner else False,
|
||||
"field_owner": arg_field_owner,
|
||||
"import_path": None,
|
||||
"source_file": str_path,
|
||||
@@ -956,6 +989,8 @@ def extract_go(path: Path) -> dict:
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid, self_name, self_type, scope_types)
|
||||
if child.type in ("short_var_declaration", "var_spec", "range_clause"):
|
||||
scope_types.update(_go_receiver_type_table(child, source))
|
||||
|
||||
for caller_nid, body_node, self_name, self_type, scope_types in function_bodies:
|
||||
walk_calls(body_node, caller_nid, self_name, self_type, scope_types)
|
||||
@@ -972,5 +1007,5 @@ def extract_go(path: Path) -> dict:
|
||||
"edges": clean_edges,
|
||||
"raw_calls": raw_calls,
|
||||
"go_imports": dict(go_imported_pkgs),
|
||||
"go_type_table": {"path": str_path, "table": type_table},
|
||||
"go_type_table": {"path": str_path, "table": type_table, "package_vars": package_types},
|
||||
}
|
||||
@@ -370,11 +370,7 @@ def test_fresh_and_cached_extraction_agree(tmp_path):
|
||||
def test_schema_bumped_for_the_id_change():
|
||||
from graphify import cache
|
||||
|
||||
assert cache._AST_CACHE_SCHEMA >= 30
|
||||
source = Path(cache.__file__).read_text(encoding="utf-8")
|
||||
marker = f"_AST_CACHE_SCHEMA = {cache._AST_CACHE_SCHEMA}"
|
||||
line = next(line for line in source.splitlines() if line.startswith(marker))
|
||||
assert "#4854" in line, "schema bump must document #4854"
|
||||
assert cache._AST_CACHE_SCHEMA >= 34
|
||||
|
||||
|
||||
def test_decl_ids_survive_the_ast_cache(tmp_path):
|
||||
|
||||
@@ -162,16 +162,14 @@ def test_two_packages_declaring_the_same_type_resolve_to_neither(tmp_path):
|
||||
assert _greet_edge(calls) is None, calls
|
||||
|
||||
|
||||
def test_a_same_file_method_call_keeps_its_extracted_edge(tmp_path):
|
||||
# In-file resolution still happens by bare label before this pass, so the edge must
|
||||
# stay EXTRACTED and must not be doubled.
|
||||
def test_a_same_file_method_call_resolves_once_through_its_receiver(tmp_path):
|
||||
calls, _ = _calls(tmp_path, {
|
||||
"svc/app.go": "package svc\n\ntype App struct{}\n\nfunc (a *App) Greet() {}\n\n"
|
||||
"func Run(a *App) { a.Greet() }\n",
|
||||
})
|
||||
edges = [e for (src, tgt), e in calls.items() if src == "Run()" and tgt == ".Greet()"]
|
||||
assert len(edges) == 1, calls
|
||||
assert edges[0]["confidence"] == "EXTRACTED"
|
||||
assert edges[0]["confidence"] == "INFERRED"
|
||||
|
||||
|
||||
def test_a_type_from_another_language_never_answers_a_go_receiver(tmp_path):
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
"""同文件 Go 调用必须区分接收者方法与包级函数。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
importlib.util.find_spec("tree_sitter_go") is None,
|
||||
reason="tree_sitter_go not installed",
|
||||
)
|
||||
|
||||
|
||||
def _targets(tmp_path, source, caller="Use()", siblings=None):
|
||||
path = tmp_path / "app.go"
|
||||
path.write_text("package demo\n" + source, encoding="utf-8")
|
||||
paths = [path]
|
||||
for name, body in (siblings or {}).items():
|
||||
sibling = tmp_path / name
|
||||
sibling.write_text("package demo\n" + body, encoding="utf-8")
|
||||
paths.append(sibling)
|
||||
result = extract(paths, root=tmp_path, cache_root=tmp_path / "cache", parallel=False)
|
||||
nodes = {node["id"]: node for node in result["nodes"]}
|
||||
owners = {
|
||||
edge["target"]: nodes[edge["source"]]["label"]
|
||||
for edge in result["edges"]
|
||||
if edge["relation"] == "method"
|
||||
}
|
||||
return [
|
||||
(owners.get(edge["target"]), nodes[edge["target"]]["label"], edge["confidence"])
|
||||
for edge in result["edges"]
|
||||
if edge["relation"] == "calls" and nodes[edge["source"]]["label"] == caller
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
def test_same_named_methods_follow_the_receiver_in_either_declaration_order(tmp_path, reverse):
|
||||
methods = ["func (*A) apply() {}\n", "func (*B) apply() {}\n"]
|
||||
if reverse:
|
||||
methods.reverse()
|
||||
source = "type A struct{}\ntype B struct{}\n" + "".join(methods)
|
||||
source += "func Use(a *A) { a.apply() }\n"
|
||||
assert _targets(tmp_path, source) == [("A", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
def test_a_unique_method_on_another_type_does_not_answer_the_receiver(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*B) apply() {}\n"
|
||||
"func Use(a *A) { a.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == []
|
||||
|
||||
|
||||
def test_an_unknown_receiver_does_not_bind_a_unique_local_method(tmp_path):
|
||||
source = (
|
||||
"type B struct{}\nfunc (*B) apply() {}\n"
|
||||
"func Use(a Missing) { a.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
def test_a_bare_function_call_never_selects_a_same_named_method(tmp_path, reverse):
|
||||
declarations = ["func apply() {}\n", "func (*B) apply() {}\n"]
|
||||
if reverse:
|
||||
declarations.reverse()
|
||||
source = "type B struct{}\n" + "".join(declarations) + "func Use() { apply() }\n"
|
||||
assert _targets(tmp_path, source) == [(None, "apply()", "EXTRACTED")]
|
||||
|
||||
|
||||
def test_an_imported_selector_never_selects_a_local_function(tmp_path):
|
||||
source = 'import "fmt"\nfunc Println() {}\nfunc Use() { fmt.Println() }\n'
|
||||
assert _targets(tmp_path, source) == []
|
||||
|
||||
|
||||
def test_each_function_keeps_its_receiver_type_in_the_same_file(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func Other(a *B) { a.apply() }\n"
|
||||
"func Use(a *A) { a.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [("A", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
def test_a_field_on_the_methods_own_receiver_selects_its_declared_type(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\ntype App struct { value *A }\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func (app *App) Use() { app.value.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source, caller=".Use()") == [("A", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
def test_an_unknown_local_does_not_borrow_another_functions_parameter_type(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func Other(x *A) {}\nfunc NewB() *B { return &B{} }\n"
|
||||
"func Use() { x := NewB(); x.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [(None, "NewB()", "EXTRACTED")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("binding", ["var x *B", "var x = &B{}"])
|
||||
def test_a_package_variable_does_not_borrow_a_functions_parameter_type(tmp_path, binding):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func Other(x *A) {}\n" + binding + "\nfunc Use() { x.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [("B", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("binding", ["x := NewB()", "var x = NewB()"])
|
||||
def test_an_unknown_local_shadows_a_typed_package_variable(tmp_path, binding):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"var x *A\nfunc NewB() *B { return &B{} }\n"
|
||||
"func Use() { " + binding + "; x.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [(None, "NewB()", "EXTRACTED")]
|
||||
|
||||
|
||||
def test_a_qualified_parameter_does_not_borrow_a_local_type(tmp_path):
|
||||
source = (
|
||||
'import "example.org/other"\n'
|
||||
"type A struct{}\nfunc (*A) apply() {}\n"
|
||||
"func Other(x *A) {}\nfunc Use(x *other.A) { x.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == []
|
||||
|
||||
|
||||
def test_a_field_owner_beats_another_structs_same_named_field(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"type Other struct { value *A }\ntype App struct { value *B }\n"
|
||||
"func (s *App) Use() { s.value.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source, caller=".Use()") == [("B", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
def test_a_direct_call_takes_priority_over_a_method_value(tmp_path, reverse):
|
||||
statements = ["Register(a.apply)", "a.apply()"]
|
||||
if reverse:
|
||||
statements.reverse()
|
||||
source = (
|
||||
"type A struct{}\nfunc (*A) apply() {}\nfunc Register(f func()) {}\n"
|
||||
"func Use(a *A) { " + "; ".join(statements) + " }\n"
|
||||
)
|
||||
assert set(_targets(tmp_path, source)) == {
|
||||
(None, "Register()", "EXTRACTED"), ("A", ".apply()", "INFERRED"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("expression", ["T.apply(t)", "(*T).apply(&t)"])
|
||||
def test_an_explicit_method_expression_resolves_its_receiver_type(tmp_path, expression):
|
||||
source = (
|
||||
"type T struct{}\nfunc (T) apply() {}\n"
|
||||
"func Use(t T) { " + expression + " }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [("T", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("binding", ["", "x := &Box[int]{}; ", "var x *Box[int]; "])
|
||||
def test_a_generic_receiver_keeps_its_base_type(tmp_path, binding):
|
||||
source = (
|
||||
"type Box[T any] struct{}\nfunc (*Box[T]) apply() {}\n"
|
||||
+ ("func Use(x *Box[int]) { x.apply() }\n" if not binding
|
||||
else "func Use() { " + binding + "x.apply() }\n")
|
||||
)
|
||||
assert _targets(tmp_path, source) == [("Box", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outer_call", [False, True])
|
||||
def test_a_block_binding_shadows_its_parameter_and_restores_it_afterward(tmp_path, outer_call):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func Use(x *A) { { x := &B{}; x.apply() }; "
|
||||
+ ("x.apply()" if outer_call else "") + " }\n"
|
||||
)
|
||||
expected = {("B", ".apply()", "INFERRED")}
|
||||
if outer_call:
|
||||
expected.add(("A", ".apply()", "INFERRED"))
|
||||
assert set(_targets(tmp_path, source)) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outer_call", [False, True])
|
||||
def test_an_unknown_block_binding_cannot_borrow_its_outer_type(tmp_path, outer_call):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func NewB() *B { return &B{} }\n"
|
||||
"func Use(x *A) { { x := NewB(); x.apply() }; "
|
||||
+ ("x.apply()" if outer_call else "") + " }\n"
|
||||
)
|
||||
expected: set[tuple[str | None, str, str]] = {(None, "NewB()", "EXTRACTED")}
|
||||
if outer_call:
|
||||
expected.add(("A", ".apply()", "INFERRED"))
|
||||
assert set(_targets(tmp_path, source)) == expected
|
||||
|
||||
|
||||
def test_a_range_binding_with_unknown_element_type_shadows_its_parameter(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func Use(x *A, xs []*B) { for _, x := range xs { x.apply() } }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("binding", ["var x *B", "var x = &B{}", "x := &B{}"])
|
||||
@pytest.mark.parametrize("before", [False, True])
|
||||
def test_a_local_binding_only_applies_after_its_declaration(tmp_path, binding, before):
|
||||
statements = "x.apply(); " + binding if before else binding + "; x.apply()"
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"var x *A\nfunc Use() { " + statements + " }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [
|
||||
("A" if before else "B", ".apply()", "INFERRED"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unknown", [False, True])
|
||||
@pytest.mark.parametrize("outer_call", [False, True])
|
||||
def test_an_if_initializer_binding_stays_inside_the_if(tmp_path, unknown, outer_call):
|
||||
binding = "NewB()" if unknown else "&B{}"
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func NewB() *B { return &B{} }\n"
|
||||
"func Use(x *A) { if x := " + binding + "; x != nil { x.apply() }; "
|
||||
+ ("x.apply()" if outer_call else "") + " }\n"
|
||||
)
|
||||
expected: set[tuple[str | None, str, str]] = {(None, "NewB()", "EXTRACTED")} if unknown else {
|
||||
("B", ".apply()", "INFERRED"),
|
||||
}
|
||||
if outer_call:
|
||||
expected.add(("A", ".apply()", "INFERRED"))
|
||||
assert set(_targets(tmp_path, source)) == expected
|
||||
|
||||
|
||||
def test_a_range_binding_does_not_escape_the_loop(tmp_path):
|
||||
source = (
|
||||
"type A struct{}\ntype B struct{}\n"
|
||||
"func (*A) apply() {}\nfunc (*B) apply() {}\n"
|
||||
"func Use(x *A, xs []*B) { for _, x := range xs { x.apply() }; x.apply() }\n"
|
||||
)
|
||||
assert _targets(tmp_path, source) == [("A", ".apply()", "INFERRED")]
|
||||
|
||||
|
||||
def test_a_bare_call_resolves_a_sibling_function_instead_of_a_local_method(tmp_path):
|
||||
source = "type B struct{}\nfunc (B) apply() {}\nfunc Use() { apply() }\n"
|
||||
assert _targets(tmp_path, source, siblings={"other.go": "func apply() {}\n"}) == [
|
||||
(None, "apply()", "INFERRED"),
|
||||
]
|
||||
Reference in new issue
Block a user