Skip to content

Scala structural extraction misses trait/given/extension/enum containers AND all abstract method declarations (function_declaration) — 5 of 8 relevant node types missing from _SCALA_CONFIG #2042

Open

Description

@sub4biz

Summary

_SCALA_CONFIG in extract.py defines which tree-sitter node types count as a "class" or a "function"
boundary for Scala. It only lists:

class_types=frozenset({"class_definition", "object_definition"})
function_types=frozenset({"function_definition"})
function_boundary_types=frozenset({"function_definition"})

The installed tree_sitter_scala grammar (0.26.0) parses trait, given, extension, and enum as their
own distinct top-level node types (trait_definition, given_definition, extension_definition,
enum_definition), and splits methods into function_definition (has a body) vs. function_declaration
(signature only — abstract methods, trait members without a default implementation). None of the four
container types, and neither function_declaration, appear anywhere in _SCALA_CONFIG. Confirmed by
dumping the grammar's own parse tree directly (see Reproduction) — this is not read off tags.scm/
highlights.scm alone.

Since walk()'s class-node branch, contains/method edge creation, and parent_class_nid propagation to
children all gate on t in config.class_types / t in config.function_types, none of these five node
shapes are recognized:

  • A trait_definition, given_definition, extension_definition, or enum_definition node falls into the
    generic "default: recurse" branch (engine.py:3569-3571), which explicitly resets
    parent_class_nid=None
    before recursing into children. Their members are walked as if they were bare
    top-level code.
  • A function_declaration (abstract method, no = body) never matches function_types/
    function_boundary_types at all, in any container — including inside an ordinarily well-handled
    class/object/trait — so it produces no node under any circumstance.

trait is Scala's primary unit of interface/typeclass abstraction, and given/extension are the idiomatic
Scala 3 replacement for implicit. Any codebase built around typeclass-style design (the dominant pattern in
the cats/cats-effect ecosystem — Functor[F[_]], Concurrent[F], MonadError, custom domain typeclasses,
given instances providing them) has its central abstraction layer almost entirely absent from the
structural graph. There is no LLM/semantic fallback for code files, so none of this is backfilled.

Root cause

extract.py (_SCALA_CONFIG; logic lives in graphify/extractors/engine.py):

_SCALA_CONFIG = LanguageConfig(
    ts_module="tree_sitter_scala",
    class_types=frozenset({"class_definition", "object_definition"}),
    function_types=frozenset({"function_definition"}),
    import_types=frozenset({"import_declaration"}),
    call_types=frozenset({"call_expression"}),
    call_function_field="",
    call_accessor_node_types=frozenset({"field_expression"}),
    call_accessor_field="field",
    name_fallback_child_types=("identifier",),
    body_fallback_child_types=("template_body",),
    function_boundary_types=frozenset({"function_definition"}),
    import_handler=_import_scala,
)

engine.py's class-node branch (~2356):

if t in config.class_types:
    ...
    class_nid = _make_id(stem, ".".join(namespace_stack), class_name)
    add_node(class_nid, class_name, line, metadata=metadata)
    add_edge(file_nid, class_nid, "contains", line)
    ...  # children walked with parent_class_nid = class_nid

engine.py's default fallback (~3569-3571):

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

trait_definition/given_definition/extension_definition/enum_definition never enter the class branch,
so they fall all the way to this default, which strips parent_class_nid for everything beneath them.

For comparison, other languages in the same file give function boundaries multiple node types — e.g. the
JS/TS config lists function_declaration, generator_function_declaration, arrow_function, and
method_definition in function_boundary_types. Scala's config lists exactly one. This is a
narrower-than-usual config for one language, not a structural limitation of the extraction engine.

Additional findings

Found while building an adversarial Scala 2/3 + cats-effect conformance corpus (--no-cluster, pure
structural extraction, no LLM):

  • val/implicit val never produces its own node, only its type annotation surfaces as a references
    edge from the enclosing container. Given how much cats-effect typeclass wiring lives in implicit val/
    given value bindings, this silently drops a real class of typeclass-instance nodes. Same root cause
    extends to Scala 3 opaque type companion values and top-level val. given bindings are strictly
    more invisible than implicit val, not just differently invisible
    :

    trait Codec[A]
    
    object Codecs {
      implicit val intCodec: Codec[Int] = new Codec[Int] {}
      given stringCodec: Codec[String] = new Codec[String] {}
    }

    Codecs gets exactly two references edges — to Codec and to Int, both from intCodec's type
    annotation. stringCodec (identical shape, given instead of implicit val) produces zero trace: no
    node for it, no references edge to Codec or String, nothing distinguishing it from code that was
    never written. implicit def (function-shaped, not a value binding) is unaffected — the gap is specific to
    value bindings (val/given), not to the implicit/given keywords in general.

  • A trait and a same-named companion object collide onto one node id:

    trait Greeter {
      def greet: String
    }
    object Greeter {
      def default: Greeter = new Greeter { def greet = "hi" }
    }

    Produces exactly one node labeled Greeter, with a method edge to .default() — the object's own
    method. The trait's own method (greet, a function_declaration) has no node at all, and there is nothing
    in the graph distinguishing that Greeter was ever a trait — _make_id(stem, namespace, className) doesn't
    disambiguate by node kind, so trait Foo + object Foo (the single most common Scala typeclass/service
    idiom) silently lose the trait's identity to the object's. Today this only shows up as silent absence
    (only the object gets a node) because trait_definition never reaches the class branch at all — but simply
    adding trait_definition to class_types without also making _make_id node-kind-aware turns this into an
    actual id collision between two independently real definitions (see Suggested fix below).

  • export clauses are completely invisible:

    object Impl {
      def coreLogic(): Int = 1
      val version: String = "1.0"
    }
    object Facade {
      export Impl.{coreLogic, version}
    }

    Facade gets its own node (correctly, as an object_definition) but zero edges of any kind connecting it
    to coreLogic/version — nothing in the graph indicates Facade re-exposes Impl's members.

  • derives clauses are completely invisible:

    trait Eq[A] {
      def eqv(a: A, b: A): Boolean
    }
    object Eq {
      def derived[A]: Eq[A] = (a, b) => a == b
    }
    
    case class Coord(x: Int, y: Int) derives Eq

    Coord produces a references edge only to Int (from its constructor parameters) — no edge to Eq at
    all, despite the explicit derives Eq clause.

    Both export and derives have concrete suggested fixes (derives reuses the existing extends_clause
    handling block almost verbatim), planned as a separate follow-up issue since they turned out to need more
    than a one-line mention here.

  • Only the first parameter list of a curried/multi-parameter-list method has its types tracked; every
    subsequent parameter list is silently ignored, regardless of implicit/using status.
    Root-caused to an
    exact line in engine.py (~3435-3455, the Scala-specific parameter-reference branch):

    if config.ts_module == "tree_sitter_scala":
        params_node = None
        for c in node.children:
            if c.type == "parameters":
                params_node = c
                break          # <-- stops at the first "parameters" sibling

    A curried method's AST has one parameters node per parameter list as siblings under the function
    definition; this loop takes the first and breaks, so a second, third, etc. parameter list — explicit or
    implicit/using — never gets walked for type references at all:

    class SecondMarker
    
    class Curried {
      def twoListsSecondExplicit(x: Int)(m: SecondMarker): Int = x
    }

    SecondMarker gets its own node (from its own top-level class declaration, independent of whether anything
    references it) — but twoListsSecondExplicit produces exactly one references edge, to Int (from the
    first parameter list / return type), and none to SecondMarker, even though SecondMarker is a real
    class in the same file the method could have referenced. Confirmed positional, not keyword-specific — a
    bare using clause in the second list loses its type the same way:

    trait Codec[A]
    
    class Migration {
      def encodeString(x: String)(using c: Codec[String]): String = x
    }

    encodeString produces a references edge only to String (from the first list), never to Codec.
    Suggested fix: collect all parameters-typed children instead of breaking after the first —
    params_nodes = [c for c in node.children if c.type == "parameters"], then iterate all of them.

  • Context bounds are never walked for type references at all, independent of the parameter-list bug
    above:

    trait Ordering[A]
    
    def sort[A: Ordering](xs: List[A]): List[A] = xs

    sort produces references edges to List and A (from the parameter type), but none to Ordering
    — the context bound's constraint type is invisible. They compile to a context_bound node nested inside
    type_parameters, never as a parameters sibling — grep -n "context_bound" engine.py returns zero
    matches, the node type is never referenced anywhere in the extraction code. Since context bounds are the
    standard sugar for typeclass-parameter wiring in idiomatic Scala (arguably more common than the desugared
    (implicit ...) form in modern code), this independently affects the same practical outcome (typeclass
    wiring invisible) via an unrelated code path. Has its own concrete diff (including a confirmed-real
    higher-kinded-nesting edge case a naive scan would miss), planned as a separate follow-up issue.

Reproduction (graphifyy 0.9.20 / tree_sitter_scala 0.26.0)

Test file:

trait Foo:
  def bar: Int

given fooInstance: Foo with
  def bar = 1

class Baz extends Foo:
  def bar = 2

enum Color:
  case Red, Green, Blue

extension (x: Int)
  def double: Int = x * 2

Parse tree (dumped directly via tree_sitter_scala.language() + tree_sitter.Parser, confirming the
grammar already exposes the right shapes):

compilation_unit
  trait_definition
    identifier "Foo"
    template_body: function_declaration        <- no body: bar's signature
  given_definition
    identifier "fooInstance"
    with_template_body: function_definition    <- has body: bar = 1
  class_definition
    identifier "Baz"
    extends_clause -> type_identifier "Foo"
    template_body: function_definition         <- has body: bar = 2
  enum_definition
    identifier "Color"
    enum_body: enum_case_definitions           <- Red, Green, Blue
  extension_definition
    parameters
    function_definition                        <- double

graphify update . --no-cluster output (graph.json), annotated:

{
  "nodes": [
    {"id": "foo",       "label": "Foo", "source_file": "", "source_location": ""},
    {"id": "foo_bar",   "label": "bar()",  "source_file": "Foo.scala", "source_location": "L5"},
    {"id": "foo_baz",   "label": "Baz",    "source_file": "Foo.scala", "source_location": "L7"},
    {"id": "foo_baz_bar","label": ".bar()","source_file": "Foo.scala", "source_location": "L8"},
    {"id": "foo_double","label": "double()","source_file": "Foo.scala","source_location": "L14"},
    {"id": "int",       "label": "Int", "source_file": "", "source_location": ""}
  ],
  "links": [
    {"source": "foo", "target": "foo_bar",    "relation": "contains"},
    {"source": "foo", "target": "foo_baz",    "relation": "contains"},
    {"source": "foo_baz", "target": "foo",    "relation": "inherits"},
    {"source": "foo_baz", "target": "foo_baz_bar", "relation": "method"},
    {"source": "foo", "target": "foo_double", "relation": "contains"},
    {"source": "foo_double", "target": "int", "relation": "references"}
  ]
}

"foo" here is the file node (id derived from Foo.scala's stem, not a trait container — confirmed by
its empty source_file/source_location). Concretely, against the source:

  1. trait Foo's own container is never created. No node represents the trait itself as a class-like
    entity; it appears only as the bare inherits target of Baz.
  2. trait Foo's abstract method bar: Int (line 2, function_declaration) produces no node at all —
    confirms the function_declaration gap independently of the trait issue.
  3. given fooInstance's method bar = 1 (line 5, function_definition) leaks to file scope — appears
    as foo_bar, attributed via contains from the file node, not from any given-related container.
    No node represents the given instance itself.
  4. class Baz (correctly recognized, unaffected) shows the expected shape: own node, own method edge
    to foo_baz_bar, correct inherits edge to Foo.
  5. enum Color's cases (Red, Green, Blue) vanish completely — zero nodes, zero edges, no trace at
    all.
    Scala has no enum-case handler at all (unlike Swift/Java/Kotlin, which each have a dedicated
    extra-walk function emitting a node + edge per case) — individual cases are simple_enum_case/
    full_enum_case nodes nested inside enum_case_definitions/enum_body; grep -n "simple_enum_case\|full_enum_case\|enum_case_definitions" engine.py returns zero matches anywhere in the
    file. So the cases don't fail a guard — there is no Scala-specific code path for them at all, and they
    fall to the generic "default: recurse" branch, same as any other unrecognized node shape. Adding
    enum_definition to class_types (this issue's suggested fix) only fixes the enum's own container — cases
    would still be fully invisible afterward
    , since simple_enum_case/full_enum_case don't match
    class_types or function_types either. Scala needs its own dedicated case-handling function, mirroring
    the Swift/Kotlin pattern (emit a node per case + a case_of edge from the enum to it) — not included in
    this issue's suggested diff.
  6. extension (x: Int)'s method double (line 14) leaks to file scope — same pattern as Wroked out examples missing graph.html #3, appears as
    foo_double via contains from the file node.

Impact

  • Trait/given/extension/enum containers are absent from the graph; their members are silently reparented to
    file scope (traits/extensions) or dropped entirely (enum cases), which will also skew god_nodes/
    community detection (loose file-level definitions instead of properly grouped ones).
  • Abstract method signatures (function_declaration) are invisible everywhere, not just inside
    unrecognized containers — this also affects abstract methods declared inside an ordinarily well-handled
    class/object.
  • No semantic/LLM backfill exists for code files by default, so none of this is compensated automatically.

Suggested fix

 _SCALA_CONFIG = LanguageConfig(
     ts_module="tree_sitter_scala",
-    class_types=frozenset({"class_definition", "object_definition"}),
-    function_types=frozenset({"function_definition"}),
+    class_types=frozenset({
+        "class_definition", "object_definition", "trait_definition", "enum_definition",
+    }),
+    function_types=frozenset({"function_definition", "function_declaration"}),
     import_types=frozenset({"import_declaration"}),
     call_types=frozenset({"call_expression"}),
     call_function_field="",
     call_accessor_node_types=frozenset({"field_expression"}),
     call_accessor_field="field",
     name_fallback_child_types=("identifier",),
     body_fallback_child_types=("template_body",),
-    function_boundary_types=frozenset({"function_definition"}),
+    function_boundary_types=frozenset({"function_definition", "function_declaration"}),
     import_handler=_import_scala,
 )

Notes on the diff, and open questions to resolve before landing it:

  1. given_definition/extension_definition are deliberately not added to class_types above — a
    given can be a term-level value (given foo: Foo = ..., function-like) or a full instance body
    (given foo: Foo with { ... }, class-like), and extension blocks group multiple methods under one
    receiver rather than being a class themselves. Both are planned as separate follow-up issues:
    extension_definition has two concrete diff options (adapted from Swift's own extension-handling
    precedent); given_definition has a narrower scope than it first appears (its term-level form reduces to
    the val/given finding above) and one genuinely unresolved design question for the class-like/anonymous
    case (an anonymous instance has no name to derive an id from).
  2. trait_definition/enum_definition use the same template_body/enum_body shape as class_definition
    per body_fallback_child_types, so they should slot into the existing class-handling branch with minimal
    special-casing — but traits can't have constructor parameters the way classes can, so verify the
    constructor-parameter-handling sub-branch doesn't assume every class_types member has one.
  3. Adding trait_definition to class_types needs a companion change to _make_id (or an equivalent
    disambiguator) to avoid the trait/companion-object id collision described above
    — _make_id(stem, namespace, name) has no node-kind parameter, so trait Foo and object Foo in the same file/namespace
    would compute the identical id once both enter the class branch: add_node is if nid in seen_ids: return (first-processed wins, second is a silent no-op — never a merge or overwrite), and the subsequent
    contains edge from the file also dedups silently, so the walk continues with parent_class_nid pointing
    at whichever of the two was written first in source order. Verified end-to-end, not just reasoned from
    the code
    : applying exactly this diff (class_types/function_types additions, nothing else) to
    trait Greeter { def greet: String } / object Greeter { def default: Greeter = new Greeter { def greet = "hi" } } produces a single node labeled Greeter with both .greet() (the trait's own method) and
    .default() (the object's own method) attached to it via method edges — the graph has no way to tell
    these came from two separate definitions. trait Foo + companion object Foo is one of the most common
    Scala typeclass/service idioms, so this isn't a rare edge case worth deferring.
  4. Verified, not just expected: extends_clause → inherits resolution still works once the target of
    extends (e.g. Foo in class Baz extends Foo) is itself a properly-created trait node rather than a
    dangling name — re-running this issue's own reproduction file with exactly this diff applied confirms
    Baz's inherits edge now points at a trait_definition-backed node with real source_file/
    source_location, not an empty placeholder.
  5. Adding function_declaration broadly may also surface abstract methods in Java-style interfaces if any
    share config with Scala's fallback child types — scoped review is Scala-only per this diff, but re-check
    function_boundary_types consumers elsewhere in engine.py don't assume "boundary implies has a body".
  6. This diff does NOT restore enum cases — a separate follow-up issue is planned, see finding graspologic dependency pulls in gensim<=3.9 which fails to build on Python 3.12+ #5 in
    Reproduction above. It has its own concrete diff already (a direct adaptation of Kotlin's own enum-case
    handler, verified against the installed grammar including a check for whether Scala has a per-case
    override body — it doesn't).

Related work

Two open PRs from another contributor (Synvoya, unreviewed since 2026-07-11) address adjacent slices of this
same gap:

  • graphify#1792 adds trait_definition to
    class_types — fixing the trait-container half of finding above in isolation, with one test
    (test_scala_trait_definition_heritage). As noted in Suggested fix Wroked out examples missing graph.html #3 above, merging that change alone
    (without a matching _make_id update) converts today's silent trait absence into an actual id collision
    between a trait and a same-named companion object — worth flagging on that PR directly, since it's a
    concrete consequence of the diff as currently written, not a pre-existing issue it inherits.

  • graphify#1794 adds heritage-edge support for
    qualified (stable_type_identifier) extends/with targets, with one test covering a 2-segment example
    (pkg.Base/other.Trait1). This issue's conformance corpus exercises additional shapes: 3-4 segment depth,
    and mixed extends/with slots with independently-varying depth on each side. Verified, not just read
    — replicated the PR's exact tail-extraction logic (the stable_type_identifier branch, byte-for-byte)
    against real parsed trees:

    # Literal replica of PR #1794's added branch inside the extends_clause loop:
    def resolve_bases(extends_clause_node, source):
        bases = []
        for c in extends_clause_node.children:
            if c.type == "type_identifier":
                bases.append(read_text(c, source))
            elif c.type == "stable_type_identifier":
                tail = None
                for sc in c.children:
                    if sc.type in ("type_identifier", "identifier"):
                        tail = sc
                if tail is not None:
                    bases.append(read_text(tail, source))
            elif c.type == "generic_type":
                base = c.child_by_field_name("type")
                if base is not None:
                    bases.append(read_text(base, source))
        return bases
    class Foo extends pkg.Base                                    // -> ['Base']
    class Foo extends cats.effect.IOApp                           // -> ['IOApp']
    class Foo extends a.b.c.Deep                                  // -> ['Deep']
    class Foo extends cats.effect.IOApp with other.Trait1         // -> ['IOApp', 'Trait1']
    class Foo extends pkg.Base with a.b.c.Deep                    // -> ['Base', 'Deep']
    class Foo extends Base with Trait1                            // -> ['Base', 'Trait1']  (unqualified control)

    All six resolve to the correct tail name regardless of segment depth (2/3/4) or which heritage slot
    (extends/with) the qualified name sits in. The grammar nests deeper qualifiers inside a
    stable_identifier wrapper rather than keeping them flat (worth noting since the PR's own code comment
    describes the segments as "flat identifier children," which isn't quite accurate for 3+ segments — but the
    fix's type-based filter naturally skips that wrapper and still finds the correct tail, so the code works
    correctly despite the imprecise comment). These are offered as extra test coverage confirming the fix
    generalizes, not a bug report against it.

Environment

  • graphifyy 0.9.20, tree_sitter_scala 0.26.0
  • Reproduction run against a live graphify update --no-cluster on a minimal Scala 3 file (see above), not
    just source review — parse tree and graph.json both captured directly.

Activity

  1. sub4biz commented on Nov 15, 2026

    @sub4biz
    Author

    Retested on clean upstream v0.9.109. Trait/enum containers and abstract method nodes now pass the relevant extraction checks. Two additional cases described in this report remain reproducible: a trait and companion object with the same name collapse to one node, and the type of the second parameter list of a curried method is not emitted as a parameter_type reference. It would be useful to keep the issue open for these remaining cases.

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