mpushexperimental.nim 734 B

12345678910111213141516171819202122232425262728293031
  1. import macros
  2. macro enumerate(x: ForLoopStmt): untyped =
  3. expectKind x, nnkForStmt
  4. # we strip off the first for loop variable and use
  5. # it as an integer counter:
  6. result = newStmtList()
  7. result.add newVarStmt(x[0], newLit(0))
  8. var body = x[^1]
  9. if body.kind != nnkStmtList:
  10. body = newTree(nnkStmtList, body)
  11. body.add newCall(bindSym"inc", x[0])
  12. var newFor = newTree(nnkForStmt)
  13. for i in 1..x.len-3:
  14. newFor.add x[i]
  15. # transform enumerate(X) to 'X'
  16. newFor.add x[^2][1]
  17. newFor.add body
  18. result.add newFor
  19. proc main*[T](x: T) =
  20. {.push experimental: "forLoopMacros".}
  21. for a, b in enumerate(items([1, 2, 3])):
  22. echo a, " ", b
  23. for a2, b2 in enumerate([1, 2, 3, 5]):
  24. echo a2, " ", b2
  25. {.pop.}