LoginSignup
5
2

More than 5 years have passed since last update.

Ruby2.6 + Graphvizで抽象構文木をグラフにしてみる

Last updated at Posted at 2018-12-29

Pythonの抽象構文木をGraphvizで可視化するを見て、ruby でもやってみようと思った。

正直言って、RubyVM モジュールに触るのは初めてなので、正しいのかどうかはよくわからない。
でもまあ、それらしいツリーが出力できたからいいかなと思っている。

というわけで、ソースコード:

ruby2.6
# ruby rubyast.rb sample.rb | dot -Tpng -oast.png
@symbol=:a
def sym
  @symbol = @symbol.succ
end

def show(x, parent)
  return if x.nil?
  label, shape = if x.respond_to?(:type)
    [ x.type.to_s, "oval" ]
  else
    [ "%s(%s)" % [x.inspect, x.class], "box" ]
  end
  this = sym
  puts( "%s -> %s" % [ parent, this ] )
  puts( %Q!%s[ label=%s; shape=%s ]! % [ this, label.to_s.inspect, shape ] )
  if RubyVM::AbstractSyntaxTree::Node===x
    x.children.each do |ch|
      show(ch, this)
    end
  end
end

puts( %Q!digraph{graph [dpi=288;];! )
src = File.open(ARGV[0]){ |f| f.read }
show(RubyVM::AbstractSyntaxTree.parse(src), "root")
puts("}")

食べさせたコードはこんな感じ:

sample.rb
def foobar(hoge, fuga)
  p( hoge + fuga * 2 )
end
foobar(111,222)

出てくる絵は、こんな感じ:

image.png

なかなか楽しい。

5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2