From 13403405b0fedb95c00586a6127878a80f4256f6 Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Sat, 1 May 2021 16:54:24 -0400 Subject: [PATCH] Add Error class to handle grammar loading errors --- lib/imbecile.rb | 9 +++++++-- lib/imbecile/grammar.rb | 17 ++++------------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/lib/imbecile.rb b/lib/imbecile.rb index 193f0f7..7e3ed94 100644 --- a/lib/imbecile.rb +++ b/lib/imbecile.rb @@ -5,11 +5,16 @@ require "erb" module Imbecile + class Error < RuntimeError + end + class << self def run(input_file, output_file) - grammar = Grammar.new - unless grammar.load(input_file) + begin + grammar = Grammar.new(input_file) + rescue Error => e + $stderr.puts e.message return 2 end classname = grammar.classname || grammar.capitalize diff --git a/lib/imbecile/grammar.rb b/lib/imbecile/grammar.rb index 35b1303..bb5952e 100644 --- a/lib/imbecile/grammar.rb +++ b/lib/imbecile/grammar.rb @@ -7,14 +7,9 @@ module Imbecile # @return [String, nil] Class name. attr_reader :classname - def initialize + def initialize(input_file) @tokens = {} @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| line = line.chomp line_number = line_index + 1 @@ -29,20 +24,16 @@ module Imbecile elsif line =~ /^\s*token\s+(\S+)\s+(.*)$/ name, expr = $1, $2 unless name =~ /^[a-zA-Z_][a-zA-Z_0-9]*$/ - $stderr.puts "Invalid token name #{name} on line #{line_number}" - return false + raise Error.new("Invalid token name #{name} on line #{line_number}") end if @tokens[name] - $stderr.puts "Duplicate token name #{name} on line #{line_number}" - return false + raise Error.new("Duplicate token name #{name} on line #{line_number}") end @tokens[name] = expr else - $stderr.puts "Unexpected input on line #{line_number}: #{line}" - return false + raise Error.new("Unexpected input on line #{line_number}: #{line}") end end - true end end