Skip to content

Scala top-level (file-scope) val/var definitions lose all type references — the same parent_class_nid reset already fixed once for Python (#1050) #2054

Closed

Description

@sub4biz

Summary

Scala 3's headline "no boilerplate wrapper" feature — writing val/var/given/def directly at file
scope, with no enclosing object/class/trait — silently drops every type reference a top-level val/
var makes. Confirmed end-to-end with the real extractor, not just by reading the dispatch code: a top-level
val greeting: String = ... produces zero node and zero edge, while the exact same definition nested one
level inside any container resolves correctly. Functions are unaffected, since function parameter/return-type
references anchor to the function's own node id, not to an enclosing container. The root cause is a generic
mechanism in the walker's default recursion path — the same mechanism that already caused and was fixed once
for a Python-specific case.

The gap, demonstrated end-to-end with the real extractor

import cats.effect.{Async, IO}

def greet(name: String): String = s"Hello, $name"

val greeting: String = greet("World")

given Ordering[Int] = Ordering.Int

def program[F[_]: Async]: F[Unit] = Async[F].unit

Running this through the actual installed extractor (graphify.extractors.engine._extract_generic with
graphify.extract._SCALA_CONFIG, called directly — not reimplemented) produces:

NODE greet()
NODE String
NODE program()
NODE F
NODE Unit
EDGE <file> -[contains]-> greet()
EDGE greet() -[references]-> String   (parameter_type)
EDGE greet() -[references]-> String   (return_type)
EDGE <file> -[contains]-> program()
EDGE program() -[references]-> F      (return_type)
EDGE program() -[references]-> Unit   (generic_arg)

greet/program — both top-level functions — get complete, correct node and reference output. greeting
(the top-level val) and the top-level given produce no node and no edge of any kind — not even the
String reference greeting's type annotation makes shows up anywhere in the output.

Root cause: the same parent_class_nid reset already documented as a bug source once, for Python

The Scala-specific val/var reference-extraction branch requires parent_class_nid to be truthy:

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")
    ...

The main walker's final fallback, reached whenever a node type isn't handled by anything more specific,
explicitly clears this to None for every child:

# Default: recurse
for child in node.children:
    walk(child, parent_class_nid=None)

compilation_unit (the parse root) doesn't match any class/def-specific dispatch, so all of its direct
children — every top-level statement in the file — are walked through this exact fallback, with
parent_class_nid explicitly reset to None. Right above this fallback, the code already documents a prior,
related bug from the exact same mechanism, for a different language:

# Python's `@property` / `@staticmethod` / `@classmethod` wrap the
# inner function_definition in a `decorated_definition` node. The
# default recurse below clears parent_class_nid, which would cause the
# inner method to be emitted with a class-unqualified node id (e.g.
# `file_baz` instead of `file_bar_baz`). ... (#1050)

This is the same root mechanism causing the Scala top-level gap — Python's decorated_definition was given a
transparent pass-through case to avoid it; Scala's genuinely-top-level val/var never got the equivalent
treatment, because there's no enclosing container at all to pass through from.

A package header doesn't provide a container either — checked both forms, not assumed

package myapp

val greeting: String = "hi"
compilation_unit
  package_clause
  val_definition   <- still a direct sibling of package_clause, not nested inside it
package myapp {
  val greeting: String = "hi"
}
compilation_unit
  package_clause
    template_body
      val_definition   <- nested one level deeper, but package_clause has no dispatch of its own

package_clause never appears anywhere in the extractor (grepped the whole file — zero matches), so neither
form gives val_definition a container to inherit parent_class_nid from; both still resolve through the
same default-recurse fallback. Ran both through the real extractor: identical result, zero node/edge for the
val in either case.

Proposed diff

if (config.ts_module == "tree_sitter_scala"
        and t in ("val_definition", "var_definition")):
    owner_nid = parent_class_nid or file_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 != owner_nid:
                add_edge(owner_nid, target_nid, "references", line, context=ctx)

file_nid is already an in-scope closure variable at this point (file_nid = _make_id(str(path)), defined
immediately before def walk(...), in the same enclosing function) — no new state needs to be threaded
through. The original and parent_class_nid guard is dropped rather than widened to
and (parent_class_nid or file_nid): file_nid is unconditionally created once per file before walk
starts and was non-empty in every one of the real end-to-end runs above, so the condition would always be
true anyway — keeping it would just be dead weight.

Verified against a real parsed node (not just reasoned through) — running this exact simplified logic
against the top-level greeting: String above: owner_nid resolves to the file's own node id, and
refs = [('String', 'type')] — the reference that's currently silently dropped.

Regression-checked against the nested case, which must stay unchanged — running the same simplified
logic with a genuinely-present parent_class_nid (simulating val stack: ... inside class Holder):
owner_nid resolves to parent_class_nid exactly as today, file_nid never enters into it; no behavior
change for the already-working case.

Forward note on the type_definition fix in

graphify#2049

That fix reuses the identical and parent_class_nid guard. If that fix lands as originally written, a
top-level type alias (type AppF[A] = ..., written directly in a file with no wrapper — an idiomatic way to
name a monad-transformer stack in cats-effect code) would still be silently dropped, for the same reason
described here. Flagging this so both fixes can adopt the same parent_class_nid or file_nid pattern
consistently, rather than fixing one and leaving the other with the same blind spot.

What this deliberately does not propose

  • Any change to the general walk() fallback itself, or to any other language's handling — only Python's
    decorated_definition case is already special-cased there, and this proposal doesn't touch that. The root
    mechanism is generic engine machinery and could in principle affect other languages' equivalent top-level
    constructs, but that was not tested here and isn't claimed.
  • self_type is unaffected by this gap and needs no equivalent fix — a self-type annotation can only appear
    inside a template_body, which by construction always has an enclosing class/trait/object, so
    parent_class_nid is always already set by the time a self_type node is reached.
  • given_definition's own type-reference extraction remains a separate, pre-existing gap regardless of
    nesting (noted in graphify#2042 and
    graphify#2047) — not newly introduced or changed
    by this proposal.

Environment

  • graphifyy 0.9.20, tree_sitter_scala 0.26.0
  • All four fixtures (bare top-level, bare package, braced package, top-level type alias + val) were
    parsed with zero ERROR/is_missing nodes and additionally run through the real, installed
    graphify.extractors.engine._extract_generic end-to-end extractor (imported and called directly, not
    reimplemented) to confirm the actual current node/edge output, not just the dispatch code's apparent
    behavior. The proposed fix was verified against a real parsed node using the same real
    _scala_collect_type_refs.

Activity

  1. omsenjalia commented on Oct 18, 2026

    @omsenjalia
    Contributor

    This looks fixed on the v8 branch by commits cb973c03 (fix(extract): walk Scala type_definition right-hand sides (#2049)), 447d41dd (fix(extract): keep Scala file-scope val/var type references (#2054)). Could a maintainer confirm and close?

  2. sub4biz commented on Nov 15, 2026

    @sub4biz
    Author

    Retested on clean upstream v0.9.109: file-scope val and var type annotations emit references from the file node. The original examples with both plain and braced package headers emit the expected String reference too. The upstream regression suite passes. This addresses the reported type-reference gap; thanks for 447d41dd!

    All four original top-level fixtures compile under Scala 3 and their expected file-level type references pass on this clean tag; separate minimal cats typeclass/type stubs were supplied where needed.

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