enumerate.nim 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2020 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements `enumerate` syntactic sugar based on Nim's
  10. ## macro system.
  11. import std/private/since
  12. import macros
  13. macro enumerate*(x: ForLoopStmt): untyped {.since: (1, 3).} =
  14. ## Enumerating iterator for collections.
  15. ##
  16. ## It yields `(count, value)` tuples (which must be immediately unpacked).
  17. ## The default starting count `0` can be manually overridden if needed.
  18. runnableExamples:
  19. let a = [10, 20, 30]
  20. var b: seq[(int, int)]
  21. for i, x in enumerate(a):
  22. b.add((i, x))
  23. assert b == @[(0, 10), (1, 20), (2, 30)]
  24. let c = "abcd"
  25. var d: seq[(int, char)]
  26. for (i, x) in enumerate(97, c):
  27. d.add((i, x))
  28. assert d == @[(97, 'a'), (98, 'b'), (99, 'c'), (100, 'd')]
  29. template genCounter(x): untyped =
  30. # We strip off the first for loop variable and use it as an integer counter.
  31. # We must immediately decrement it by one, because it gets incremented before
  32. # the loop body - to be able to use the final expression in other macros.
  33. newVarStmt(x, infix(countStart, "-", newLit(1)))
  34. template genInc(x): untyped =
  35. newCall(bindSym"inc", x)
  36. expectKind x, nnkForStmt
  37. # check if the starting count is specified:
  38. var countStart = if x[^2].len == 2: newLit(0) else: x[^2][1]
  39. result = newStmtList()
  40. var body = x[^1]
  41. if body.kind != nnkStmtList:
  42. body = newTree(nnkStmtList, body)
  43. var newFor = newTree(nnkForStmt)
  44. if x.len == 3: # single iteration variable
  45. if x[0].kind == nnkVarTuple: # for (x, y, ...) in iter
  46. result.add genCounter(x[0][0])
  47. body.insert(0, genInc(x[0][0]))
  48. for i in 1 .. x[0].len-2:
  49. newFor.add x[0][i]
  50. else:
  51. error("Missing second for loop variable") # for x in iter
  52. else: # for x, y, ... in iter
  53. result.add genCounter(x[0])
  54. body.insert(0, genInc(x[0]))
  55. for i in 1 .. x.len-3:
  56. newFor.add x[i]
  57. # transform enumerate(X) to 'X'
  58. newFor.add x[^2][^1]
  59. newFor.add body
  60. result.add newFor
  61. # now wrap the whole macro in a block to create a new scope
  62. result = newBlockStmt(result)