Skip to content

Scala type_definition right-hand sides are never scanned for type references — a one-line dispatch fix covers type aliases and opaque type, match type needs one more small addition #2049

Closed

Description

@sub4biz

Summary

type_definition (plain type aliases, opaque type, match type) never has its right-hand side walked for
type references at all, in any context — not just "no node for the alias itself" (an already-accepted,
narrower tradeoff shared with val/given bindings), but zero references edges of any kind, in contrast to
val_definition/var_definition, which do get their type annotation walked when inside a class. The fix for
plain aliases and opaque type is a one-line dispatch widening that reuses the existing val/var code
path verbatim. match type needs one more, independent addition on top: the type-reference walker's own
recursion whitelist doesn't know about match_type/type_case_clause nodes, so even a correctly-dispatched
call on a match type's right-hand side would still resolve nothing.

The asymmetry with val/var

trait Repo:
  type Elem[X] = X match
    case String => Char
    case Array[t] => t

  opaque type Id = Long

  type Alias = List[Int]
trait_definition
  identifier "Repo"
  template_body
    type_definition            <- Elem: ['type','type_identifier','type_parameters','=','match_type']
    type_definition            <- Id:   ['opaque_modifier','type','type_identifier','=','type_identifier']
    type_definition            <- Alias:['type','type_identifier','=','generic_type']

All three sit at the exact same sibling level inside template_body that a val_definition would occupy.
The existing Scala-specific dispatch only fires for the latter:

if (config.ts_module == "tree_sitter_scala"
        and t in ("val_definition", "var_definition")
        and parent_class_nid):
    type_node = node.child_by_field_name("type")
    if type_node is not None:
        line = node.start_point[0] + 1
        refs: list[tuple[str, str]] = []
        _scala_collect_type_refs(type_node, source, False, refs)
        for ref_name, role in refs:
            ctx = "generic_arg" if role == "generic_arg" else "field"
            target_nid = ensure_named_node(ref_name, line)
            if target_nid != parent_class_nid:
                add_edge(parent_class_nid, target_nid, "references", line, context=ctx)

type_definition is not in the t in (...) check, so type Alias = List[Int] loses the List/Int
references completely — a val x: List[Int] = ... in the same position would keep them.

The fix is a one-line widening, not a new code path — type_definition already has a "type" field

The grammar assigns field names to type_definition's children exactly the way it does for val_definition
— including a "type" field for the right-hand side, the same field name the existing val/var code above
already reads with node.child_by_field_name("type"). Enumerating the actual field assigned to each child,
for both RHS-bearing definitions and RHS-less abstract type members (type Foo, type Bar <: Serializable,
type Baz >: Nothing <: AnyRef — deferred type members with no = at all, legal and common in traits):

trait Repo:
  type Foo
  type Bar <: Serializable
  type Baz >: Nothing <: AnyRef
Elem: 'type_identifier' <- field "name", 'type_parameters' <- field "type_parameters", 'match_type' <- field "type"
Id:   'type_identifier' <- field "name", 'type_identifier' (RHS) <- field "type"
Alias:'type_identifier' <- field "name", 'generic_type' <- field "type"
Foo:  'type_identifier' <- field "name"                      (no "type" field at all)
Bar:  'type_identifier' <- field "name", 'upper_bound' <- field "bound"   (not "type")
Baz:  'type_identifier' <- field "name", 'lower_bound'/'upper_bound' <- field "bound"

Calling child_by_field_name("type") directly on all six confirms this without any special-casing:

Elem -> match_type      Foo -> None
Id   -> type_identifier  Bar -> None
Alias -> generic_type    Baz -> None

The three abstract members correctly return None — their RHS-equivalent (the bound) lives under field
"bound", not "type", so the exact same one-line call already used for val/var needs no additional
logic to skip them safely. No manual token-scanning or positional-child heuristic is needed for this part —
reusing node.child_by_field_name("type") verbatim, just with "type_definition" added to the t in (...)
check, is the complete fix for aliases and opaque type.

Confirming the walker handles the RHS shapes it now reaches

Elem  (rhs type: match_type)      -> refs = []
Id    (rhs type: type_identifier) -> refs = [('Long', 'type')]
Alias (rhs type: generic_type)    -> refs = [('List', 'type'), ('Int', 'generic_arg')]

Id and Alias resolve correctly the moment _scala_collect_type_refs is called on them — for these two,
the one-line dispatch widening above is the complete fix. Elem (the match type) comes back empty even
when the walker is called on it directly, which rules out the dispatch fix alone as complete for match
types.

The second, independent bug: match_type/type_case_clause aren't in the walker's recursion whitelist

def _scala_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[str, str]]) -> None:
    ...
    if t in ("compound_type", "infix_type", "function_type", "tuple_type",
             "annotated_type", "projected_type"):
        for c in node.children:
            if c.is_named:
                _scala_collect_type_refs(c, source, generic, out)

match_type and type_case_clause are absent from this whitelist, so even a correctly-dispatched call on a
match type's right-hand side recurses into nothing and returns an empty list — confirmed above (Elem
returns []). This is independent of the dispatch fix: widening only the t in (...) check would make
Alias/Id resolve but Elem would still silently produce zero references.

Proposed diff — both layers together

# 1. dispatch: one-line widening, reuses the existing val/var code path verbatim —
#    child_by_field_name("type") already resolves correctly for type_definition,
#    including returning None for RHS-less abstract type members.
if (config.ts_module == "tree_sitter_scala"
        and t in ("val_definition", "var_definition", "type_definition")
        and parent_class_nid):
    type_node = node.child_by_field_name("type")
    ...  # unchanged from here — same ensure_named_node/add_edge calls already in place

# 2. walker: teach _scala_collect_type_refs about match_type/type_case_clause
if t in ("match_type", "type_case_clause"):
    for c in node.children:
        if c.is_named:
            _scala_collect_type_refs(c, source, generic, out)

Verified against a real parsed tree, running both patches together (not just reasoned through) — all six
type_definitions from the two shapes above (three with a RHS, three abstract members with none), walked
with the widened dispatch and patched walker:

Elem  -> [('X', 'type'), ('String', 'type'), ('Char', 'type'), ('Array', 'type'), ('t', 'generic_arg'), ('t', 'type')]
Id    -> [('Long', 'type')]
Alias -> [('List', 'type'), ('Int', 'generic_arg')]
Foo   -> []   (abstract member, no "type" field — correctly produces no references, not an error)
Bar   -> []   (abstract member with only a "bound" field — also correctly out of scope here)
Baz   -> []   (abstract member with two "bound" fields — same)

All three RHS-bearing definitions now resolve, and all three RHS-less abstract members correctly stay empty
instead of producing garbage. X/t (the match type's own type-parameter/binder names, not external types)
are also picked up — the same kind of reference a generic type parameter used anywhere else in this extractor
already produces (resolves through ensure_named_node's bare-stub fallback), not a new class of noise
introduced by this fix.

What this deliberately does not propose

  • Making type_definition a node/container of its own — that's the already-covered, separate val/given
    value-binding-invisibility tradeoff. This proposal is scoped to reference-edge extraction only: the binding
    itself stays invisible, exactly like val, but the type references it makes are no longer silently
    dropped.
  • Any change to class_types (trait/enum container support) — independent of this finding.
  • Extracting anything from abstract type members' bounds (type Bar <: Serializable) — their reference
    (Serializable) lives under a different field ("bound", not "type") and is out of scope here; flagged
    as a possible narrow follow-up, not folded into this proposal to keep the diff minimal and precedent-driven.

Environment

  • graphifyy 0.9.20, tree_sitter_scala 0.26.0
  • All six type_definition shapes (three RHS-bearing, three abstract/RHS-less) were dumped directly against
    the installed grammar (tree_sitter.Parser + tree_sitter_scala.language()), checked for absence of
    ERROR/is_missing nodes. Field assignments were read via the grammar's own field_name_for_id/
    field_name_for_child introspection, not guessed from node shape. The current-behavior and
    patched-behavior traces above were both produced by running the installed _scala_collect_type_refs
    (imported from the installed package) and a manually-patched copy against the same real parsed nodes, not
    inferred from reading the source.

Activity

  1. omsenjalia commented on Oct 18, 2026

    @omsenjalia
    Contributor

    This looks fixed on the v8 branch by cb973c03 (fix(extract): walk Scala type_definition right-hand sides (#2049)). Could a maintainer confirm and close?

  2. sub4biz commented on Nov 15, 2026

    @sub4biz
    Author

    Retested the original type-definition examples on clean upstream v0.9.109. The type alias, opaque type and match-type cases emit the expected references, while abstract type declarations without RHS do not invent RHS references. The focused upstream regression suite also passes. This covers the reported cases; thank you for cb973c03!

    The two original type-definition fixtures also compile under Scala 3 and their expected references pass on this clean tag.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions