summary refs log tree commit diff stats
path: root/tests/macros/tforloop_macro1.nim
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2018-04-15 01:07:28 +0200
committerAndreas Rumpf <rumpf_a@web.de>2018-04-15 01:07:28 +0200
commitc08efb4c512fdd094a0386699cbdb8797d841150 (patch)
tree2ab26024c81f252f122fd1149c4032821a394607 /tests/macros/tforloop_macro1.nim
parenta30b52eb6410bff3430c6a1786761a6ded4cd88d (diff)
downloadNim-c08efb4c512fdd094a0386699cbdb8797d841150.tar.gz
implements first version of for-loop macros
Diffstat (limited to 'tests/macros/tforloop_macro1.nim')
-rw-r--r--tests/macros/tforloop_macro1.nim44
1 files changed, 44 insertions, 0 deletions
diff --git a/tests/macros/tforloop_macro1.nim b/tests/macros/tforloop_macro1.nim
new file mode 100644
index 000000000..a8f45c7ac
--- /dev/null
+++ b/tests/macros/tforloop_macro1.nim
@@ -0,0 +1,44 @@
+discard """
+  output: '''0 1
+1 2
+2 3
+0 1
+1 2
+2 3
+0 1
+1 2
+2 3
+3 5'''
+"""
+
+import macros
+
+macro mymacro(): untyped =
+  result = newLit([1, 2, 3])
+
+for a, b in mymacro():
+  echo a, " ", b
+
+macro enumerate(x: ForLoopStmt): untyped =
+  expectKind x, nnkForStmt
+  # we strip off the first for loop variable and use
+  # it as an integer counter:
+  result = newStmtList()
+  result.add newVarStmt(x[0], newLit(0))
+  var body = x[^1]
+  if body.kind != nnkStmtList:
+    body = newTree(nnkStmtList, body)
+  body.add newCall(bindSym"inc", x[0])
+  var newFor = newTree(nnkForStmt)
+  for i in 1..x.len-3:
+    newFor.add x[i]
+  # transform enumerate(X) to 'X'
+  newFor.add x[^2][1]
+  newFor.add body
+  result.add newFor
+
+for a, b in enumerate(items([1, 2, 3])):
+  echo a, " ", b
+
+for a2, b2 in enumerate([1, 2, 3, 5]):
+  echo a2, " ", b2