Created
June 16, 2023 07:00
-
-
Save hamidb80/61bd585d1c0424a09cdc6ba43495d9d1 to your computer and use it in GitHub Desktop.
converts python's way of defining function to Nim way.
This file contains hidden or 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 std/macros | |
import macroplus | |
# ----- impl | |
template emp: untyped = newEmptyNode() | |
func resolveParams(rawParams: openArray[NimNode]): seq[NimNode] = | |
template init = | |
result.add newNimNode nnkIdentDefs | |
init | |
for i, p in rawParams: | |
case p.kind | |
of nnkExprColonExpr: | |
result[^1].add p[0] | |
result[^1].add p[1] | |
result[^1].add emp | |
init | |
of nnkIdent: | |
result[^1].add p | |
else: | |
error "invalid type" | |
discard result.pop | |
macro def(head, body): untyped = | |
assert head.matchInfix "->" | |
let | |
returnType = head[InfixRightSide] | |
other = head[InfixLeftSide] | |
expectKind other, {nnkCall, nnkObjConstr} | |
let | |
fnName = other[CallIdent] | |
params = resolveParams other[CallArgs] | |
newproc fnName, (@[returnType] & params), body | |
# ----- usage | |
def eq(a, b: int, c: bool) -> bool: | |
case c | |
of true: a == b | |
of false: a != b | |
# ----- test | |
echo eq(1, 1, true) | |
echo eq(1, 1, false) | |
echo eq(2, 1, false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment