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:
parent
5db181f377
commit
d03f24147a
3 changed files with 55 additions and 0 deletions
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue