Class: Whittle::ParseErrorBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/whittle/parse_error_builder.rb

Overview

Since parse error diagram the region where the error occured, this logic is split out from the main Parser

Class Method Summary collapse

Class Method Details

.exception(state, token, context) ⇒ ParseError

Generates a ParseError for the given set of error conditions

A ParseError always specifies the line nunber, the expected inputs and the received input.

If possible, it also draw a diagram indicating the point where the error occurred.

Parameters:

  • state (Hash)

    all the instructions for the current parser state

  • token (Hash)

    the unexpected input token

  • context (Hash)

    the current parser context, providing line number, input string + stack etc

Returns:

  • (ParseError)

    a detailed Exception to be raised



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/whittle/parse_error_builder.rb', line 28

def exception(state, token, context)
  region   = extract_error_region(token[:offset], context[:input])
  expected = extract_expected_tokens(state)
  message  = <<-ERROR.gsub(/\n(?!\n)\s+/, " ").strip
    Parse error:
    #{expected.count > 1 ? 'expected one of' : 'expected'}
    #{expected.map { |k| k.inspect }.join(", ")}
    but got
    #{token[:name].inspect}
    on line
    #{token[:line]}.
  ERROR

  unless region.nil?
    region = "\n\nExact region marked...\n\n#{region}"
  end

  ParseError.new(message + region.to_s, token[:line], expected, token[:name])
end