Skip to content

Instantly share code, notes, and snippets.

@rayman22201
Created July 3, 2018 05:39
Show Gist options
  • Save rayman22201/003ae414c1943278dfd25460e3098fbf to your computer and use it in GitHub Desktop.
Save rayman22201/003ae414c1943278dfd25460e3098fbf to your computer and use it in GitHub Desktop.
Rewrite Power Operator
import macros
proc rewritePowerOp(node: NimNode): NimNode =
let funcIdent = node[1]
let repeatLit = node[2][0]
echo funcIdent
expectKind(repeatLit, nnkIntLit)
let call = newCall(funcIdent)
for i in 1 ..< node[2].len:
call.add(node[2][i])
let stmts = newStmtList()
for i in 1 .. repeatLit.intVal:
let stmt = newNimNode(nnkDiscardStmt, node)
stmt.add(call)
stmts.add(stmt)
result = newBlockStmt(stmts)
proc findPowerOp(node: NimNode): NimNode =
if node.len < 1:
result = node
else:
result = node
for i in 0 ..< node.len:
echo node[i].kind
case node[i].kind
of nnkInfix:
case node[i][0].kind
of nnkIdent:
if $result[i][0] == "^":
result[i] = rewritePowerOp(node[i])
else:
result[i] = findPowerOp(node[i])
else:
result[i] = findPowerOp(node[i])
macro altPowerSyntax(body: untyped): untyped =
return findPowerOp(body)
proc hexThingy(hex: string): string =
echo "hexify side effect"
return "hexify!"
proc foo(bar: int): int =
echo "another function"
return bar
altPowerSyntax:
hexThingy^4("hi")
foo^3(42)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment