tforloop_macro1.nim 822 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. macro mymacro(): untyped =
  15. result = newLit([1, 2, 3])
  16. for a, b in mymacro():
  17. echo a, " ", b
  18. macro enumerate(x: ForLoopStmt): untyped =
  19. expectKind x, nnkForStmt
  20. # we strip off the first for loop variable and use
  21. # it as an integer counter:
  22. result = newStmtList()
  23. result.add newVarStmt(x[0], newLit(0))
  24. var body = x[^1]
  25. if body.kind != nnkStmtList:
  26. body = newTree(nnkStmtList, body)
  27. body.add newCall(bindSym"inc", x[0])
  28. var newFor = newTree(nnkForStmt)
  29. for i in 1..x.len-3:
  30. newFor.add x[i]
  31. # transform enumerate(X) to 'X'
  32. newFor.add x[^2][1]
  33. newFor.add body
  34. result.add newFor
  35. for a, b in enumerate(items([1, 2, 3])):
  36. echo a, " ", b
  37. for a2, b2 in enumerate([1, 2, 3, 5]):
  38. echo a2, " ", b2