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
This commit is contained in:
Ivan Bobev 2020-11-09 11:02:01 +02:00 • committed by GitHub
commit d03f24147a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 0 deletions

View file

@ -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)