4
require 'kpeg/code_generator'
5
require 'kpeg/format_parser'
6
require 'kpeg/grammar_renderer'
11
OptionParser.new do |o|
12
o.banner = "Usage: kpeg [options]"
14
o.on("-t", "--test", "Syntax check the file only") do |v|
18
o.on("--reformat", "Reformat your grammar and write it back out") do
19
options[:reformat] = true
22
o.on("-o", "--output FILE", "Where the output should go") do |v|
26
o.on("-n", "--name NAME", "Class name to use for the parser") do |v|
30
o.on("-f", "--force", "Overwrite the output if it exists") do |v|
34
o.on("-s", "--stand-alone", "Write the parser to run standalone") do |v|
35
options[:standalone] = v
38
o.on("-v", "--[no-]verbose", "Run verbosely") do |v|
42
o.on("-d", "--debug", "Debug parsing the file") do |v|
49
unless File.exists?(file)
50
puts "File '#{file}' does not exist"
54
parser = KPeg::FormatParser.new File.read(file), true
56
unless m = parser.parse
57
puts "Syntax error in grammar #{file}"
62
grammar = parser.grammar
66
puts "Please specify -o for where to write the new grammar"
70
output = options[:output]
71
if File.exists?(output) and !options[:force]
72
puts "Output '#{output}' already exists, not overwriting (use -f)"
76
rend = KPeg::GrammarRenderer.new(parser.grammar)
78
File.open output, "w" do |f|
82
puts "Wrote reformatted output to #{output}"
87
if !options[:test] and !options[:name]
88
unless name = grammar.variables["name"]
89
puts "Please specify -n"
98
new_path = options[:output]
100
new_path = "#{file}.rb"
103
if !options[:test] and File.exists?(new_path) and !options[:force]
104
puts "Path #{new_path} already exists, not overwriting\n"
112
gr = KPeg::GrammarRenderer.new(grammar)
119
cg = KPeg::CodeGenerator.new name, grammar
120
cg.standalone = options[:standalone]
124
open new_path, "w" do |io|
128
puts "Wrote #{name} to #{new_path}"