graphify icon indicating copy to clipboard operation
graphify copied to clipboard

Scala `derives` and `export` clauses are invisible to structural extraction — `derives` reuses an existing block, `export` gets a precise (not placeholder) resolution

Open sub4biz opened this issue 4 months ago • 1 comments

Summary

derives has a concrete diff, reusing an existing per-language block almost verbatim. export initially looked like it should just accept the general "member calls to external symbols aren't precisely resolved" tradeoff (documented in graphify#2041) — that framing turned out to be wrong: export's source object name is a static, syntactically-known local identifier, not a dynamic call receiver, and the extractor already has a mechanism that resolves exactly this case precisely when possible. Applying the general tradeoff without checking that first would have been a needless, avoidable loss specific to Scala/cats-effect-style code, where export is commonly used to re-expose a locally-defined delegate/companion object's members — precisely the case where precise resolution is available.

derives — concrete diff, reuses the existing extends_clause block almost verbatim

Verified shape

case class Coord(x: Int, y: Int) derives Eq, Show
class_definition
  identifier "Coord"
  class_parameters -> class_parameter "x": Int, class_parameter "y": Int
  derives_clause
    type_identifier "Eq"
    type_identifier "Show"

derives_clause is a direct sibling of class_parameters, at the same level as extends_clause — the exact same position the existing Scala-specific inheritance block (engine.py:2750+) already scans for extends_clause/with. No new dispatch site, no new function.

Proposed diff

# inside the existing `if config.ts_module == "tree_sitter_scala":` block at engine.py:2750,
# alongside the extends_clause handling already there:
for c in node.children:
    if c.type != "derives_clause":
        continue
    for sub in c.children:
        if sub.type != "type_identifier":
            continue
        derived_name = _read_text(sub, source)
        target_nid = ensure_named_node(derived_name, line)
        if target_nid != class_nid:
            add_edge(class_nid, target_nid, "derives", line)

Reuses ensure_named_node/add_edge exactly as the neighboring extends_clause code already does — the only new thing is the "derives" relation label (vs. "inherits"/"mixes_in"), which the maintainer may want to rename for consistency with whatever relation vocabulary they already use elsewhere.

Verified against a real parsed tree, not just reasoned through: running this exact extraction logic against case class Coord(x: Int, y: Int) derives Eq, Show resolves ['Eq', 'Show'].

Open question

Eq/Show here are typeclasses being derived, almost always external (cats.Eq, cats.Show) — so most real-world uses will resolve through ensure_named_node's bare-placeholder fallback, same as any other external type reference in this tool. This is the ordinary, already-accepted tradeoff (external symbol → bare stub) and doesn't need a workaround — unlike export below, derives' targets aren't usually locally defined, so there's no equivalent "we actually know more" case to exploit here.

export — precise resolution instead of a blind placeholder

Verified shape, including the multi-segment case

object Facade:
  export impl.{coreLogic, version}
export_declaration
  identifier "impl"
  namespace_selectors
    identifier "coreLogic"
    identifier "version"
object Facade2:
  export pkg.helper.{util}
export_declaration
  identifier "pkg"
  identifier "helper"
  namespace_selectors
    identifier "util"

A qualified prefix (pkg.helper.{util}) parses as multiple sibling identifier nodes, not one combined path node — the segment immediately before namespace_selectors/namespace_wildcard is the actual object being re-exported from (helper); earlier segments (pkg) are outer package qualification.

Wildcard forms confirmed, not left untried: both export impl.* and export impl._ (Scala 3 accepts either token for "export everything") were dumped directly:

export impl.*
export_declaration
  identifier "impl"
  namespace_wildcard
    *
export impl._
export_declaration
  identifier "impl"
  namespace_wildcard
    _

Both produce the identical shape — a namespace_wildcard node whose only child is the token (* or _) — so handling needs no branching on which token was used, detecting child.type == "namespace_wildcard" alone covers both.

Why "accept the general external-symbol tradeoff" was the wrong starting point

The initially-considered design would have called ensure_named_node(member_name, line) directly on each bare selector name (coreLogic, version), producing an unqualified stub exactly like any unresolved external call target. That throws away information genuinely available here and not in the general case: the source object's name is a literal identifier in the source text, not a computed/dynamic expression — and this extractor already has a mechanism, used everywhere else, that resolves exactly this shape precisely when the source is locally defined.

The mechanism already in the extractor

ensure_named_node (engine.py:2290-2312) is called for every unqualified name reference elsewhere in the file, and it already tries the qualified id first:

def ensure_named_node(name: str, line: int) -> str:
    nid = _make_id(stem, ".".join(namespace_stack), name)
    if nid in seen_ids:
        return nid                      # <-- exact match to a real, locally-defined node
    nid = _make_id(name)                 # <-- only reached if the qualified guess missed
    if nid not in seen_ids:
        ... # create a sourceless bare stub
    return nid

And a class member's own id is confirmed (engine.py:3151, the function branch) to be func_nid = _make_id(parent_class_nid, func_name) — i.e. the parent's own resolved id, plus the member name. Putting these together: calling ensure_named_node("impl", line) for the source object, when impl is defined locally in the same file/namespace, returns the exact same id impl's own object_definition node already has — not a guess. Then _make_id(that_id, member_name) for each selector produces the exact same id that member would already have if impl's body was walked normally (same formula as line 3151). Zero new resolution logic — this is the existing mechanism, applied to a case it already handles well.

Proposed diff (new branch in the _scala_extra_walk function proposed in

graphify#2044)

if node.type == "export_declaration":
    segments: list[str] = []
    selector_names: list[str] = []
    is_wildcard = False
    for child in node.children:
        if child.type == "identifier":
            segments.append(_read_text(child, source))
        elif child.type == "namespace_selectors":
            for sub in child.children:
                if sub.type == "identifier":
                    selector_names.append(_read_text(sub, source))
        elif child.type == "namespace_wildcard":
            is_wildcard = True
    if not segments:
        return True
    source_name = segments[-1]           # tail: the object actually being exported from
    line = node.start_point[0] + 1
    source_nid = ensure_named_node(source_name, line)   # exact id if `impl` is locally defined,
                                                          # bare stub otherwise — same fallback
                                                          # every other reference in the file gets
    owner_nid = parent_class_nid if parent_class_nid else file_nid
    for member_name in selector_names:
        member_nid = _make_id(source_nid, member_name)   # matches a real member's own id
                                                          # (engine.py:3151's formula) when
                                                          # source_nid resolved precisely
        add_edge_fn(owner_nid, member_nid, "exports", line)
    if is_wildcard and not selector_names:
        add_edge_fn(owner_nid, source_nid, "exports_all", line)
    return True

Verified against a real parsed tree, not just reasoned through — running this exact extraction logic (the segments/selector_names/is_wildcard collection) against all four shapes above:

export impl.{coreLogic, version}    -> source: impl,   selectors: [coreLogic, version], wildcard: False
export pkg.helper.{util}            -> source: helper, selectors: [util],               wildcard: False
export impl.*                       -> source: impl,   selectors: [],                   wildcard: True
export impl._                       -> source: impl,   selectors: [],                   wildcard: True

All four resolve correctly — the tail segment, the selector names, and the wildcard flag are all extracted as claimed.

This needs member_nid to also become a real node if it isn't one yet (currently _make_id alone doesn't create a node — only add_node/ensure_named_node do). Two sub-options, not resolved here:

  1. Call add_node_fn(member_nid, member_name, line) unconditionally before the edge (matches how case_of targets are created in the enum-case handler) — creates a node even when source_nid was a bare stub (i.e. impl is external), giving every exported name some node to attach to.
  2. Only emit the edge if member_nid is already in seen_ids (i.e. skip silently when impl is external or its members haven't been walked yet) — avoids creating speculative nodes for members that may not actually exist under that exact id, at the cost of exporting-from-an-external-object producing nothing visible at all.

A wildcard re-export (export impl.*/export impl._) gets a single edge from the owner straight to the resolved source object (source_nid — same precise-or-fallback resolution as the named-selector case above), tagged with a distinct relation ("exports_all", proposed) so it isn't confused with a per-member "exports" edge. No per-member ids are needed since there are no individual names to attach them to.

Open questions before landing

  1. When impl is defined in a different file than the one being walked, ensure_named_node("impl", ...) only checks seen_ids built up so far in this file's own walk (confirmed by reading the closure — stem/namespace_stack are this-file-scoped) — cross-file precise resolution isn't claimed here, only same-file. This matches the scope of every other ensure_named_node call in this extractor, so it's not a new limitation introduced by this proposal, just worth stating explicitly rather than implying it resolves across the whole corpus.
  2. Should the edge relation be "exports" (proposed, new label) or reuse "references" with a context tag (context="export") for consistency with how most other cross-references in this tool are labeled? Precedent is split both ways elsewhere in the file (case_of/inherits/mixes_in are dedicated labels; most type references reuse "references" with a context) — maintainer's call.

Environment

  • graphifyy 0.9.20, tree_sitter_scala 0.26.0
  • All shapes in this file, including the multi-segment export case, dumped directly against the installed grammar and checked for zero ERROR/is_missing nodes. The proposed extraction logic for both derives and export was run against real parsed trees, not just reasoned through.

sub4biz avatar Jul 19 '26 16:07 sub4biz

Retested on clean upstream tag v0.9.109. The derives case now emits a references edge with context derives, following bcf96244. Thanks for addressing that part!

The export part still appears open: for the two examples below, I found neither an exports edge to .coreLogic() nor an exports_all edge from Facade to Impl, respectively.

object Impl {
  def coreLogic(): Int = 1
}
object Facade {
  export Impl.{coreLogic}
}
object Impl {
  def coreLogic(): Int = 1
}
object Facade {
  export Impl.*
}

The two cases were checked separately using extract_scala. It would be useful to keep this issue open for export.

sub4biz avatar Nov 14 '26 23:11 sub4biz