I am defining an enum such as @enum myenum enumname1 enumname2 in a module using Julia 0.6. it seems I have to explicitly export both enum type name(myenum) and enum elements(enumname1,enumname2). I know this way is more explicit, but usually we want all elements of an enum type be exported too. is there a way to just do export myenum so that type name and all its elements be exported, or should this behavior be the default for export enum?
macro exported_enum(name, args...)
esc(quote
@enum($name, $(args...))
export $name
$([:(export $arg) for arg in args]...)
end)
end
@exported_enum fruit apple banana
In order to deal with the case where you specify the value of each instances, you may use:
julia> module A
macro exported_enum(T, syms...)
return esc(quote
@enum($T, $(syms...))
export $T
for inst in Symbol.(instances($T))
eval($(Expr(:quote, :(export $(Expr(:$, :inst))))))
end
end)
end
@exported_enum fruit apple=2 banana=3
end
Main.A
julia> using Main.A
julia> fruit
Enum fruit:
apple = 2
banana = 3
sorry for reviving this.
I got the macro to to support a begin end block (with comments)
(I had some help from the ai, as macro definition syntax is a bit of a black art)
eg.
@exported_enum MyEnum begin
#this is a
A
#this is b
B
end
macro exported_enum(name, args...)
if length(args) == 1 && args[1] isa Expr && args[1].head == :block
# Handle the begin ... end block syntax
block = args[1]
# Filter out comments from the block
enum_members = filter(x -> x isa Symbol, block.args)
return esc(quote
@enum $name begin
$(enum_members...)
end
export $name
$([:(export $arg) for arg in enum_members]...)
end)
else
# Handle the standard @enum syntax
return esc(quote
@enum($name, $(args...))
export $name
$([:(export $arg) for arg in args]...)
end)
end
end