Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Add Enums module for enum support through the @enum macro #10168

Merged
merged 10 commits into from
Feb 21, 2015
79 changes: 79 additions & 0 deletions base/Enums.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
module Enums

export @enum

abstract Enum

function Base.convert{T<:Integer}(::Type{T},x::Enum)
(x.n < typemin(T) || x.n > typemax(T)) && throw(InexactError())
convert(T, x.n)
end
Base.convert(::Type{BigInt},x::Enum) = big(x.n)
function Base.convert{T<:Enum}(::Type{T},x::Integer)
(x < typemin(T).n || x > typemax(T).n) && throw(InexactError())
T(x)
end
Base.start{T<:Enum}(::Type{T}) = 1
Base.next{T<:Enum}(::Type{T},s) = Base.next(names(T),s)
Base.done{T<:Enum}(::Type{T},s) = Base.done(names(T),s)
# Pass Integer through to Enum constructor through Val{T}
call{T<:Enum}(::Type{T},x::Integer) = T(Val{convert(fieldtype(T,:n),x)})
# Catchall that errors when specific Enum(::Type{Val{n}}) hasn't been defined
call{T<:Enum,n}(::Type{T},::Type{Val{n}}) = error(string("invalid enum value for $T: ",n))

macro enum(T,syms...)
assert(!isempty(syms))
vals = Array((Symbol,Integer),0)
lo = typemax(Int)
hi = typemin(Int)
i = -1
enumT = typeof(i)
for s in syms
i += one(typeof(i))
if isa(s,Symbol)
# pass
elseif isa(s,Expr) && s.head == :(=) && length(s.args) == 2 && isa(s.args[1],Symbol)
i = eval(s.args[2]) # allow exprs, e.g. uint128"1"
s = s.args[1]
else
error(string("invalid syntax in @enum: ",s))
end
push!(vals, (s,i))
I = typeof(i)
enumT = ifelse(length(vals) == 1, I, promote_type(enumT,I))
i < lo && (lo = i)
i > hi && (hi = i)
end
blk = quote
# enum definition
immutable $(esc(T)) <: $(esc(Enum))
n::$(esc(enumT))
end
$(esc(:(Base.typemin)))(x::Type{$(esc(T))}) = $(esc(T))($lo)
$(esc(:(Base.typemax)))(x::Type{$(esc(T))}) = $(esc(T))($hi)
$(esc(:(Base.length)))(x::Type{$(esc(T))}) = $(length(vals))
$(esc(:(Base.names)))(x::Type{$(esc(T))}) = $(esc(T))[]
function $(esc(:(Base.show))){T<:$(esc(T))}(io::IO,x::T)
vals = $vals
for (sym, i) in vals
i = convert($(esc(enumT)), i)
i == x.n && print(io, sym)
end
print(io, "::", T.name)
end
end
for (sym,i) in vals
i = convert(enumT, i)
# add inner constructors to Enum type definition for specific Val{T} values
push!(blk.args[2].args[3].args, :($(esc(T))(::Type{Val{$i}}) = new($i)))
# define enum member constants
push!(blk.args, :(const $(esc(sym)) = $(esc(T))($i)))
# add enum member value to names(T) function
push!(blk.args[10].args[2].args[2].args, :($(esc(sym))))
end
push!(blk.args, :nothing)
blk.head = :toplevel
return blk
end

end # module
3 changes: 2 additions & 1 deletion base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1438,4 +1438,5 @@ export
@noinline,
@doc,
@doc_str,
@doc_mstr
@doc_mstr,
@enum
4 changes: 4 additions & 0 deletions base/sysimg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,10 @@ importall .Profile
include("Dates.jl")
import .Dates: Date, DateTime, now

# enums
include("Enums.jl")
import .Enums: @enum

# deprecated functions
include("deprecated.jl")

Expand Down
130 changes: 130 additions & 0 deletions test/enums.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
module TestEnums

using Base.Test

@test_throws MethodError convert(Base.Enums.Enum, 1.0)

Base.Enums.@enum Fruit apple orange kiwi
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it make more sense to import the @enums macro and then use it bare? I'd expect that we export this from Base if this gets merged.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It actually is exported from Base in this PR, I just tend to write tests as fully qualified as possible :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's fair, although I might argue that the fact that it's exported is something one might want to test for. After all, if it somehow was suddenly deleted from Base's exports that would certainly break a lot of code.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point.

@test typeof(Fruit) == DataType
@test isbits(Fruit)
@test typeof(apple) <: Fruit <: Base.Enums.Enum
@test typeof(apple.n) <: Int
@test int(apple) == 0
@test int(orange) == 1
@test int(kiwi) == 2
@test Fruit(0) == apple
@test Fruit(1) == orange
@test Fruit(2) == kiwi
@test_throws ErrorException Fruit(3)
@test_throws ErrorException Fruit(-1)
@test Fruit(Val{0}) == apple
@test_throws ErrorException Fruit(Val{3})
@test Fruit(0x00) == apple
@test Fruit(big(0)) == apple
@test_throws MethodError Fruit(0.0)
@test start(Fruit) == 1
@test next(Fruit,1) == (apple,2)
@test next(Fruit,2) == (orange,3)
@test next(Fruit,3) == (kiwi,4)
@test !done(Fruit,3)
@test done(Fruit,4)
@test length(Fruit) == 3
@test typemin(Fruit) == apple
@test typemax(Fruit) == kiwi
@test convert(Fruit,0) == apple
@test convert(Fruit,1) == orange
@test convert(Fruit,2) == kiwi
@test_throws InexactError convert(Fruit,3)
@test_throws InexactError convert(Fruit,-1)
@test convert(UInt8,apple) === 0x00
@test convert(UInt16,orange) === 0x0001
@test convert(UInt128,kiwi) === 0x00000000000000000000000000000002
@test typeof(convert(BigInt,apple)) <: BigInt
@test convert(BigInt,apple) == 0
@test convert(Bool,apple) == false
@test convert(Bool,orange) == true
@test_throws InexactError convert(Bool,kiwi)
@test names(Fruit) == [apple, orange, kiwi]

f(x::Fruit) = "hey, I'm a Fruit"
@test f(apple) == "hey, I'm a Fruit"

d = Dict(apple=>"apple",orange=>"orange",kiwi=>"kiwi")
@test d[apple] == "apple"
@test d[orange] == "orange"
@test d[kiwi] == "kiwi"
vals = [apple,orange,kiwi]
for (i,enum) in enumerate(Fruit)
@test enum == vals[i]
end

Base.Enums.@enum(QualityofFrenchFood, ReallyGood)
@test length(QualityofFrenchFood) == 1
@test typeof(ReallyGood) <: QualityofFrenchFood <: Base.Enums.Enum
@test int(ReallyGood) == 0

Base.Enums.@enum Binary _zero=0 _one=1 _two=10 _three=11
@test _zero.n === 0
@test _one.n === 1
@test _two.n === 10
@test _three.n === 11
Base.Enums.@enum Negative _neg1=-1 _neg2=-2
@test _neg1.n === -1
@test _neg2.n === -2
Base.Enums.@enum Negative2 _neg5=-5 _neg4 _neg3
@test _neg5.n === -5
@test _neg4.n === -4
@test _neg3.n === -3

# currently allow silent overflow
Base.Enums.@enum Uint8Overflow ff=0xff overflowed
@test ff.n === 0xff
@test overflowed.n === 0x00

@test_throws MethodError eval(macroexpand(:(Base.Enums.@enum Test1 _zerofp=0.0)))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Am I missing a better way to test error-throwing macros? This felt a little weird.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is pretty much it, but just eval should be sufficient. It does macro expansion.


@test_throws InexactError eval(macroexpand(:(Base.Enums.@enum Test11 _zerofp2=0.5)))
# can't use non-identifiers as enum members
@test_throws ErrorException eval(macroexpand(:(Base.Enums.@enum Test2 1=2)))
# other Integer types of enum members
Base.Enums.@enum Test3 _one_Test3=0x01 _two_Test3=0x02 _three_Test3=0x03
@test typeof(_one_Test3.n) <: UInt8
@test _one_Test3.n === 0x01
@test length(Test3) == 3

Base.Enums.@enum Test4 _one_Test4=0x01 _two_Test4=0x0002 _three_Test4=0x03
@test typeof(_one_Test4.n) <: UInt16

Base.Enums.@enum Test5 _one_Test5=0x01 _two_Test5=0x00000002 _three_Test5=0x00000003
@test typeof(_one_Test5.n) <: UInt32

Base.Enums.@enum Test6 _one_Test6=0x00000000000000000000000000000001 _two_Test6=0x00000000000000000000000000000002
@test typeof(_one_Test6.n) <: UInt128

Base.Enums.@enum Test7 _zero_Test7=0b0 _one_Test7=0b1 _two_Test7=0b10
@test typeof(_zero_Test7.n) <: UInt8

@test_throws MethodError eval(macroexpand(:(Base.Enums.@enum Test8 _zero="zero")))
@test_throws MethodError eval(macroexpand(:(Base.Enums.@enum Test9 _zero='0')))

Base.Enums.@enum Test8 _zero_Test8=zero(Int64)
@test typeof(_zero_Test8.n) <: Int64
@test _zero_Test8.n === Int64(0)

Base.Enums.@enum Test9 _zero_Test9 _one_Test9=0x01 _two_Test9
@test typeof(_zero_Test9.n) <: Int
@test _zero_Test9.n === 0
@test typeof(_one_Test9.n) <: Int
@test _one_Test9.n === 1
@test typeof(_two_Test9.n) <: Int
@test _two_Test9.n === 2

Base.Enums.@enum Test10 _zero_Test10=0x00 _one_Test10 _two_Test10
@test typeof(_zero_Test10.n) <: UInt8
@test _zero_Test10.n === 0x00
@test typeof(_one_Test10.n) <: UInt8
@test _one_Test10.n === 0x01
@test typeof(_two_Test10.n) <: UInt8
@test _two_Test10.n === 0x02

end # module
2 changes: 1 addition & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ testnames = [
"lineedit", "replcompletions", "repl", "replutil", "sets", "test", "goto",
"llvmcall", "grisu", "nullable", "meta", "profile",
"libgit2", "docs", "markdown", "base64", "parser", "serialize", "functors",
"char", "misc"
"char", "misc", "enums"
]

if isdir(joinpath(JULIA_HOME, Base.DOCDIR, "examples"))
Expand Down