I'd like to have something like
type Level = enum
LOW
HIGH
template low*(arg: expr): stmt =
something(Level.LOW,arg)
template high*(arg: expr): stmt =
something(Level.HIGH,arg)
But I don't want to copy and paste the same template declaration code for every kind of "Level". Is it possible to generate those templates automatically?This is an example using macros:
import macros, strutils
macro def*(myEnum: untyped): untyped =
result = newStmtList()
add result, myEnum
# StmtList
# TypeSection # 0
# TypeDef # 0 0
# Ident !"Level" # 0 0 0
# Empty
# EnumTy # 0 0 2
# Empty
# Ident !"HIGH"
# Ident !"LOW"
let name = myEnum[0][0][0]
for item in myEnum[0][0][2]:
if kind(item) != nnkIdent: continue
let n = !toLowerAscii($item)
add result, quote do:
template `n`*(arg: typed): untyped =
something(`name`.`item`, arg)
# echo repr(result)
def:
type Level = enum
LOW
HIGH
template something(level: Level, arg: untyped): untyped =
$level & ": " & arg
echo low("No problems")
echo high("Hope is lost")