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