If I have an enumeration type, how can I retrieve the field names associated with that enumeration?
e.g. Given this:
type
Foo = enum
foo = "Foo"
bar = "Bar"
....
I'd like to be able to iterate over the field something like:
for f in Foo.fields:
echo f # "foo", "bar", etc
There is
https://nim-lang.org/docs/iterators.html#fieldPairs.i%2CS%2CT
but I have never used it, and it seems to be not intended for enums.
If I understand you correctly, here you go:
import macros
type
Foo = enum
foo = "Foo"
bar = "Bar"
more = "More"
macro enumFields(n: typed): untyped =
let impl = getType(n)
expectKind impl[1], nnkEnumTy
result = nnkBracket.newTree()
for f in impl[1]:
case f.kind
of nnkSym, nnkIdent:
result.add newLit(f.strVal)
else: discard
for f in enumFields(Foo):
echo f