tforloop_macro1.nim 855 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. discard """
  2. output: '''0 1
  3. 1 2
  4. 2 3
  5. 0 1
  6. 1 2
  7. 2 3
  8. 0 1
  9. 1 2
  10. 2 3
  11. 3 5'''
  12. """
  13. import macros
  14. {.experimental: "forLoopMacros".}
  15. macro mymacro(): untyped =
  16. result = newLit([1, 2, 3])
  17. for a, b in mymacro():
  18. echo a, " ", b
  19. macro enumerate(x: ForLoopStmt): untyped =
  20. expectKind x, nnkForStmt
  21. # we strip off the first for loop variable and use
  22. # it as an integer counter:
  23. result = newStmtList()
  24. result.add newVarStmt(x[0], newLit(0))
  25. var body = x[^1]
  26. if body.kind != nnkStmtList:
  27. body = newTree(nnkStmtList, body)
  28. body.add newCall(bindSym"inc", x[0])
  29. var newFor = newTree(nnkForStmt)
  30. for i in 1..x.len-3:
  31. newFor.add x[i]
  32. # transform enumerate(X) to 'X'
  33. newFor.add x[^2][1]
  34. newFor.add body
  35. result.add newFor
  36. for a, b in enumerate(items([1, 2, 3])):
  37. echo a, " ", b
  38. for a2, b2 in enumerate([1, 2, 3, 5]):
  39. echo a2, " ", b2