diff options
author | Ivan Bobev <bobeff@protonmail.ch> | 2020-11-09 11:02:01 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-11-09 10:02:01 +0100 |
commit | d03f24147a185091344c67a720a13ca0b3c98dc2 (patch) | |
tree | fdefb9206cb008c9067a64750608ab143dcce569 /lib | |
parent | 5db181f377e30f3a06e70b48e14337722d4dc114 (diff) | |
download | Nim-d03f24147a185091344c67a720a13ca0b3c98dc2.tar.gz |
Add a macro returning enum items count (#15824)
Add a macro `enumLen` which is used to determine the number of items in an enumeration type to the `typetraits.nim` module. Also, add unit tests for it in the `ttypetraits.nim` module. Related to nimlang/Nim#15824
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pure/typetraits.nim | 13 |
1 files changed, 13 insertions, 0 deletions
diff --git a/lib/pure/typetraits.nim b/lib/pure/typetraits.nim index 0a05b5ded..7b6c94cbd 100644 --- a/lib/pure/typetraits.nim +++ b/lib/pure/typetraits.nim @@ -107,6 +107,19 @@ since (1, 3, 5): import std/macros +macro enumLen*(T: typedesc[enum]): int = + ## Returns the number of items in the enum `T`. + + runnableExamples: + type Foo = enum fooItem1 fooItem2 + doAssert Foo.enumLen == 2 + + let bracketExpr = getType(T) + expectKind(bracketExpr, nnkBracketExpr) + let enumTy = bracketExpr[1] + expectKind(enumTy, nnkEnumTy) + result = newLit(enumTy.len - 1) + macro genericParamsImpl(T: typedesc): untyped = # auxiliary macro needed, can't do it directly in `genericParams` result = newNimNode(nnkTupleConstr) |