Skip to content

Commit

Permalink
Added SyntaxNode#write_dot_file
Browse files Browse the repository at this point in the history
This will output a file in DOT format that you can
feed to Graphviz <http://www.graphviz.org/> to graphically
inspect ASTs generated by Parser#parse. It is a quick hack
and there are many possible improvements. Each SyntaxNode is
assigned a unique integer id in the instance variable @dot_id
using the class variable @@dot_id_counter. The method
SyntaxNode#write_dot does the actual work. Right now it doesn't
ignore any nodes, but one can imagine ignoring nodes only
consisting of whitespace, etc.
  • Loading branch information
Nicolas Ojeda Bar committed Aug 20, 2009
1 parent 4b0b91f commit 5c30822
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/treetop/runtime/syntax_node.rb
@@ -1,8 +1,11 @@
module Treetop
module Runtime
class SyntaxNode
@@dot_id_counter = 0

attr_reader :input, :interval, :elements
attr_accessor :parent
attr_reader :dot_id

def initialize(input, interval, elements = nil)
@input = input
Expand All @@ -12,6 +15,9 @@ def initialize(input, interval, elements = nil)
element.parent = self
end
end

@dot_id = @@dot_id_counter
@@dot_id_counter += 1
end

def terminal?
Expand Down Expand Up @@ -67,6 +73,26 @@ def inspect(indent="")
""
)
end

def write_dot(io)
io.puts "node#{dot_id} [label=\"#{text_value}\"];"
if nonterminal? then
elements.each do
|x|
io.puts "node#{dot_id} -> node#{x.dot_id};"
x.write_dot(io)
end
end
end

def write_dot_file(fname)
File.open(fname + ".dot","w") do
|file|
file.puts "digraph G {"
write_dot(file)
file.puts "}"
end
end
end
end
end

0 comments on commit 5c30822

Please sign in to comment.