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)
出てくる絵は、こんな感じ:
なかなか楽しい。