Last active
September 3, 2020 07:20
-
-
Save z-------------/c196206ca1d270aa95e6c3b8d2462cd2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import macros | |
template constDecl(n, t, v): untyped = | |
const n: t = v | |
macro cenum*(t, body: untyped): untyped = | |
var | |
i: BiggestInt = 0 | |
curBaseExpr = newIntLitNode(0) | |
result = newStmtList() | |
for node in body.children: | |
if node.kind == nnkAsgn: # explicit value | |
let | |
name = node[0] | |
rhs = node[1] | |
curBaseExpr = rhs | |
i = 0 | |
result.add(getAst(constDecl(name, t, rhs))) | |
elif node.kind == nnkIdent: # implicit value, i.e. increment previous | |
let name = node | |
var addedExpr = newNimNode(nnkInfix) | |
addedExpr.add( | |
newIdentNode("+"), | |
curBaseExpr, | |
newIntLitNode(i), | |
) | |
result.add(getAst(constDecl(name, t, addedExpr))) | |
i.inc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment