Debian Codegraph @

lib/prism/parse_result/errors.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 # :markup: markdown
3
4 require "stringio"
5
6 module Prism
7 class ParseResult < Result
8 # An object to represent the set of errors on a parse result. This object
9 # can be used to format the errors in a human-readable way.
10 class Errors
11 # The parse result that contains the errors.
12 attr_reader :parse_result
13
14 # Initialize a new set of errors from the given parse result.
15 def initialize(parse_result)
16 @parse_result = parse_result
17 end
18
19 # Formats the errors in a human-readable way and return them as a string.
20 def format
21 error_lines = {} #: Hash[Integer, Array[ParseError]]
22 parse_result.errors.each do |error|
23 location = error.location
24 (location.start_line..location.end_line).each do |line|
25 error_lines[line] ||= []
26 error_lines[line] << error
27 end
28 end
29
30 source_lines = parse_result.source.source.lines
31 source_lines << "" if error_lines.key?(source_lines.size + 1)
32
33 io = StringIO.new
34 source_lines.each.with_index(1) do |line, line_number|
35 io.puts(line)
36
37 (error_lines.delete(line_number) || []).each do |error|
38 location = error.location
39
40 case line_number
41 when location.start_line
42 io.print(" " * location.start_column + "^")
43
44 if location.start_line == location.end_line
45 if location.start_column != location.end_column
46 io.print("~" * (location.end_column - location.start_column - 1))
47 end
48
49 io.puts(" " + error.message)
50 else
51 io.puts("~" * (line.bytesize - location.start_column))
52 end
53 when location.end_line
54 io.puts("~" * location.end_column + " " + error.message)
55 else
56 io.puts("~" * line.bytesize)
57 end
58 end
59 end
60
61 io.puts
62 io.string
63 end
64 end
65 end
66 end