2021-06-30 06:28:22 +03:00
|
|
|
require_relative "formatter"
|
|
|
|
|
2021-06-28 07:27:35 +03:00
|
|
|
module ErrorHighlight
|
2021-06-18 11:11:39 +03:00
|
|
|
module CoreExt
|
2022-06-07 11:40:03 +03:00
|
|
|
private def generate_snippet
|
2021-06-18 11:11:39 +03:00
|
|
|
locs = backtrace_locations
|
2022-06-07 11:40:03 +03:00
|
|
|
return "" unless locs
|
2021-06-18 11:11:39 +03:00
|
|
|
|
|
|
|
loc = locs.first
|
2022-06-07 11:40:03 +03:00
|
|
|
return "" unless loc
|
|
|
|
|
2021-06-18 11:11:39 +03:00
|
|
|
begin
|
2021-08-20 10:18:36 +03:00
|
|
|
node = RubyVM::AbstractSyntaxTree.of(loc, keep_script_lines: true)
|
2021-06-18 11:11:39 +03:00
|
|
|
opts = {}
|
|
|
|
|
|
|
|
case self
|
|
|
|
when NoMethodError, NameError
|
2021-06-30 06:31:55 +03:00
|
|
|
opts[:point_type] = :name
|
2021-06-18 11:11:39 +03:00
|
|
|
opts[:name] = name
|
|
|
|
when TypeError, ArgumentError
|
2021-06-30 06:31:55 +03:00
|
|
|
opts[:point_type] = :args
|
2021-06-18 11:11:39 +03:00
|
|
|
end
|
|
|
|
|
2021-06-30 06:31:55 +03:00
|
|
|
spot = ErrorHighlight.spot(node, **opts)
|
2021-06-18 11:11:39 +03:00
|
|
|
|
2021-12-18 22:13:14 +03:00
|
|
|
rescue SyntaxError
|
|
|
|
rescue SystemCallError # file not found or something
|
|
|
|
rescue ArgumentError # eval'ed code
|
2021-06-18 11:11:39 +03:00
|
|
|
end
|
|
|
|
|
|
|
|
if spot
|
2022-06-07 11:40:03 +03:00
|
|
|
return ErrorHighlight.formatter.message_for(spot)
|
|
|
|
end
|
|
|
|
|
|
|
|
""
|
|
|
|
end
|
|
|
|
|
|
|
|
if Exception.method_defined?(:detailed_message)
|
|
|
|
def detailed_message(highlight: false, error_highlight: true, **)
|
|
|
|
return super unless error_highlight
|
|
|
|
snippet = generate_snippet
|
|
|
|
if highlight
|
|
|
|
snippet = snippet.gsub(/.+/) { "\e[1m" + $& + "\e[m" }
|
|
|
|
end
|
|
|
|
super + snippet
|
2021-06-18 11:11:39 +03:00
|
|
|
end
|
2022-06-07 11:40:03 +03:00
|
|
|
else
|
|
|
|
# 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
|
2021-06-18 11:11:39 +03:00
|
|
|
|
2022-06-07 11:40:03 +03:00
|
|
|
def to_s
|
|
|
|
msg = super
|
|
|
|
snippet = generate_snippet
|
|
|
|
if snippet != "" && !msg.include?(snippet)
|
|
|
|
msg + snippet
|
|
|
|
else
|
|
|
|
msg
|
|
|
|
end
|
|
|
|
end
|
2021-06-18 11:11:39 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
NameError.prepend(CoreExt)
|
|
|
|
|
2021-06-30 05:44:48 +03:00
|
|
|
# The extension for TypeError/ArgumentError is temporarily disabled due to many test failures
|
|
|
|
|
2021-06-18 11:11:39 +03:00
|
|
|
#TypeError.prepend(CoreExt)
|
|
|
|
#ArgumentError.prepend(CoreExt)
|
|
|
|
end
|