Skip to content

Nested class/object containment is never represented as a graph edge — contains always sources from the file node, not the enclosing type, across ~19 languages #2040

Closed

Description

@sub4biz

Summary

For any language using _extract_generic's class-node branch (graphify/extractors/engine.py), a nested
class/object/trait never gets a contains edge from its actual enclosing type. The edge is hard-coded to
originate from the file node, regardless of nesting depth:

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)
    callable_def_nids.add(class_nid)
    add_edge(file_nid, class_nid, "contains", line)   # <-- always file_nid, never parent_class_nid
    ...

There is a partial, C#-specific mitigation: when parent_class_nid is set, the node gets a
metadata={"is_nested_type": True} flag — but even then, no edge is created to the actual parent, only a
boolean flag on the node. Every other language, including Scala, doesn't even get that.

(A nested type's own members — e.g. a method inside the nested class — DO correctly nest under it via the
usual parent_class_nid mechanism once the nested type itself is being walked. The gap is specifically one
level up, at the class-containing-a-class edge, not at class-containing-a-method.)

Reproduction (Scala)

class Outer {
  class Inner
  def makeInner: Inner = new Inner
}

graph.json shows Inner's contains edge sourced from the file, never from Outer — there is no edge
anywhere in the graph connecting Outer → Inner. The only way to know Inner lives inside Outer is to
notice their source lines are close together and infer it; the graph itself does not encode it.

Why this matters

  • Any codebase using nested types for organization (inner builder/helper classes, module-like nested objects)
    loses that structure in the graph — nested types appear as flat siblings of everything else in the file,
    indistinguishable from top-level types.
  • Community detection / god_nodes likely treats a deeply-nested helper class the same as a top-level public
    API class, since there's no edge signal indicating one is an implementation detail nested inside the other.

Cross-language scope — precise counts, not "every language"

Path 1 — shared _extract_generic/engine.py walker (15 LanguageConfig blocks in extract.py). Every
one of these calls the same _extract_generic function with only the config differing, so the bug is
structurally guaranteed for all of them. Empirically confirmed by a live graphify update run, each
compiled first with a real toolchain (8 of 15):

  • Scala (see Reproduction above).
  • Java — Inner's contains edge sourced from the file, not Outer; same for the static nested class:
    public class Outer {
        class Inner {
            int x;
        }
    
        static class StaticNested {
            int y;
        }
    }
  • Kotlin — same symptom for both a plain nested class and an inner class:
    class Outer {
        class Nested {
            val y: Int = 0
        }
    
        inner class Inner {
            val x: Int = 0
        }
    }
  • TypeScript — no native "class inside class" syntax, so tested the closest idiomatic equivalent
    (declaration-merging a namespace with a class of the same name):
    class Outer {
      y: number = 0;
    }
    
    namespace Outer {
      export class Inner {
        x: number = 0;
      }
    }
  • C# — same symptom; Inner's contains edge sourced from the file:
    class Outer
    {
        class Inner
        {
            int x;
        }
    
        static void Main() { }
    }
  • C++ — see the independent, more severe C++-specific bug below (nested class fully disappears rather
    than misattributing).
  • Python — same symptom:
    class Outer:
        class Inner:
            def __init__(self):
                self.x = 0
  • Ruby — same symptom:
    class Outer
      class Inner
        def initialize
          @x = 0
        end
      end
    end

All seven (plus Scala) show the identical pattern: the nested type gets its own node, but its contains edge
is sourced from the file node, never from the enclosing type.

Structurally certain but not individually run (7 of 15): plain JavaScript, TSX, Groovy, C, Lua, Swift —
same code path as an already-tested sibling. PHP is in this list by config but has no true
lexically-nested-class syntax
(only anonymous classes), so the general finding likely doesn't have a clean
PHP repro.

Path 2 — separate, per-language "custom walk" extractors, not sharing engine.py's class branch at all.
Each has its own add_edge(file_nid, ..., "contains", ...) call, written independently but repeating the same
design choice. Live-tested with a real compiler/toolchain per language:

  • 4 of 7 empirically confirm the anti-pattern, each with its own precise symptom:
    • Rust — worse than misattribution: outer gets no node at all, only Inner appears, sourced from
      the file. Rust's extractor has no module-handling at all, so the module itself is fully invisible, not
      merely mis-parented.
      mod outer {
          pub struct Inner {
              pub x: i32,
          }
      }
    • Zig — the textbook case: both Outer and Inner get real nodes, but Inner's contains edge is
      sourced from the file, not Outer.
      const Outer = struct {
          const Inner = struct {
              x: i32,
          };
      };
    • PowerShell — identical symptom to Zig.
      function Outer {
          function Inner {
              return 1
          }
      }
    • Elixir — same module-to-module symptom, but with a real nuance: the function hello() inside
      Inner correctly gets a method edge sourced from Inner itself, not the file. The module-creation code
      hard-codes the file unconditionally; the function-creation code one level down already checks for a
      parent module and uses it correctly. The bug is real but partial — one level of nesting is wrong, the
      next is right.
      defmodule Outer do
        defmodule Inner do
          def hello do
            :world
          end
        end
      end
  • 3 of 7 have no real nested-type construct in the language to demonstrate the bug with, so they are not
    counted as additional confirmed instances even though their code has the same shape:
    • Go has no lexical nested-type declaration syntax (only anonymous struct fields); tested sibling
      package-level types instead, which correctly attach to the file — that's correct behavior for genuinely
      non-nested code, not a bug.
      package main
      
      type Outer struct {
          X int
      }
      
      type Inner struct {
          Y int
      }
      
      func main() {}
    • Objective-C's categories/extensions aren't lexical nesting either; a plain @interface/@implementation
      correctly attaches to the file and gets its inherits edge.
      @interface Outer : NSObject
      @end
      
      @implementation Outer
      @end
    • SQL has no lexical nesting concept for tables at all; a plain CREATE TABLE correctly attaches to the
      file.
      CREATE TABLE outer_table (
          id INT PRIMARY KEY
      );
  • Two extractors already get this right — useful precedent for the fix: extractors/pascal_forms.py
    (Delphi/Lazarus form files) uses an explicit stack: list[str] of enclosing container ids, and
    extractors/verilog.py uses parent = module_nid or file_nid for functions/tasks nested inside a module.
    Both correctly fall back to the real enclosing container instead of always the file.
  • Not investigated further, flagged as unverified rather than assumed either way: Julia, Fortran, and Dart
    have no contains-edge pattern matching this shape found by inspection — could mean they don't emit this
    relation for class-like structures at all, or genuinely lack a nesting concept in scope.

Precise scope: at least 19 languages have a demonstrated bug (15 via the shared path, 8 empirically
confirmed there; 4 more independently-coded extractors empirically confirmed) — not universal, since at least
2 extractors (pascal_forms, verilog) already implement the fix correctly, and Go/Objective-C/SQL/PHP have
no construct that would trigger it.

An independent, more severe C++-specific bug found during this audit

C++ doesn't leak the nested class to file scope like the others — it's completely absent: zero nodes, zero
edges
, for the nested class or its own methods:

class Outer {
public:
    class Inner {
    public:
        int x;
        int method() { return x; }
    };
};

int main() { return 0; }

Confirmed via a live run: only Outer gets a node; no Inner node exists anywhere in the graph, not even a
misattributed one. Root cause: a nested class Inner { ... }; inside Outer's body parses as
field_declaration → class_specifier (C++'s grammar puts a nested type definition in the same grammatical
position as a data member). The C++-specific field_declaration handler (built for ordinary data members)
does:

if (config.ts_module == "tree_sitter_cpp" and t == "field_declaration" and parent_class_nid):
    decls = list(node.children_by_field_name("declarator"))
    # ... (no declarator matches for a nested class — there's no variable name, just a class body)
    return   # <-- unconditional return, never recurses into node's children

The unconditional return means the walker never descends into this node's children at all, so it never
reaches the nested class_specifier inside it — class_specifier is in C++'s class_types, so if this
early return didn't fire, the nested class would hit the same file-sourced-contains bug as every other
language; instead it's swallowed one level earlier and disappears outright. This is a separate,
higher-severity bug (silent complete disappearance vs. misattribution), independent of the general finding
above — worth tracking and fixing separately. A fix would need the field_declaration handler to check
whether any child is a class_specifier/struct_specifier before returning, and recurse into it (with
parent_class_nid still set to Outer's id) if so.

Is this a bug or a deliberate simplification?

Open question, not assumed. Possible reasons this could be intentional:

  • Flattening containment to file-level might be a deliberate simplification for a "file contains N classes"
    mental model, with parent_class_nid reserved for member-level (method/field) attribution only.
  • The C# is_nested_type flag suggests someone cared about distinguishing nested types at some point, but
    chose a metadata flag over a graph edge.

Suggested fix (one option, not the only one)

     add_node(class_nid, class_name, line, metadata=metadata)
     callable_def_nids.add(class_nid)
-    add_edge(file_nid, class_nid, "contains", line)
+    if parent_class_nid:
+        add_edge(parent_class_nid, class_nid, "contains", line)
+    else:
+        add_edge(file_nid, class_nid, "contains", line)

Not a novel pattern for this codebase — extractors/pascal_forms.py and extractors/verilog.py already
implement equivalent parent-tracking correctly and could serve as reference implementations.

Open questions before landing:

  1. Would this break any existing consumer that assumes every class has exactly one contains edge sourced
    from a file node (e.g. a query enumerating "all classes in file X" via contains edges from the file node
    — it would now miss nested classes unless it also walks nested contains edges transitively)?
  2. Should the C# is_nested_type metadata flag be kept alongside the new edge, or removed as superseded?
  3. Does this interact with god_nodes/community-detection in a way that needs separate verification (a
    newly-nested-under-parent class might shift community assignment)?

Environment

  • graphifyy 0.9.20
  • Cross-language toolchains used for compile-checking every repro above before running graphify: javac
    (Eclipse Adoptium JDK 17), kotlinc 2.1.20, tsc (TypeScript, via npx), dotnet 9.0 SDK (C#), clang++
    (LLVM 22.1.8), CPython 3.13 (py_compile), ruby 3.3, rustc/cargo (rustup), zig 0.16.0, Erlang OTP 29
    • Elixir (portable), go build, Windows PowerShell's own script parser, Python's built-in sqlite3 for the
      SQL case. Objective-C was not compiler-checked (no toolchain available on the test platform) — noted as a
      limitation, not silently skipped.

Activity

  1. safishamsi commented on Jul 20, 2026

    @safishamsi
    Member

    Fixed in v0.9.22: a nested class/object/trait's contains edge now sources from its enclosing type instead of the file node (across the generic-extractor languages), so the containment tree is file -> Outer -> Inner. https://github.com/Graphify-Labs/graphify/releases/tag/v0.9.22

  2. added a commit that references this issue on Jul 26, 2026
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