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

allow use of begin blocks inside enum definitions #25424

Merged
merged 2 commits into from
Jan 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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