-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar
executable file
·75 lines (54 loc) · 1.63 KB
/
grammar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env ruby
# adds lib directory to Gem path
$LOAD_PATH.unshift(File.expand_path("../lib", __FILE__))
# shortcut notation to require gems
%w{ grammar optparse regexTokenStream nfa dfa }.each { |gem| require gem }
# object to parse command line options
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: grammar [OPTIONS] [FILE]"
opts.on("-o NAME", "--output=NAME", "output Graph to file") do |file|
options[:output] = file
end
opts.on("-t TYPE", "--type=TYPE", "type to compile to graph to. Default is png") do |type|
options[:type] = type.to_sym
end
opts.on("-s", "--simplify", "simplify regular expression parse tree") do |opt|
options[:simplify] = opt
end
opts.on("-r", "--regex", "accept a regular expression in a file in place of a token file") do |opt|
options[:regex] = opt
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end.parse!
grammar = Grammar.new ARGV.first
puts grammar.to_s
puts "\nItem sets: "
grammar.get_item_sets.each_with_index do |item_set, i|
puts "Item set #{i}:"
item_set.each do |lhs, rhs_array|
rhs_array.each do |rhs|
puts "\t#{lhs} -> #{rhs.join(" ")}"
end
end
end
if options[:regex]
tokens = RegexTokenStream.new "#{ARGV[1]}"
else
tokens = TokenStream.new "#{ARGV[1]}"
end
parse_tree = grammar.makeTree tokens
if options[:simplify]
parse_tree.simplify!
nfa = Nfa.new(parse_tree)
puts nfa
dfa = Dfa.new(nfa)
puts dfa
end
options[:output] ||= "parse_tree.png"
type = File.extname(options[:output]).delete(".")
type.empty? ? :png : type.to_sym
parse_tree.to_graphviz options[:output], :type => type