fix(scala): scope extension methods to their receiver type (#2044)
extension_definition has no name of its own, so the walk fell through to the default recursion and every extension method became a file-level function with no edge to the type it extends. Handle it in _scala_extra_walk: take the receiver from the first non-using parameter clause (head of a generic, last segment of a qualified type; none for the extension's own type parameter) and walk each body member under it. The receiver id comes from ensure_named_node, so a same-file class keeps its one node and a type from another file gets the sourceless stub the corpus rewire collapses onto its definition, never a sourced duplicate (#1402). body is a repeated field, which is why this doesn't go through the class branch. The enum-case half of #2044 already landed in35207e9b. (cherry picked from commite07794aa00)
This commit is contained in:
1 parent
611ea9e2dd
commit
8dff9e380c
2 files changed
+205
-3
No files matched your search
@@ -4965,11 +4965,54 @@ def _swift_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: s
|
||||
return True
|
||||
return False
|
||||
|
||||
def _scala_extension_receiver_name(node, source: bytes) -> str | None:
|
||||
"""The type an `extension_definition` extends, or None if it names no type.
|
||||
|
||||
The receiver is the single parameter of the first non-`using` parameter
|
||||
clause: `extension (using c: Ctx)(x: Int)` extends `Int`, not `Ctx`. A
|
||||
generic (`List[A]`) or qualified (`pkg.Thing`) receiver binds to its type
|
||||
name. A receiver typed by the extension's own type parameter
|
||||
(`extension [T](t: T)`) extends every type, so there is no type to own it.
|
||||
"""
|
||||
clause = next(
|
||||
(c for c in node.children
|
||||
if c.type == "parameters" and not any(cc.type == "using" for cc in c.children)),
|
||||
None,
|
||||
)
|
||||
if clause is None:
|
||||
return None
|
||||
param = next((c for c in clause.children if c.type == "parameter"), None)
|
||||
if param is None:
|
||||
return None
|
||||
type_node = next(
|
||||
(c for c in param.children
|
||||
if c.type in ("type_identifier", "generic_type", "stable_type_identifier")),
|
||||
None,
|
||||
)
|
||||
if type_node is not None and type_node.type == "generic_type":
|
||||
type_node = next(
|
||||
(c for c in type_node.children
|
||||
if c.type in ("type_identifier", "stable_type_identifier")),
|
||||
None,
|
||||
)
|
||||
if type_node is not None and type_node.type == "stable_type_identifier":
|
||||
type_node = next(
|
||||
(c for c in reversed(type_node.children) if c.type == "type_identifier"),
|
||||
None,
|
||||
)
|
||||
if type_node is None:
|
||||
return None
|
||||
name = _read_text(type_node, source).strip()
|
||||
if not name or name in _scala_type_parameters_in_scope(node, source):
|
||||
return None
|
||||
return name
|
||||
|
||||
def _scala_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: str,
|
||||
nodes: list, edges: list, seen_ids: set, function_bodies: list,
|
||||
parent_class_nid: str | None, add_node_fn, add_edge_fn,
|
||||
walk_fn) -> bool:
|
||||
"""Emit a node per Scala 3 enum case with a case_of edge. Returns True if handled.
|
||||
walk_fn, ensure_named_node_fn) -> bool:
|
||||
"""Emit a node per Scala 3 enum case with a case_of edge, and scope extension
|
||||
methods to their receiver type. Returns True if handled.
|
||||
|
||||
tree-sitter-scala wraps the members of an `enum` in `enum_case_definitions`,
|
||||
whose children are `simple_enum_case` (`case Red`) or `full_enum_case`
|
||||
@@ -5003,6 +5046,23 @@ def _scala_extra_walk(node, source: bytes, file_nid: str, stem: str, str_path: s
|
||||
add_node_fn(case_nid, case_name, line)
|
||||
add_edge_fn(parent_class_nid, case_nid, "case_of", line)
|
||||
return True
|
||||
if node.type == "extension_definition":
|
||||
# `extension (p: Point) def flip` adds `flip` to `Point`. The node has no
|
||||
# name of its own, so without this its methods fell through to file
|
||||
# scope with no edge to the type they extend (#2044). The receiver is
|
||||
# resolved like a type reference: a `Point` declared in this file keeps
|
||||
# its one node, and any other type gets the sourceless stub the corpus
|
||||
# rewire collapses onto its real definition, never a sourced copy that
|
||||
# would duplicate it (#1402).
|
||||
receiver = _scala_extension_receiver_name(node, source)
|
||||
if receiver is None:
|
||||
return False
|
||||
receiver_nid = ensure_named_node_fn(receiver, node.start_point[0] + 1)
|
||||
# `body` is a repeated field (each `def`, plus the braces of a braced
|
||||
# body), so child_by_field_name would return only the first member.
|
||||
for member in node.children_by_field_name("body"):
|
||||
walk_fn(member, parent_class_nid=receiver_nid)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _cpp_declarator_type_name(declarator, source: bytes) -> str | None:
|
||||
@@ -8687,7 +8747,8 @@ def _extract_generic(
|
||||
if config.ts_module == "tree_sitter_scala":
|
||||
if _scala_extra_walk(node, source, file_nid, stem, str_path,
|
||||
nodes, edges, seen_ids, function_bodies,
|
||||
parent_class_nid, add_node, add_edge, walk):
|
||||
parent_class_nid, add_node, add_edge, walk,
|
||||
ensure_named_node):
|
||||
return
|
||||
|
||||
# C++ enumerators (`Red`, `Green = 2`) inside an enum / enum class body.
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Scala 3 `extension` methods are members of the receiver type, not file scope (#2044).
|
||||
|
||||
`extension (p: Point) def flip` adds `flip` to `Point`, but tree-sitter-scala has
|
||||
no name on `extension_definition` (the receiver sits inside its `parameters`), so
|
||||
the walk fell through to the default recursion and every extension method became
|
||||
a file-level function with no edge to the type it extends. The receiver's type
|
||||
now owns them, the same way a Swift `extension Point` reuses `Point`'s node.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.extract import extract, extract_scala
|
||||
|
||||
SRC = (
|
||||
"class Point(val x: Int):\n"
|
||||
" def norm: Int = x\n"
|
||||
"\n"
|
||||
"extension (p: Point)\n"
|
||||
" def flip(): Point = p\n"
|
||||
" def twice: Int = flip().norm * 2\n"
|
||||
"\n"
|
||||
"extension (x: Int)\n"
|
||||
" def double: Int = x * 2\n"
|
||||
"\n"
|
||||
"extension [A](xs: List[A])\n"
|
||||
" def second: A = xs(1)\n"
|
||||
"\n"
|
||||
"extension (using ctx: Ctx)(s: String)\n"
|
||||
" def shout: String = s\n"
|
||||
"\n"
|
||||
"extension (t: pkg.Thing) {\n"
|
||||
" def first: Int = 1\n"
|
||||
" def last: Int = 2\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"extension [T](t: T)\n"
|
||||
" def self2: T = t\n"
|
||||
)
|
||||
|
||||
|
||||
def _graph(tmp_path):
|
||||
f = tmp_path / "ext.scala"
|
||||
f.write_text(SRC, encoding="utf-8")
|
||||
r = extract_scala(f)
|
||||
label = {n["id"]: str(n.get("label", "")) for n in r["nodes"]}
|
||||
return r, label
|
||||
|
||||
|
||||
def _method(r, label, owner, method):
|
||||
return any(
|
||||
e.get("relation") == "method"
|
||||
and label.get(e.get("source")) == owner
|
||||
and label.get(e.get("target")) == method
|
||||
for e in r["edges"]
|
||||
)
|
||||
|
||||
|
||||
def _file_contains(r, label, member):
|
||||
file_nid = next(n["id"] for n in r["nodes"] if n.get("label") == "ext.scala")
|
||||
return any(
|
||||
e.get("relation") == "contains" and e.get("source") == file_nid
|
||||
and label.get(e.get("target")) == member
|
||||
for e in r["edges"]
|
||||
)
|
||||
|
||||
|
||||
def test_extension_on_local_class_attaches_to_that_class(tmp_path):
|
||||
r, label = _graph(tmp_path)
|
||||
assert _method(r, label, "Point", ".flip()")
|
||||
assert _method(r, label, "Point", ".twice()")
|
||||
assert not _file_contains(r, label, "flip()"), "extension method leaked to file scope"
|
||||
points = [n for n in r["nodes"] if n.get("label") == "Point"]
|
||||
assert len(points) == 1, f"extension must reuse the class node, got {points}"
|
||||
assert _method(r, label, "Point", ".norm()"), "class lost its own method"
|
||||
|
||||
|
||||
def test_extension_on_external_and_generic_types(tmp_path):
|
||||
r, label = _graph(tmp_path)
|
||||
assert _method(r, label, "Int", ".double()")
|
||||
# a generic receiver binds to its head type, not the type argument
|
||||
assert _method(r, label, "List", ".second()")
|
||||
|
||||
|
||||
def test_using_clause_is_not_the_receiver(tmp_path):
|
||||
r, label = _graph(tmp_path)
|
||||
assert _method(r, label, "String", ".shout()")
|
||||
assert not any(n.get("label") == "Ctx" and _method(r, label, "Ctx", ".shout()") for n in r["nodes"])
|
||||
|
||||
|
||||
def test_qualified_receiver_and_braced_body(tmp_path):
|
||||
r, label = _graph(tmp_path)
|
||||
assert _method(r, label, "Thing", ".first()")
|
||||
assert _method(r, label, "Thing", ".last()")
|
||||
|
||||
|
||||
def test_type_parameter_receiver_is_not_invented_as_a_type(tmp_path):
|
||||
r, label = _graph(tmp_path)
|
||||
# `extension [T](t: T)` extends every type; there is no `T` declaration to
|
||||
# own the method, so it stays at file scope rather than on a fabricated node.
|
||||
assert not any(n.get("label") == "T" for n in r["nodes"])
|
||||
assert _file_contains(r, label, "self2()")
|
||||
|
||||
|
||||
def test_call_between_extension_methods_resolves(tmp_path):
|
||||
r, label = _graph(tmp_path)
|
||||
calls = {
|
||||
(label.get(e["source"]), label.get(e["target"]))
|
||||
for e in r["edges"] if e.get("relation") == "calls"
|
||||
}
|
||||
assert (".twice()", ".flip()") in calls
|
||||
|
||||
|
||||
def test_extension_is_deterministic(tmp_path):
|
||||
a, _ = _graph(tmp_path)
|
||||
b, _ = _graph(tmp_path)
|
||||
key = lambda r: (sorted(n["id"] for n in r["nodes"]),
|
||||
sorted((e["source"], e["relation"], e["target"]) for e in r["edges"]))
|
||||
assert key(a) == key(b)
|
||||
|
||||
|
||||
def test_extension_in_another_file_attaches_to_the_real_class(tmp_path):
|
||||
# A sourced per-file `Point` copy would be a phantom duplicate of the real
|
||||
# class (#1402); the receiver must be the sourceless stub the corpus rewire
|
||||
# collapses onto `geo/Point.scala`'s node.
|
||||
(tmp_path / "geo").mkdir()
|
||||
point = tmp_path / "geo" / "Point.scala"
|
||||
point.write_text("class Point(val x: Int):\n def norm: Int = x\n", encoding="utf-8")
|
||||
ops = tmp_path / "geo" / "PointOps.scala"
|
||||
ops.write_text("extension (p: Point)\n def flip(): Point = p\n", encoding="utf-8")
|
||||
fwd = tmp_path / "Fwd.scala"
|
||||
fwd.write_text("extension (v: Vec)\n def len(): Int = 1\n\nclass Vec:\n def dim: Int = 2\n",
|
||||
encoding="utf-8")
|
||||
r = extract([point, ops, fwd], cache_root=tmp_path, parallel=False)
|
||||
by_id = {n["id"]: n for n in r["nodes"]}
|
||||
owners = {
|
||||
by_id[e["target"]]["label"]: by_id[e["source"]]
|
||||
for e in r["edges"] if e.get("relation") == "method"
|
||||
}
|
||||
assert owners[".flip()"]["source_file"].endswith("Point.scala")
|
||||
assert owners[".flip()"]["id"] == owners[".norm()"]["id"]
|
||||
assert owners[".len()"]["id"] == owners[".dim()"]["id"], "forward-declared receiver split in two"
|
||||
assert sum(1 for n in r["nodes"] if n.get("label") == "Point") == 1
|
||||
Reference in new issue
Block a user