Skip to content

fix(extract): resolve Scala context bounds to references edges (#2046) - #4038

Closed
Faisal-Fayaz wants to merge 3 commits into
Graphify-Labs:v8from
Faisal-Fayaz:fix/scala-context-bound-refs
Closed

Faisal-Fayaz wants to merge 3 commits into
Graphify-Labs:v8from
Faisal-Fayaz:fix/scala-context-bound-refs

Conversation

@Faisal-Fayaz

Copy link
Copy Markdown
Contributor

Stacked on #4036 and #4037. This branch is those two plus one commit. The
reviewable unit is the top commit (e293b64); the two below it are #4036 and
#4037 verbatim. This PR targets v8 only because GitHub cannot base a PR on a fork
branch. The net effect of the top commit alone is: add one helper function, and call
it from one place.

Problem

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 [A: Ordering] form is the idiomatic spelling, more common in modern Scala than the (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. I verified both against tree-sitter-scala 0.26.0 before writing the fix:

  • context_bound is a direct child of type_parameters, one per bound, sitting alongside the type parameter's own identifier. That means the walk belongs in the existing per-function Scala block and needs no new handler — exactly as the issue anticipated.

    type_parameters  fields=[(identifier, name), (':', bound), (context_bound, bound)]
      identifier     "A"
      context_bound  fields=[(type_identifier, type)]
        type_identifier  "Ordering"
    
  • A higher-kinded parameter nests a further type_parameters for its own arity brackets, so the walk must recurse rather than read direct children only — otherwise both bounds on def program[F[_]: Async: Temporal] are missed.

    type_parameters  fields=[(identifier, name), (type_parameters, type_parameters),
                             (':', bound), (context_bound, bound), (':', bound), (context_bound, bound)]
    

Implementation

A _scala_collect_context_bounds helper next to the existing _scala_collect_type_refs, called from the per-function Scala block. Bounds get their own type_bound context rather than reusing parameter_type, so a consumer can tell a typeclass constraint from a parameter annotation.

upper_bound ([T <: Comparable[T]]) is deliberately not matched. It is a distinct node type, and a subtype constraint is not a dependency — emitting an edge there would assert something the source does not say.

One trap worth flagging

type_parameters and parameters carry the same field name ("parameters") on function_definition:

function_definition fields=[(identifier, name), (type_parameters, parameters),
                            (parameters, parameters), (generic_type, return_type), ...]

So child_by_field_name("parameters") returns whichever comes first — the type parameters. The bounds are therefore located by node type, never by field name; a field lookup here would read the function's real parameters as if they were bounds. A regression test pins that xs: List[A] still resolves under parameter_type and never under type_bound.

Verification

uv run pytest tests/test_scala_context_bounds.py -q        # 10 passed
uv run pytest tests/ -q                                   # 28 failed, 6164 passed, 101 skipped
uv run ruff check .                                       # All checks passed!
uv run pyright                                            # 635 errors
  • 6 of the 10 new tests fail on the pre-fix tree (confirmed by stashing the engine.py change and re-running). The other 4 are deliberate negative/guard cases: unbounded type parameter, upper bound only, the field-name trap, and the self-edge guard.
  • The 28 failures are byte-identical to the clean-tree baseline (28 failed, 6136 passed), diffed test-id-by-test-id — missing tree-sitter grammars for erlang/R/solidity/vbnet plus ollama retry tests. None touch Scala.
  • pyright is at parity: 635 errors before and after.

Tests cover a single bound, several bounds, the nested F[_] case, the distinct type_bound context, the two negative cases (unbounded / upper bound), the field-name trap, a class member ([K: Ordering]), EXTRACTED tagging with a source location, and the self-edge guard.

Limitations

  • Only def/function_definition is handled, matching where the per-function Scala block already lives. A context bound on a class-level type parameter (class Foo[A: Ordering]) is still not walked; that is a separate dispatch and I left it out rather than widening this PR.
  • The emitted bound type goes through the same ensure_named_node resolution as every other reference, so an unbound typeclass resolves to a sourceless stub for the corpus rewire to collapse later — the normal path.

🤖 Generated with Claude Code

Faisal-Fayaz and others added 3 commits October 3, 2026 19:21
…-Labs#2054)

Scala 3 allows `val`/`var` to be written directly at file scope with no
enclosing object/class/trait. The `val_definition`/`var_definition`
type-reference dispatch was gated on `and parent_class_nid`, so a file-scope
binding produced no node and no edge of any kind, while the byte-identical
definition nested one level inside any container resolved correctly. The
missing container was the only difference: both positions parse to the same
node type carrying the same `type` field.

This is the Scala instance of a generic defect in the walker's default
recursion path that had already caused and been fixed once for Python
(Graphify-Labs#1050) -- a position that legitimately has no container must fall back to
the file node rather than be skipped. The fix reuses the `owner_nid =
parent_class_nid or file_nid` idiom already present in the property branch
above, and moves the self-reference guard onto the same anchor so a
file-scope binding cannot mint an edge from the file node to itself.

Behaviour is unchanged for class-nested bindings; a regression test pins
that case explicitly.

Verified:
- uv run pytest tests/test_scala_top_level_binding.py -q  (8 passed)
- 6 of the 8 new tests fail on the pre-fix tree, 2 pass either way
  (the in-class control, and the self-edge guard which is trivially empty
  before the fix and meaningful after it)
- uv run pytest tests/ -q -> 28 failed, 6144 passed, 101 skipped; the 28
  failures are byte-identical to the clean-tree baseline (missing
  tree-sitter grammars for erlang/R/solidity/vbnet, plus ollama retry
  tests) and none touch Scala
- uv run ruff check . -> clean
- uv run pyright -> 635 errors, identical to the clean-tree baseline
  (pre-existing debt; this change adds none)

Co-Authored-By: Claude <[email protected]>
…abs#2049)

A type alias (`type Alias = List[Int]`), an `opaque type`, and a `match type`
all declare a dependency on the types they name, but the type-reference
dispatch only fired for `val_definition`/`var_definition`, so these produced
zero `references` edges in any context -- in contrast to a `val`/`var`, whose
annotation is walked.

`match_type` needed a second, independent change: the type-reference walker's
recursion whitelist did not know `match_type`/`type_case_clause`, so even a
correctly dispatched call on a match type's right-hand side would have
resolved nothing. Both are now handled, recursing over named children exactly
as `compound_type` already is.

Verified field names against tree-sitter-scala 0.26.0 before writing the fix:
`type_definition` carries its RHS under the `type` field for all three forms
(`generic_type`, `type_identifier`, `match_type`), so the existing
`child_by_field_name("type")` walk applies verbatim and no new handler is
needed. File-scope aliases inherit the Graphify-Labs#2054 anchor fallback.

Scope: only the edges are added. The alias still gets no node of its own, which
is a separate already-accepted tradeoff shared with `val`/`given` bindings.

Verified:
- uv run pytest tests/test_scala_type_definition.py -q  (10 passed)
- 8 of the 10 new tests fail on the pre-fix tree
- uv run pytest tests/ -q -> 28 failed, 6154 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]>
…ify-Labs#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]>
@github-actions

github-actions Bot commented Oct 3, 2026

Copy link
Copy Markdown

Thanks for the pull request, @Faisal-Fayaz. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@Faisal-Fayaz
Faisal-Fayaz marked this pull request as ready for review October 3, 2026 15:03

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Looks safe to merge — no coupling regressions and no blocking issues, checked against the code graph (not a self-assessment).

Formal verification. PR-changed functions: 0/2 verified (0 proven, 0 may-equivalent, 0 distinguished) · 2 not verified (1 vacuous, 1 unsupported).

Not verified on this run: \_extract\_generic (unsupported), \_scala\_collect\_type\_refs (vacuous: never exercised).


Graphify review — findings

Adds Scala references edges for context bounds (def sort[A: Ordering]), tagged with a new type_bound context and found by recursing through nested type_parameters, so higher-kinded [F[_]: Async: Temporal] yields both bounds; upper_bound constraints deliberately emit nothing. File-scope val/var bindings now attribute their type references to the file node when there's no enclosing class, instead of being dropped. type_definition (aliases, opaque type, match type) gets the same treatment, with _scala_collect_type_refs now walking match_type case clauses. The alias itself still gets no node of its own.

No blocking issues surfaced. 6 lower-confidence candidates did not survive cross-model review.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 771 functions depend on the 291 functions this change touches.

Health — this change adds coupling hotspots:

  • new: _extract_generic() — 18 callers, 30 callees
  • new: extract_js() — 87 callers, 4 callees
  • new: extract_xaml() — 19 callers, 17 callees
  • new: extract_objc() — 27 callers, 9 callees
  • new: extract_julia() — 19 callers, 7 callees
  • new: extract_cpp() — 31 callers, 3 callees
  • new: extract_vue() — 10 callers, 7 callees
  • new: walk() — 1 callers, 68 callees
  • …and 9 more — each is listed as a finding

Verification — 771 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 706 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

28 of 321 test file(s) selected (9%) via static blast radius.

  • tests/test_astro_extraction.py — impact
  • tests/test_build.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_cpp_nested_and_cli.py — impact
  • tests/test_dotnet.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_php_closures.py — impact
  • tests/test_import_extension_resolution.py — impact
  • tests/test_indirect_call_block_scoped_shadow.py — impact
  • tests/test_indirect_dispatch.py — impact
  • tests/test_indirect_dispatch_assign_return.py — impact
  • tests/test_indirect_dispatch_getattr.py — impact
  • tests/test_js_exported_scalar_bindings.py — impact
  • tests/test_languages.py — impact
  • tests/test_multilang.py — impact
  • tests/test_python_underscore_resolution.py — impact
  • tests/test_rationale.py — impact
  • tests/test_ruby_resolution.py — impact
  • tests/test_scala_context_bounds.py — impact, changed-test
  • tests/test_scala_self_type.py — impact
  • tests/test_scala_top_level_binding.py — impact, changed-test
  • tests/test_scala_type_definition.py — impact, changed-test
  • tests/test_swift_computed_properties.py — impact
  • tests/test_swift_protocol_requirements.py — impact
  • tests/test_trailing_newline_not_a_syntax_error.py — impact
  • tests/test_ts_new_expression_calls.py — impact
  • tests/test_typescript_module_extensions.py — impact
  • tests/test_vue_extraction.py — impact

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Docs that may be stale (advisory)

…and 10 more.

Formal verification

Could not verify: Could not verify \_extract\_generic.

The verifier did not have enough to check \_extract\_generic, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: parameter `config` is annotated `LanguageConfig` — outside the synthesizable primitive/collection set

Could not verify: Could not verify \_scala\_collect\_type\_refs.

The verifier did not have enough to check \_scala\_collect\_type\_refs, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 200 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

· 17 more finding(s) on lines outside this diff (see the check run).

@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.75 (live on PyPI as graphifyy==0.9.75). Landed on v8 via an authorship-preserving cherry-pick, so your original commit authorship is kept. Thanks @Faisal-Fayaz for Scala context-bound references 🙏

Closing as shipped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants