I need to use an enum inside a macro, but it is passed inside a stmt list, therefore static is out of question. Seems like i cannot evaluate it on compile time. Any workaround?
proc enumL(enumIdent: NimNode): int =
expectKind enumIdent, nnkIdent
macro m: typed = return enumIdent
return int(low(m()))
My idea is to create a macro that, given a list of numbers/enums that can fit inside an int/long, it will create a new type and procs to store them using bitwise operations. Or, to put it in another way, given this code ...
type MyEnum = enum meA, meB, meC
createType ArrrType:
arg1: 200
arg2: MyEnum
it should produce this:
type ArrrType = int16
proc arg1(at: var ArrrType, a: range[200]) =
proc arg1(at: ArrType): int =
proc arg2(at: var ArrrType, a: MyEnum) =
proc arg2(at: ArrrType): MyEnum =
But using macros, i cannot tell how many bits will 'MyEnum' consume.
Bit count should match enum option count (or lowest byte size which fits them), right? So you could use macros.getType() for this probably...
import macros
type Foo = enum Bar, Baz
macro bitLen(e:typedesc[enum]): untyped =
let ty = getType(e)[1][0] # used 'treeRepr' to find these indices
return newLit(ty.len)
echo "Foo Bit Count: ", Foo.bitLen # prints 'Foo Bit Count: 2'
Simply extract the enum node and count it'd definitions.
I don't know how to do that given only a nimnode of kind nnkIdent. In my example, that would be
arg2: MyEnum
Well you need to put it differently so that Nim has a chance to sem'check it for you and then you can look at the types via getType():
macro createType(t: typed): typed =
discard
createType:
type ArrrType = object
arg1: range[0..200]
arg2: MyEnum