Fancier error messages for the parser.

The error messages of the parser now contain surrounding lines of code instead
of only the offending line of code. This should make debugging a bit easier.
Line numbers are also shown for each line.
This commit is contained in:
Yorick Peterse 2014-03-20 23:30:24 +01:00
parent 74bc11a239
commit ba17996bfc
1 changed files with 20 additions and 8 deletions

View File

@ -145,19 +145,31 @@ end
end end
def on_error(type, value, stack) def on_error(type, value, stack)
name = token_to_str(type) name = token_to_str(type)
line_str = @lines[@line - 1] index = @line - 1
lines = ''
raise Racc::ParseError, <<-EOF.strip # Show up to 2 lines before and after the offending line (if they exist).
Unexpected #{name} with value #{value.inspect} on line #{@line} (-2..2).each do |offset|
line = @lines[index + offset]
Offending code: if line
number = @line + offset
#{line_str} if offset == 0
prefix = '=> '
else
prefix = ' '
end
Current stack: lines << "#{prefix}#{number}: #{line}"
end
end
#{stack.inspect} raise Racc::ParseError, <<-EOF
Unexpected #{name} with value #{value.inspect} on line #{@line}:
#{lines}
EOF EOF
end end