[KG] (Ruby) Parse Definitions

Goal 1: Extract core code definitions from Ruby files using tree-sitter-ruby and ast-grep.

This issue focuses on identifying and extracting structural definitions within Ruby code. These definitions are crucial for building the foundational nodes of the Knowledge Graph.

Scope: The parser should identify and extract the following types of definitions:

  • class_definition: Classes and nested classes.
  • module_definition: Modules and nested modules.
  • method_definition: Instance methods within classes or modules.
  • singleton_method_definition: Class methods (methods defined on self or a specific object/class).
  • constant: Top-level constants and constants defined within classes/modules.
  • Anonymous functions/blocks: lambda expressions and do_blocks, where they define scope and contain logic that needs to be recognized for FQN resolution.

Implementation Details: Leverage the tree-sitter-ruby grammar to build the Abstract Syntax Tree (AST) and ast-grep for efficient pattern matching to locate these constructs.

Current Progress (from gitlab-org/rust/gitlab-code-parser!1+): Initial work on parsing these definitions is already complete and available in gitlab-org/rust/gitlab-code-parser!1+. This issue serves to formalize that work, ensure comprehensive coverage, and integrate it into the epic's progression. The crates/parser-core/src/ruby/definitions.rs file in the MR demonstrates the current capabilities.

Example of constructs covered by initial implementation:

# class_definition
class MyClass
  # method_definition
  def instance_method
    # lambda
    my_lambda = -> { puts "Hello" }
  end

  # singleton_method_definition
  def self.class_method
    # do_block
    [1, 2, 3].each do |i|
      puts i
    end
  end

  # constant
  MY_CONSTANT = 123

  # Nested class
  class NestedClass
  end
end

# module_definition
module MyModule
  # Nested module
  module NestedModule
  end
end

Goal 2: Compute a Fully Qualified Name (FQN) for each definition identified in Ruby files.

Once definitions are parsed, the next step is to assign them a unique, hierarchical FQN. This FQN represents the full path to the definition within the codebase, enabling accurate linking in the Knowledge Graph.

Scope: For each definition (classes, modules, methods, constants, and relevant anonymous functions/blocks) identified by the parser, compute its FQN. This involves traversing the AST and maintaining a stack of "scope names" to correctly reflect nesting.

Expected FQN Examples (based on test_data/expected_definitions.json from gitlab-org/rust/gitlab-code-parser!1+):

Given a file lib/my_app/utils.rb:

module MyApp
  class MyClass
    def instance_method
    end

    def self.class_method
    end

    MY_CONSTANT = 1
  end

  module MyModule
    class NestedClass
    end
  end

  GLOBAL_CONSTANT = 2
end

def top_level_method
end
Edited by Kisha Mavryck Richardson