summaryrefslogtreecommitdiff
path: root/lib/error_highlight/core_ext.rb
blob: 1ae180aeac8d5fa63591ec3567a18cb866a5c1de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require_relative "formatter"

module ErrorHighlight
  module CoreExt
    # This is a marker to let `DidYouMean::Correctable#original_message` skip
    # the following method definition of `to_s`.
    # See https://github.com/ruby/did_you_mean/pull/152
    SKIP_TO_S_FOR_SUPER_LOOKUP = true
    private_constant :SKIP_TO_S_FOR_SUPER_LOOKUP

    def to_s
      msg = super.dup

      locs = backtrace_locations
      return msg unless locs

      loc = locs.first
      begin
        node = RubyVM::AbstractSyntaxTree.of(loc, keep_script_lines: true)
        opts = {}

        case self
        when NoMethodError, NameError
          opts[:point_type] = :name
          opts[:name] = name
        when TypeError, ArgumentError
          opts[:point_type] = :args
        end

        spot = ErrorHighlight.spot(node, **opts)

      rescue Errno::ENOENT, SyntaxError
      end

      if spot
        points = ErrorHighlight.formatter.message_for(spot)
        msg << points if !msg.include?(points)
      end

      msg
    end
  end

  NameError.prepend(CoreExt)

  # The extension for TypeError/ArgumentError is temporarily disabled due to many test failures

  #TypeError.prepend(CoreExt)
  #ArgumentError.prepend(CoreExt)
end