Skip to content

Commit 562dfd6

Browse files
Faisal-Fayazclaude
authored andcommitted
fix(extract): resolve Scala context bounds to references edges (#2046)
`def sort[A: Ordering]` desugars to an implicit `Ordering[A]`, so a context bound is a real dependency the function has on that typeclass -- and the idiomatic form is more common in modern Scala than the desugared `(implicit ...)` it compiles to. `context_bound` was not referenced anywhere in the extractor, so the dependency was invisible wherever it appeared. Two grammar shapes drive the implementation, both verified against tree-sitter-scala 0.26.0 before writing the fix: - `context_bound` is a direct child of `type_parameters`, one per bound, so the walk belongs in the existing per-function Scala block and needs no new handler. - A higher-kinded parameter nests a further `type_parameters` for its own arity brackets (`def program[F[_]: Async: Temporal]`), so the walk recurses rather than reading direct children only -- otherwise both bounds on `program` are missed. `upper_bound` (`[T <: Comparable[T]]`) is a distinct node type and is deliberately not matched: a subtype constraint is not a dependency, so an edge there would assert something the source does not say. Bounds also get their own `type_bound` context rather than reusing `parameter_type`, so a consumer can tell a typeclass constraint from a parameter annotation. One trap worth recording, because the neighbouring code invites it: `type_parameters` and `parameters` carry the *same* field name on `function_definition`, so `child_by_field_name("parameters")` returns whichever comes first. The bounds are therefore located by node type, never by field name -- a field lookup would read the function's real parameters as bounds. A regression test pins that `xs: List[A]` still resolves under `parameter_type` and never under `type_bound`. Verified: - uv run pytest tests/test_scala_context_bounds.py -q (10 passed) - 6 of the 10 new tests fail on the pre-fix tree - uv run pytest tests/ -q -> 28 failed, 6164 passed, 101 skipped; the 28 failures are byte-identical to the clean-tree baseline and none touch Scala - uv run ruff check . -> clean - uv run pyright -> 635 errors, identical to the clean-tree baseline Co-Authored-By: Claude <[email protected]> (cherry picked from commit e293b64)
1 parent cb973c0 commit 562dfd6

2 files changed

Lines changed: 191 additions & 0 deletions

File tree

‎graphify/extractors/engine.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,6 +1309,38 @@ def _scala_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple
13091309
if c.is_named:
13101310
_scala_collect_type_refs(c, source, generic, out)
13111311

1312+
1313+
def _scala_collect_context_bounds(
1314+
tp_node, source: bytes, out: list[tuple[str, str]]
1315+
) -> None:
1316+
"""Collect the types named by a ``type_parameters`` node's context bounds.
1317+
1318+
``def sort[A: Ordering]`` desugars to an implicit ``Ordering[A]``, so the
1319+
bound is a real dependency the function has on that typeclass -- but
1320+
``context_bound`` was not referenced anywhere in the extractor, so the
1321+
dependency was invisible wherever it appeared (#2046).
1322+
1323+
A ``context_bound`` is a direct child of ``type_parameters``, one per bound.
1324+
A higher-kinded parameter nests a further ``type_parameters`` for its own
1325+
arity brackets (``def program[F[_]: Async: Temporal]``), so this recurses
1326+
rather than reading direct children only -- otherwise both bounds on
1327+
``program`` are missed.
1328+
1329+
``upper_bound`` (``[T <: Comparable[T]]``) is a distinct node type and is
1330+
deliberately not matched here: a subtype constraint is not a dependency, so
1331+
emitting an edge for it would assert something the source does not say.
1332+
"""
1333+
if tp_node is None:
1334+
return
1335+
for c in tp_node.children:
1336+
if c.type == "type_parameters":
1337+
_scala_collect_context_bounds(c, source, out)
1338+
elif c.type == "context_bound":
1339+
bound_type = c.child_by_field_name("type")
1340+
if bound_type is not None:
1341+
_scala_collect_type_refs(bound_type, source, False, out)
1342+
1343+
13121344
def _python_collect_param_refs(params_node, source: bytes) -> list[tuple[str, str]]:
13131345
"""Collect type refs from each typed parameter under a `parameters` node."""
13141346
out: list[tuple[str, str]] = []
@@ -5941,6 +5973,26 @@ def scala_base_name(type_node) -> str | None:
59415973
if target_nid != func_nid:
59425974
add_edge(func_nid, target_nid, "references",
59435975
line, context=ctx)
5976+
# Context bounds (`def sort[A: Ordering]`) are the sugar for
5977+
# typeclass-parameter wiring and name a real dependency, so they
5978+
# get their own `type_bound` context rather than being folded
5979+
# into `parameter_type` (#2046). Found by node type, never by
5980+
# field name: `type_parameters` and `parameters` share the field
5981+
# name "parameters" on function_definition, so a field lookup
5982+
# here would return the type parameters and read the function's
5983+
# real parameters as if they were bounds.
5984+
for c in node.children:
5985+
if c.type != "type_parameters":
5986+
continue
5987+
bound_refs: list[tuple[str, str]] = []
5988+
_scala_collect_context_bounds(c, source, bound_refs)
5989+
for ref_name, role in bound_refs:
5990+
ctx = ("generic_arg" if role == "generic_arg"
5991+
else "type_bound")
5992+
target_nid = ensure_named_node(ref_name, line)
5993+
if target_nid != func_nid:
5994+
add_edge(func_nid, target_nid, "references",
5995+
line, context=ctx)
59445996

59455997
body = _find_body(node, config)
59465998
# JS/TS: capture callable members assigned directly in a function

‎tests/test_scala_context_bounds.py‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
"""Scala context bounds (`[A: Ordering]`) never produce a `references` edge.
2+
3+
Context bounds are the standard sugar for typeclass-parameter wiring in
4+
idiomatic Scala, and are more common in modern code than the desugared
5+
`(implicit ...)` form they compile to. The `context_bound` node type was not
6+
referenced anywhere in the extractor, so a type parameter's constraint was
7+
invisible no matter where in the file it appeared (#2046).
8+
9+
The grammar shapes this precisely, and two of them drive the fix:
10+
11+
- `context_bound` is a direct child of `type_parameters`, one per bound, sitting
12+
alongside the type parameter's own `identifier`.
13+
- For a higher-kinded parameter the nested arity brackets are a *nested*
14+
`type_parameters` (`F[_]`), so the walk has to recurse rather than take direct
15+
children only, or `[F[_]: Async: Temporal]` yields nothing.
16+
17+
Two deliberate non-emissions are pinned as well. An `upper_bound` (`[T <: C]`)
18+
is a separate node type and is a subtype constraint, not a dependency, so it
19+
must not emit an edge. And `type_parameters` and `parameters` share the *same*
20+
field name on `function_definition`, so the sibling walk must match on node type
21+
-- looking the node up by field name would return the type parameters and read
22+
the function's real parameters as if they were bounds.
23+
"""
24+
from pathlib import Path
25+
26+
from graphify.extract import extract_scala
27+
28+
SRC = '''\
29+
trait Ordering
30+
trait Async
31+
trait Temporal
32+
trait Comparable
33+
34+
def sort[A: Ordering](xs: List[A]): List[A] = xs
35+
36+
def program[F[_]: Async: Temporal](x: F[Int]): F[Int] = x
37+
38+
def plain[T](t: T): T = t
39+
40+
def bounded[T <: Comparable[T]](t: T): T = t
41+
42+
class Container {
43+
def member[K: Ordering](k: K): K = k
44+
}
45+
'''
46+
47+
48+
def _build(tmp_path):
49+
(tmp_path / "ContextBounds.scala").write_text(SRC)
50+
r = extract_scala(tmp_path / "ContextBounds.scala")
51+
nid = {n["label"]: n["id"] for n in r["nodes"]}
52+
return r, nid
53+
54+
55+
def _bound_targets(r, func_label, nid):
56+
"""References from `func_label` whose context is `type_bound`."""
57+
return {e["target"] for e in r["edges"]
58+
if e["relation"] == "references"
59+
and e["source"] == nid[func_label]
60+
and e.get("context") == "type_bound"}
61+
62+
63+
def test_single_context_bound_emits_reference(tmp_path):
64+
r, nid = _build(tmp_path)
65+
assert nid["Ordering"] in _bound_targets(r, "sort()", nid)
66+
67+
68+
def test_several_context_bounds_each_emit_a_reference(tmp_path):
69+
r, nid = _build(tmp_path)
70+
targets = _bound_targets(r, "program()", nid)
71+
assert nid["Async"] in targets
72+
assert nid["Temporal"] in targets
73+
74+
75+
def test_nested_type_parameters_do_not_hide_the_bounds(tmp_path):
76+
# `F[_]` nests a type_parameters inside type_parameters. A direct-children
77+
# walk would miss both bounds on `program` entirely.
78+
r, nid = _build(tmp_path)
79+
targets = _bound_targets(r, "program()", nid)
80+
assert len(targets) >= 2, targets
81+
82+
83+
def test_context_bound_uses_its_own_context_not_parameter_type(tmp_path):
84+
# A typeclass constraint is not a parameter type. Reusing `parameter_type`
85+
# would make the two indistinguishable to a consumer.
86+
r, nid = _build(tmp_path)
87+
edges = [e for e in r["edges"]
88+
if e["relation"] == "references" and e["source"] == nid["sort()"]]
89+
bound = [e for e in edges if e.get("context") == "type_bound"]
90+
assert bound, "expected a type_bound context"
91+
assert all(e.get("context") != "parameter_type" for e in bound)
92+
93+
94+
def test_unbounded_type_parameter_emits_no_bound_edge(tmp_path):
95+
r, nid = _build(tmp_path)
96+
assert not _bound_targets(r, "plain()", nid)
97+
98+
99+
def test_upper_bound_emits_no_bound_edge(tmp_path):
100+
# `[T <: Comparable[T]]` is an `upper_bound`, a distinct node type. It states
101+
# a subtype constraint, not a dependency, so it must not become an edge.
102+
r, nid = _build(tmp_path)
103+
assert not _bound_targets(r, "bounded()", nid)
104+
105+
106+
def test_context_bound_does_not_swallow_the_functions_own_parameters(tmp_path):
107+
# `type_parameters` and `parameters` share the field name "parameters" on
108+
# `function_definition`. A field-name lookup would pick the type parameters
109+
# and read `xs: List[A]` as a bound, so this pins that the real parameter
110+
# type still resolves under the `parameter_type` context.
111+
r, nid = _build(tmp_path)
112+
refs = {(e["target"], e.get("context")) for e in r["edges"]
113+
if e["relation"] == "references" and e["source"] == nid["sort()"]}
114+
assert (nid["List"], "parameter_type") in refs
115+
assert (nid["List"], "type_bound") not in refs
116+
117+
118+
def test_member_function_bound_is_attributed_to_the_member(tmp_path):
119+
# Class members carry a dotted label (`.member()`); top-level defs do not.
120+
r, nid = _build(tmp_path)
121+
assert nid["Ordering"] in _bound_targets(r, ".member()", nid)
122+
123+
124+
def test_bound_edge_is_tagged_extracted_with_a_location(tmp_path):
125+
r, nid = _build(tmp_path)
126+
edges = [e for e in r["edges"]
127+
if e["relation"] == "references"
128+
and e.get("context") == "type_bound"]
129+
assert edges
130+
for e in edges:
131+
assert e.get("confidence") == "EXTRACTED", e
132+
loc = e.get("source_location")
133+
assert isinstance(loc, str) and loc.startswith("L"), e
134+
135+
136+
def test_bound_never_points_at_the_function_itself(tmp_path):
137+
r, nid = _build(tmp_path)
138+
for label in ("sort()", "program()", ".member()"):
139+
assert nid[label] not in _bound_targets(r, label, nid)

0 commit comments

Comments
 (0)