Skip to content

MethodError thrown while preparing to throw InexactError in conversion of Rational to Integer or Complex to Real #55756

Open

Description

Minimal reproducer:

julia> struct A <: Integer end

julia> struct B <: Integer end

julia> Union{A,B}(1//2)
ERROR: MethodError: no method matching nameof(::Type{Union{A, B}})
The function `nameof` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  nameof(::Core.IntrinsicFunction)
   @ Base reflection.jl:2369
  nameof(::Module)
   @ Base essentials.jl:401
  nameof(::UnionAll)
   @ Base reflection.jl:343
  ...

Stacktrace:
 [1] Union{A, B}(x::Rational{Int64})
   @ Base ./rational.jl:151
 [2] top-level scope
   @ REPL[3]:1

It's not valid to call nameof on an arbitrary subtype of Integer, because it may be an Union:

julia/base/rational.jl

Lines 149 to 152 in 945517b

Bool(x::Rational) = x==0 ? false : x==1 ? true :
throw(InexactError(:Bool, Bool, x)) # to resolve ambiguity
(::Type{T})(x::Rational) where {T<:Integer} = (isinteger(x) ? convert(T, x.num)::T :
throw(InexactError(nameof(T), T, x)))

It seems like this could be fixed by simply replacing the nameof call with :convert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    complexComplex numberserror handlingHandling of exceptions by Julia or the usererror messagesBetter, more actionable error messagesrationalsThe Rational type and values thereof

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions