Sha256: 65c34a0077b6ebd7cb3bf45f9cb0e71a7b9db4ca8979f62b27832b4f3a22112b

Contents?: true

Size: 969 Bytes

Versions: 1

Compression:

Stored size: 969 Bytes

Contents

require 'ast2dot/version'
require 'ast2dot/node_label'
require 'erb'

class AST2Dot
  def self.render(code)
    new(code).render
  end

  attr_reader :ast, :graph_edges, :node_labels

  def initialize(code)
    @ast = RubyVM::AbstractSyntaxTree.parse(code)
    @template = File.read(File.expand_path('templates/default.dot.erb', __dir__))
  end

  def export
  end

  def render
    @graph_edges = []
    @node_labels = Hash.new

    node_labelling(ast)

    graph_data = ERB.new(@template, nil, '-').result(binding)
    graph_data.lines.map(&:rstrip).join("\n")
  end

  private

  def node_labelling(parent, index = 1)
    children_idx = parent.children.map do |child|
      next unless child.instance_of?(RubyVM::AbstractSyntaxTree::Node)

      index = node_labelling(child, index)
      index - 1
    end.compact

    children_idx.each do |idx|
      @graph_edges << { from: index, to: idx }
    end

    @node_labels[index] = parent.type

    index + 1
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ast2dot-0.1.1 lib/ast2dot.rb