Class: TRuby::ParserCombinator::ParseError

Inherits:
Object
  • Object
show all
Defined in:
lib/t_ruby/parser_combinator/parse_error.rb

Overview

Error Reporting

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(message:, position:, input:) ⇒ ParseError

Returns a new instance of ParseError.



9
10
11
12
13
14
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 9

def initialize(message:, position:, input:)
  @message = message
  @position = position
  @input = input
  @line, @column = calculate_line_column
end

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



7
8
9
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 7

def column
  @column
end

#inputObject (readonly)

Returns the value of attribute input.



7
8
9
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 7

def input
  @input
end

#lineObject (readonly)

Returns the value of attribute line.



7
8
9
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 7

def line
  @line
end

#messageObject (readonly)

Returns the value of attribute message.



7
8
9
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 7

def message
  @message
end

#positionObject (readonly)

Returns the value of attribute position.



7
8
9
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 7

def position
  @position
end

Instance Method Details

#context(lines_before: 2, lines_after: 1) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 20

def context(lines_before: 2, lines_after: 1)
  input_lines = @input.split("\n")
  start_line = [@line - lines_before - 1, 0].max
  end_line = [@line + lines_after - 1, input_lines.length - 1].min

  result = []
  (start_line..end_line).each do |i|
    prefix = i == @line - 1 ? ">>> " : "    "
    result << "#{prefix}#{i + 1}: #{input_lines[i]}"

    if i == @line - 1
      result << "    #{" " * (@column + @line.to_s.length + 1)}^"
    end
  end

  result.join("\n")
end

#to_sObject



16
17
18
# File 'lib/t_ruby/parser_combinator/parse_error.rb', line 16

def to_s
  "Parse error at line #{@line}, column #{@column}: #{@message}"
end