Skip to content

Commit

Permalink
add an error hint for min/max on an iterable (#52716)
Browse files Browse the repository at this point in the history
Inspired by the discussion in
https://discourse.julialang.org/t/max-of-a-vector/108294/15

```julia
julia> max([1,2,3])
ERROR: MethodError: no method matching max(::Vector{Int64})
Finding the maximum element of an iterable is performed with `maximum`.
....
```
  • Loading branch information
KristofferC committed Jan 9, 2024
1 parent 17280b2 commit 4b64203
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions base/errorshow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,18 @@ end

Experimental.register_error_hint(string_concatenation_hint_handler, MethodError)


# Display a hint in case the user tries to use the min or max function on an iterable
function min_max_on_iterable(io, ex, arg_types, kwargs)
@nospecialize
if (ex.f === max || ex.f === min) && length(arg_types) == 1 && Base.isiterable(only(arg_types))
f_correct = ex.f === max ? "maximum" : "minimum"
print(io, "\nFinding the $f_correct of an iterable is performed with `$f_correct`.")
end
end

Experimental.register_error_hint(min_max_on_iterable, MethodError)

# ExceptionStack implementation
size(s::ExceptionStack) = size(s.stack)
getindex(s::ExceptionStack, i::Int) = s.stack[i]
Expand Down
10 changes: 10 additions & 0 deletions test/errorshow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ include("testenv.jl")
# re-register only the error hints that are being tested here (
Base.Experimental.register_error_hint(Base.noncallable_number_hint_handler, MethodError)
Base.Experimental.register_error_hint(Base.string_concatenation_hint_handler, MethodError)
Base.Experimental.register_error_hint(Base.min_max_on_iterable, MethodError)

@testset "SystemError" begin
err = try; systemerror("reason", Cint(0)); false; catch ex; ex; end::SystemError
Expand Down Expand Up @@ -998,6 +999,15 @@ let err_str
@test occursin("String concatenation is performed with *", err_str)
end

let err_str
err_str = @except_str min([1,2,3]) MethodError
@test occursin("Finding the minimum of an iterable is performed with `minimum`.", err_str)
err_str = @except_str min((i for i in 1:3)) MethodError
@test occursin("Finding the minimum of an iterable is performed with `minimum`.", err_str)
err_str = @except_str max([1,2,3]) MethodError
@test occursin("Finding the maximum of an iterable is performed with `maximum`.", err_str)
end

@testset "unused argument names" begin
g(::Int) = backtrace()
bt = g(1)
Expand Down

0 comments on commit 4b64203

Please sign in to comment.