diff --git a/NEWS.md b/NEWS.md index cb23c20919ccc..b512e2c1b363b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 ---------------- @@ -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 diff --git a/base/Enums.jl b/base/Enums.jl index 48c7233178359..3e20f055fe175 100644 --- a/base/Enums.jl +++ b/base/Enums.jl @@ -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. @@ -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")) diff --git a/test/enums.jl b/test/enums.jl index 068aafff29e49..97f83810920bf 100644 --- a/test/enums.jl +++ b/test/enums.jl @@ -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