Skip to content

Commit 9a5d8bc

Browse files
committed
Do not error when showing invalid enums (#40042)
1 parent 23dbf16 commit 9a5d8bc

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

base/Enums.jl

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,16 @@ Base.isless(x::T, y::T) where {T<:Enum} = isless(basetype(T)(x), basetype(T)(y))
2525

2626
Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol
2727

28-
Base.print(io::IO, x::Enum) = print(io, Symbol(x))
28+
function _symbol(x::Enum)
29+
names = namemap(typeof(x))
30+
x = Integer(x)
31+
get(() -> Symbol("<invalid #$x>"), names, x)::Symbol
32+
end
33+
34+
Base.print(io::IO, x::Enum) = print(io, _symbol(x))
2935

3036
function Base.show(io::IO, x::Enum)
31-
sym = Symbol(x)
37+
sym = _symbol(x)
3238
if !(get(io, :compact, false)::Bool)
3339
from = get(io, :module, Main)
3440
def = typeof(x).name.module

base/tuple.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ function _totuple_err(@nospecialize T)
322322
throw(ArgumentError("too few elements for tuple type $T"))
323323
end
324324

325-
function _totuple(T, itr, s...)
325+
function _totuple(::Type{T}, itr, s::Vararg{Any,N}) where {T,N}
326326
@_inline_meta
327327
y = iterate(itr, s...)
328328
y === nothing && _totuple_err(T)

test/enums.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,10 @@ let io = IOBuffer()
143143
@test String(take!(io)) == sprint(print, Fruit)
144144
end
145145

146+
# Test printing of invalid enums
147+
@test repr("text/plain", reinterpret(Fruit, Int32(11))) == "<invalid #11>::Fruit = 11"
148+
@test repr("text/plain", reinterpret(Fruit, Int32(-5))) == "<invalid #-5>::Fruit = -5"
149+
146150
@enum LogLevel DEBUG INFO WARN ERROR CRITICAL
147151
@test DEBUG < CRITICAL
148152

@@ -160,6 +164,9 @@ end
160164
@test repr("text/plain", sevn) == "$(string(sevn))::UI8 = 0x07"
161165
@test repr("text/plain", fiftn) == "$(string(fiftn))::UI8 = 0xf0"
162166

167+
@test repr("text/plain", reinterpret(UI8, 0x01)) == "<invalid #1>::UI8 = 0x01"
168+
@test repr("text/plain", reinterpret(UI8, 0xff)) == "<invalid #255>::UI8 = 0xff"
169+
163170
# test block form
164171
@enum BritishFood begin
165172
blackpudding = 1

0 commit comments

Comments
 (0)