Skip to content

Commit

Permalink
allow use of begin blocks inside enum definitions (#25424)
Browse files Browse the repository at this point in the history
  • Loading branch information
simonbyrne authored and ararslan committed Jan 6, 2018
1 parent 886900c commit dbf0b45
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ New language features
* Field access via dot-syntax can now be overloaded by adding methods to
`Base.getproperty` and `Base.setproperty!` ([#1974]).

* Values for `Enum`s can now be specified inside of a `begin` block when using the
`@enum` macro ([#25424]).

Language changes
----------------

Expand Down Expand Up @@ -1162,3 +1165,4 @@ Command-line option changes
[#25184]: https://github.com/JuliaLang/julia/issues/25184
[#25231]: https://github.com/JuliaLang/julia/issues/25231
[#25365]: https://github.com/JuliaLang/julia/issues/25365
[#25424]: https://github.com/JuliaLang/julia/issues/25424
14 changes: 14 additions & 0 deletions base/Enums.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ julia> f(apple)
"I'm a Fruit with value: 1"
```
Values can also be specified inside a `begin` block, e.g.
```julia
@enum EnumName begin
value1
value2
end
```
`BaseType`, which defaults to [`Int32`](@ref), must be a primitive subtype of `Integer`.
Member values can be converted between the enum type and `BaseType`. `read` and `write`
perform these conversions automatically.
Expand All @@ -69,7 +78,12 @@ macro enum(T, syms...)
lo = hi = 0
i = zero(basetype)
hasexpr = false

if length(syms) == 1 && syms[1] isa Expr && syms[1].head == :block
syms = syms[1].args
end
for s in syms
s isa LineNumberNode && continue
if isa(s, Symbol)
if i == typemin(basetype) && !isempty(vals)
throw(ArgumentError("overflow in value \"$s\" of Enum $typename"))
Expand Down
8 changes: 8 additions & 0 deletions test/enums.jl
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,11 @@ let b = IOBuffer()
seekstart(b)
@test deserialize(b) === apple
end

# test block form
@enum BritishFood begin
blackpudding = 1
scotchegg = 2
haggis = 4
end
@test Int(haggis) == 4

0 comments on commit dbf0b45

Please sign in to comment.