Add Error class to handle grammar loading errors

This commit is contained in:
Josh Holtrop 2021-05-01 16:54:24 -04:00
parent 07dd68e367
commit 13403405b0
2 changed files with 11 additions and 15 deletions

View File

@ -5,11 +5,16 @@ require "erb"
module Imbecile module Imbecile
class Error < RuntimeError
end
class << self class << self
def run(input_file, output_file) def run(input_file, output_file)
grammar = Grammar.new begin
unless grammar.load(input_file) grammar = Grammar.new(input_file)
rescue Error => e
$stderr.puts e.message
return 2 return 2
end end
classname = grammar.classname || grammar.capitalize classname = grammar.classname || grammar.capitalize

View File

@ -7,14 +7,9 @@ module Imbecile
# @return [String, nil] Class name. # @return [String, nil] Class name.
attr_reader :classname attr_reader :classname
def initialize def initialize(input_file)
@tokens = {} @tokens = {}
@rules = {} @rules = {}
end
# @return [Boolean]
# Whether loading was successful.
def load(input_file)
File.read(input_file).each_line.each_with_index do |line, line_index| File.read(input_file).each_line.each_with_index do |line, line_index|
line = line.chomp line = line.chomp
line_number = line_index + 1 line_number = line_index + 1
@ -29,20 +24,16 @@ module Imbecile
elsif line =~ /^\s*token\s+(\S+)\s+(.*)$/ elsif line =~ /^\s*token\s+(\S+)\s+(.*)$/
name, expr = $1, $2 name, expr = $1, $2
unless name =~ /^[a-zA-Z_][a-zA-Z_0-9]*$/ unless name =~ /^[a-zA-Z_][a-zA-Z_0-9]*$/
$stderr.puts "Invalid token name #{name} on line #{line_number}" raise Error.new("Invalid token name #{name} on line #{line_number}")
return false
end end
if @tokens[name] if @tokens[name]
$stderr.puts "Duplicate token name #{name} on line #{line_number}" raise Error.new("Duplicate token name #{name} on line #{line_number}")
return false
end end
@tokens[name] = expr @tokens[name] = expr
else else
$stderr.puts "Unexpected input on line #{line_number}: #{line}" raise Error.new("Unexpected input on line #{line_number}: #{line}")
return false
end end
end end
true
end end
end end