Skip to content

Commit 9c50643

Browse files
authored
Add hint in case of missing operator (#40304)
* Add hint for missing operators * Move hint to it's own error type * Clear the hint handler after displaying hint * Don't clear the already empty array in tests * Don't pop the hint handler * Rename handler
1 parent 2ee8c87 commit 9c50643

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

base/errorshow.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,7 @@ function showerror(io::IO, ex::MethodError)
319319
"\nYou can convert to a column vector with the vec() function.")
320320
end
321321
end
322+
Experimental.register_error_hint(noncallable_number_hint_handler, MethodError)
322323
Experimental.show_error_hints(io, ex, arg_types_param, kwargs)
323324
try
324325
show_method_candidates(io, ex, kwargs)
@@ -879,3 +880,14 @@ function show(io::IO, ip::InterpreterIP)
879880
print(io, " in $(ip.code) at statement $(Int(ip.stmt))")
880881
end
881882
end
883+
884+
# handler for displaying a hint in case the user tries to call
885+
# the instance of a number(misses out hte operator)
886+
# eg: (1 + 2)(3 + 4)
887+
function noncallable_number_hint_handler(io, ex, arg_types, kwargs)
888+
if ex.f isa Number
889+
print(io, "\nMaybe you forgot to use an operator such as ")
890+
printstyled(io, "*, ^, %, / etc. ", color=:cyan)
891+
print(io, "?")
892+
end
893+
end

test/errorshow.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,13 @@ catch ex
634634
end
635635
pop!(Base.Experimental._hint_handlers[DomainError]) # order is undefined, don't copy this
636636

637+
let err_str
638+
err_str = @except_str (1 + 2)(3 + 4) MethodError
639+
@test occursin("objects of type $(typeof(3)) are not callable", err_str)
640+
@test occursin("Maybe you forgot to use an operator such as *, ^, %, / etc. ?", err_str)
641+
end
642+
pop!(Base.Experimental._hint_handlers[MethodError]) # order is undefined, don't copy this
643+
637644
# Execute backtrace once before checking formatting, see #38858
638645
backtrace()
639646

0 commit comments

Comments
 (0)