class ASTDistance::Forest

Attributes

id[R]
left[R]
node_index_tbl[R]
right[R]

Public Class Methods

ast_to_forest(ast:) click to toggle source
# File lib/ast_distance/forest.rb, line 3
def self.ast_to_forest(ast:)
  node_count, node_index_tbl = build_node_index_tbl(parent: ast)

  new(left: 0, right: node_count, node_index_tbl: node_index_tbl)
end
new(left:, right:, node_index_tbl: {}) click to toggle source
# File lib/ast_distance/forest.rb, line 38
def initialize(left:, right:, node_index_tbl: {})
  @left = left
  @right = right
  @node_index_tbl = node_index_tbl
  @id = "#{left}:#{right}"
end

Private Class Methods

build_node_index_tbl(parent:, order_number: 0, node_index_tbl: {}) click to toggle source
# File lib/ast_distance/forest.rb, line 9
def self.build_node_index_tbl(parent:, order_number: 0, node_index_tbl: {})
  children_idx = parent.children.map do |child|
    next unless child.instance_of?(RubyVM::AbstractSyntaxTree::Node)

    order_number, node_index_tbl = build_node_index_tbl(
      parent: child,
      order_number: order_number,
      node_index_tbl: node_index_tbl
    )

    order_number - 1
  end.compact

  children_idx.each do |idx|
    node_index_tbl[idx].parent_index = order_number
  end

  node_index_tbl[order_number] = Node.new(
    index: order_number,
    type: parent.type,
  )

  [order_number + 1, node_index_tbl]
end

Public Instance Methods

empty?() click to toggle source
# File lib/ast_distance/forest.rb, line 67
def empty?
  left == right
end
node_count() click to toggle source
# File lib/ast_distance/forest.rb, line 59
def node_count
  right - left
end
rightmost_forest() click to toggle source
# File lib/ast_distance/forest.rb, line 45
def rightmost_forest
  v = root_index - 1

  while v > 0 && !node_index_tbl[v].root_node?
    v -= 1
  end

  Forest.new(left: v + 1, right: root_index, node_index_tbl: node_index_tbl)
end
root_index() click to toggle source
# File lib/ast_distance/forest.rb, line 63
def root_index
  right - 1
end
root_node() click to toggle source
# File lib/ast_distance/forest.rb, line 55
def root_node
  node_index_tbl[root_index]
end