Skip to content

Instantly share code, notes, and snippets.

@codenoid
Forked from mashingan/matchmacro.nim
Created September 11, 2017 07:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codenoid/34a6884e2f64e5057741df53e621cc0d to your computer and use it in GitHub Desktop.
Save codenoid/34a6884e2f64e5057741df53e621cc0d to your computer and use it in GitHub Desktop.
defining match syntax using Nim macro
import macros
macro match(head, body: untyped): untyped =
result = newNimNode nnkStmtList
var casenode = newNimNode nnkCaseStmt
casenode.add head
for node in body:
node.expectKind nnkInfix
var ofbranch: NimNode
case $node[0]
of "->": ofbranch = newNimNode nnkOfBranch
of "=>": ofbranch = newNimNode nnkElifBranch
#var ofbranch = newNimNode nnkOfBranch
for i in 1 ..< node.len:
if i != node.len - 1 or node.kind != nnkStmtList:
ofbranch.add node[i]
else:
ofbranch.add(newStmtList node[i])
casenode.add ofbranch
result.add casenode
expandMacros:
match "3":
"3" -> echo "it's 3"
"4" -> echo "it's 4"
match "3":
"3" -> echo "it's 3"
"4" -> echo "4"
match 3 in @[1, 2, 3]:
true -> echo "it's there"
false -> echo "it's not there"
match "3":
"nice" -> echo "3 is not nice"
3 in @[1, 2, 3] => echo "haha, it works"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment