summary refs log tree commit diff stats
path: root/lib/pure/collections
diff options
context:
space:
mode:
Diffstat (limited to 'lib/pure/collections')
-rw-r--r--lib/pure/collections/deques.nim121
-rw-r--r--lib/pure/collections/hashcommon.nim5
-rw-r--r--lib/pure/collections/heapqueue.nim15
-rw-r--r--lib/pure/collections/lists.nim26
-rw-r--r--lib/pure/collections/sequtils.nim25
-rw-r--r--lib/pure/collections/setimpl.nim4
-rw-r--r--lib/pure/collections/sets.nim10
-rw-r--r--lib/pure/collections/sharedlist.nim2
-rw-r--r--lib/pure/collections/sharedtables.nim2
-rw-r--r--lib/pure/collections/tableimpl.nim33
-rw-r--r--lib/pure/collections/tables.nim59
11 files changed, 229 insertions, 73 deletions
diff --git a/lib/pure/collections/deques.nim b/lib/pure/collections/deques.nim
index ed58028c8..d2b0099f2 100644
--- a/lib/pure/collections/deques.nim
+++ b/lib/pure/collections/deques.nim
@@ -50,7 +50,7 @@ runnableExamples:
 
 import std/private/since
 
-import math
+import std/[assertions, hashes, math]
 
 type
   Deque*[T] = object
@@ -59,20 +59,29 @@ type
     ## To initialize an empty deque,
     ## use the `initDeque proc <#initDeque,int>`_.
     data: seq[T]
-    head, tail, count, mask: int
+
+    # `head` and `tail` are masked only when accessing an element of `data`
+    # so that `tail - head == data.len` when the deque is full.
+    # They are uint so that incrementing/decrementing them doesn't cause
+    # over/underflow. You can get a number of items with `tail - head`
+    # even if `tail` or `head` is wraps around and `tail < head`, because
+    # `tail - head == (uint.high + 1 + tail) - head` when `tail < head`.
+    head, tail: uint
 
 const
   defaultInitialSize* = 4
 
 template initImpl(result: typed, initialSize: int) =
   let correctSize = nextPowerOfTwo(initialSize)
-  result.mask = correctSize - 1
   newSeq(result.data, correctSize)
 
 template checkIfInitialized(deq: typed) =
-  if deq.mask == 0:
+  if deq.data.len == 0:
     initImpl(deq, defaultInitialSize)
 
+func mask[T](deq: Deque[T]): uint {.inline.} =
+  uint(deq.data.len) - 1
+
 proc initDeque*[T](initialSize: int = defaultInitialSize): Deque[T] =
   ## Creates a new empty deque.
   ##
@@ -85,22 +94,22 @@ proc initDeque*[T](initialSize: int = defaultInitialSize): Deque[T] =
   ## * `toDeque proc <#toDeque,openArray[T]>`_
   result.initImpl(initialSize)
 
-proc len*[T](deq: Deque[T]): int {.inline.} =
+func len*[T](deq: Deque[T]): int {.inline.} =
   ## Returns the number of elements of `deq`.
-  result = deq.count
+  int(deq.tail - deq.head)
 
 template emptyCheck(deq) =
   # Bounds check for the regular deque access.
   when compileOption("boundChecks"):
-    if unlikely(deq.count < 1):
+    if unlikely(deq.len < 1):
       raise newException(IndexDefect, "Empty deque.")
 
 template xBoundsCheck(deq, i) =
   # Bounds check for the array like accesses.
   when compileOption("boundChecks"): # `-d:danger` or `--checks:off` should disable this.
-    if unlikely(i >= deq.count): # x < deq.low is taken care by the Natural parameter
+    if unlikely(i >= deq.len): # x < deq.low is taken care by the Natural parameter
       raise newException(IndexDefect,
-                         "Out of bounds: " & $i & " > " & $(deq.count - 1))
+                         "Out of bounds: " & $i & " > " & $(deq.len - 1))
     if unlikely(i < 0): # when used with BackwardsIndex
       raise newException(IndexDefect,
                          "Out of bounds: " & $i & " < 0")
@@ -114,7 +123,7 @@ proc `[]`*[T](deq: Deque[T], i: Natural): lent T {.inline.} =
     doAssertRaises(IndexDefect, echo a[8])
 
   xBoundsCheck(deq, i)
-  return deq.data[(deq.head + i) and deq.mask]
+  return deq.data[(deq.head + i.uint) and deq.mask]
 
 proc `[]`*[T](deq: var Deque[T], i: Natural): var T {.inline.} =
   ## Accesses the `i`-th element of `deq` and returns a mutable
@@ -125,7 +134,7 @@ proc `[]`*[T](deq: var Deque[T], i: Natural): var T {.inline.} =
     assert a[0] == 11
 
   xBoundsCheck(deq, i)
-  return deq.data[(deq.head + i) and deq.mask]
+  return deq.data[(deq.head + i.uint) and deq.mask]
 
 proc `[]=`*[T](deq: var Deque[T], i: Natural, val: sink T) {.inline.} =
   ## Sets the `i`-th element of `deq` to `val`.
@@ -137,7 +146,7 @@ proc `[]=`*[T](deq: var Deque[T], i: Natural, val: sink T) {.inline.} =
 
   checkIfInitialized(deq)
   xBoundsCheck(deq, i)
-  deq.data[(deq.head + i) and deq.mask] = val
+  deq.data[(deq.head + i.uint) and deq.mask] = val
 
 proc `[]`*[T](deq: Deque[T], i: BackwardsIndex): lent T {.inline.} =
   ## Accesses the backwards indexed `i`-th element.
@@ -190,10 +199,8 @@ iterator items*[T](deq: Deque[T]): lent T =
     let a = [10, 20, 30, 40, 50].toDeque
     assert toSeq(a.items) == @[10, 20, 30, 40, 50]
 
-  var i = deq.head
-  for c in 0 ..< deq.count:
-    yield deq.data[i]
-    i = (i + 1) and deq.mask
+  for c in 0 ..< deq.len:
+    yield deq.data[(deq.head + c.uint) and deq.mask]
 
 iterator mitems*[T](deq: var Deque[T]): var T =
   ## Yields every element of `deq`, which can be modified.
@@ -207,10 +214,8 @@ iterator mitems*[T](deq: var Deque[T]): var T =
       x = 5 * x - 1
     assert $a == "[49, 99, 149, 199, 249]"
 
-  var i = deq.head
-  for c in 0 ..< deq.count:
-    yield deq.data[i]
-    i = (i + 1) and deq.mask
+  for c in 0 ..< deq.len:
+    yield deq.data[(deq.head + c.uint) and deq.mask]
 
 iterator pairs*[T](deq: Deque[T]): tuple[key: int, val: T] =
   ## Yields every `(position, value)`-pair of `deq`.
@@ -220,10 +225,8 @@ iterator pairs*[T](deq: Deque[T]): tuple[key: int, val: T] =
     let a = [10, 20, 30].toDeque
     assert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)]
 
-  var i = deq.head
-  for c in 0 ..< deq.count:
-    yield (c, deq.data[i])
-    i = (i + 1) and deq.mask
+  for c in 0 ..< deq.len:
+    yield (c, deq.data[(deq.head + c.uint) and deq.mask])
 
 proc contains*[T](deq: Deque[T], item: T): bool {.inline.} =
   ## Returns true if `item` is in `deq` or false if not found.
@@ -242,8 +245,9 @@ proc contains*[T](deq: Deque[T], item: T): bool {.inline.} =
 
 proc expandIfNeeded[T](deq: var Deque[T]) =
   checkIfInitialized(deq)
-  var cap = deq.mask + 1
-  if unlikely(deq.count >= cap):
+  let cap = deq.data.len
+  assert deq.len <= cap
+  if unlikely(deq.len == cap):
     var n = newSeq[T](cap * 2)
     var i = 0
     for x in mitems(deq):
@@ -251,8 +255,7 @@ proc expandIfNeeded[T](deq: var Deque[T]) =
       else: n[i] = move(x)
       inc i
     deq.data = move(n)
-    deq.mask = cap * 2 - 1
-    deq.tail = deq.count
+    deq.tail = cap.uint
     deq.head = 0
 
 proc addFirst*[T](deq: var Deque[T], item: sink T) =
@@ -267,9 +270,8 @@ proc addFirst*[T](deq: var Deque[T], item: sink T) =
     assert $a == "[50, 40, 30, 20, 10]"
 
   expandIfNeeded(deq)
-  inc deq.count
-  deq.head = (deq.head - 1) and deq.mask
-  deq.data[deq.head] = item
+  dec deq.head
+  deq.data[deq.head and deq.mask] = item
 
 proc addLast*[T](deq: var Deque[T], item: sink T) =
   ## Adds an `item` to the end of `deq`.
@@ -283,9 +285,8 @@ proc addLast*[T](deq: var Deque[T], item: sink T) =
     assert $a == "[10, 20, 30, 40, 50]"
 
   expandIfNeeded(deq)
-  inc deq.count
-  deq.data[deq.tail] = item
-  deq.tail = (deq.tail + 1) and deq.mask
+  deq.data[deq.tail and deq.mask] = item
+  inc deq.tail
 
 proc toDeque*[T](x: openArray[T]): Deque[T] {.since: (1, 3).} =
   ## Creates a new deque that contains the elements of `x` (in the same order).
@@ -314,7 +315,7 @@ proc peekFirst*[T](deq: Deque[T]): lent T {.inline.} =
     assert len(a) == 5
 
   emptyCheck(deq)
-  result = deq.data[deq.head]
+  result = deq.data[deq.head and deq.mask]
 
 proc peekLast*[T](deq: Deque[T]): lent T {.inline.} =
   ## Returns the last element of `deq`, but does not remove it from the deque.
@@ -344,7 +345,7 @@ proc peekFirst*[T](deq: var Deque[T]): var T {.inline, since: (1, 3).} =
     assert $a == "[99, 20, 30, 40, 50]"
 
   emptyCheck(deq)
-  result = deq.data[deq.head]
+  result = deq.data[deq.head and deq.mask]
 
 proc peekLast*[T](deq: var Deque[T]): var T {.inline, since: (1, 3).} =
   ## Returns a mutable reference to the last element of `deq`,
@@ -377,9 +378,8 @@ proc popFirst*[T](deq: var Deque[T]): T {.inline, discardable.} =
     assert $a == "[20, 30, 40, 50]"
 
   emptyCheck(deq)
-  dec deq.count
-  result = move deq.data[deq.head]
-  deq.head = (deq.head + 1) and deq.mask
+  result = move deq.data[deq.head and deq.mask]
+  inc deq.head
 
 proc popLast*[T](deq: var Deque[T]): T {.inline, discardable.} =
   ## Removes and returns the last element of the `deq`.
@@ -394,9 +394,8 @@ proc popLast*[T](deq: var Deque[T]): T {.inline, discardable.} =
     assert $a == "[10, 20, 30, 40]"
 
   emptyCheck(deq)
-  dec deq.count
-  deq.tail = (deq.tail - 1) and deq.mask
-  result = move deq.data[deq.tail]
+  dec deq.tail
+  result = move deq.data[deq.tail and deq.mask]
 
 proc clear*[T](deq: var Deque[T]) {.inline.} =
   ## Resets the deque so that it is empty.
@@ -410,7 +409,6 @@ proc clear*[T](deq: var Deque[T]) {.inline.} =
     assert len(a) == 0
 
   for el in mitems(deq): destroy(el)
-  deq.count = 0
   deq.tail = deq.head
 
 proc shrink*[T](deq: var Deque[T], fromFirst = 0, fromLast = 0) =
@@ -430,19 +428,17 @@ proc shrink*[T](deq: var Deque[T], fromFirst = 0, fromLast = 0) =
     a.shrink(fromFirst = 2, fromLast = 1)
     assert $a == "[30, 40]"
 
-  if fromFirst + fromLast > deq.count:
+  if fromFirst + fromLast > deq.len:
     clear(deq)
     return
 
   for i in 0 ..< fromFirst:
-    destroy(deq.data[deq.head])
-    deq.head = (deq.head + 1) and deq.mask
+    destroy(deq.data[deq.head and deq.mask])
+    inc deq.head
 
   for i in 0 ..< fromLast:
     destroy(deq.data[(deq.tail - 1) and deq.mask])
-    deq.tail = (deq.tail - 1) and deq.mask
-
-  dec deq.count, fromFirst + fromLast
+    dec deq.tail
 
 proc `$`*[T](deq: Deque[T]): string =
   ## Turns a deque into its string representation.
@@ -455,3 +451,30 @@ proc `$`*[T](deq: Deque[T]): string =
     if result.len > 1: result.add(", ")
     result.addQuoted(x)
   result.add("]")
+
+func `==`*[T](deq1, deq2: Deque[T]): bool =
+  ## The `==` operator for Deque.
+  ## Returns `true` if both deques contains the same values in the same order.
+  runnableExamples:
+    var a, b = initDeque[int]()
+    a.addFirst(2)
+    a.addFirst(1)
+    b.addLast(1)
+    b.addLast(2)
+    doAssert a == b
+
+  if deq1.len != deq2.len:
+    return false
+
+  for i in 0 ..< deq1.len:
+    if deq1.data[(deq1.head + i.uint) and deq1.mask] != deq2.data[(deq2.head + i.uint) and deq2.mask]:
+      return false
+
+  true
+
+func hash*[T](deq: Deque[T]): Hash =
+  ## Hashing of Deque.
+  var h: Hash = 0
+  for x in deq:
+    h = h !& hash(x)
+  !$h
diff --git a/lib/pure/collections/hashcommon.nim b/lib/pure/collections/hashcommon.nim
index 8fd4c6e08..17785c8c7 100644
--- a/lib/pure/collections/hashcommon.nim
+++ b/lib/pure/collections/hashcommon.nim
@@ -58,7 +58,10 @@ proc rawGetKnownHC[X, A](t: X, key: A, hc: Hash): int {.inline.} =
 template genHashImpl(key, hc: typed) =
   hc = hash(key)
   if hc == 0: # This almost never taken branch should be very predictable.
-    hc = 314159265 # Value doesn't matter; Any non-zero favorite is fine.
+    when sizeof(int) < 4:
+      hc = 31415 # Value doesn't matter; Any non-zero favorite is fine <= 16-bit.
+    else:
+      hc = 314159265 # Value doesn't matter; Any non-zero favorite is fine.
 
 template genHash(key: typed): Hash =
   var res: Hash
diff --git a/lib/pure/collections/heapqueue.nim b/lib/pure/collections/heapqueue.nim
index bcfdf37c2..96f9b4430 100644
--- a/lib/pure/collections/heapqueue.nim
+++ b/lib/pure/collections/heapqueue.nim
@@ -47,6 +47,9 @@ runnableExamples:
 
 import std/private/since
 
+when defined(nimPreviewSlimSystem):
+  import std/assertions
+
 type HeapQueue*[T] = object
   ## A heap queue, commonly known as a priority queue.
   data: seq[T]
@@ -73,6 +76,13 @@ proc `[]`*[T](heap: HeapQueue[T], i: Natural): lent T {.inline.} =
   ## Accesses the i-th element of `heap`.
   heap.data[i]
 
+iterator items*[T](heap: HeapQueue[T]): lent T {.inline, since: (2, 1, 1).} =
+  ## Iterates over each item of `heap`.
+  let L = len(heap)
+  for i in 0 .. high(heap.data):
+    yield heap.data[i]
+    assert(len(heap) == L, "the length of the HeapQueue changed while iterating over it")
+
 proc heapCmp[T](x, y: T): bool {.inline.} = x < y
 
 proc siftup[T](heap: var HeapQueue[T], startpos, p: int) =
@@ -178,6 +188,11 @@ proc find*[T](heap: HeapQueue[T], x: T): int {.since: (1, 3).} =
   for i in 0 ..< heap.len:
     if heap[i] == x: return i
 
+proc contains*[T](heap: HeapQueue[T], x: T): bool {.since: (2, 1, 1).} =
+  ## Returns true if `x` is in `heap` or false if not found. This is a shortcut
+  ## for `find(heap, x) >= 0`.
+  result = find(heap, x) >= 0
+
 proc del*[T](heap: var HeapQueue[T], index: Natural) =
   ## Removes the element at `index` from `heap`, maintaining the heap invariant.
   runnableExamples:
diff --git a/lib/pure/collections/lists.nim b/lib/pure/collections/lists.nim
index b9d5c48eb..6b88747ef 100644
--- a/lib/pure/collections/lists.nim
+++ b/lib/pure/collections/lists.nim
@@ -384,9 +384,7 @@ proc prependMoved*[T: SomeLinkedList](a, b: var T) {.since: (1, 5, 1).} =
     assert s == [0, 1, 0, 1, 0, 1]
 
   b.addMoved(a)
-  when defined(js): # XXX: swap broken in js; bug #16771
-    (b, a) = (a, b)
-  else: swap a, b
+  swap a, b
 
 proc add*[T](L: var SinglyLinkedList[T], n: SinglyLinkedNode[T]) {.inline.} =
   ## Appends (adds to the end) a node `n` to `L`. Efficiency: O(1).
@@ -983,6 +981,17 @@ func toSinglyLinkedList*[T](elems: openArray[T]): SinglyLinkedList[T] {.since: (
   for elem in elems.items:
     result.add(elem)
 
+func toSinglyLinkedRing*[T](elems: openArray[T]): SinglyLinkedRing[T] =
+  ## Creates a new `SinglyLinkedRing` from the members of `elems`.
+  runnableExamples:
+    from std/sequtils import toSeq
+    let a = [1, 2, 3, 4, 5].toSinglyLinkedRing
+    assert a.toSeq == [1, 2, 3, 4, 5]
+
+  result = initSinglyLinkedRing[T]()
+  for elem in elems.items:
+    result.add(elem)
+
 func toDoublyLinkedList*[T](elems: openArray[T]): DoublyLinkedList[T] {.since: (1, 5, 1).} =
   ## Creates a new `DoublyLinkedList` from the members of `elems`.
   runnableExamples:
@@ -993,3 +1002,14 @@ func toDoublyLinkedList*[T](elems: openArray[T]): DoublyLinkedList[T] {.since: (
   result = initDoublyLinkedList[T]()
   for elem in elems.items:
     result.add(elem)
+
+func toDoublyLinkedRing*[T](elems: openArray[T]): DoublyLinkedRing[T] =
+  ## Creates a new `DoublyLinkedRing` from the members of `elems`.
+  runnableExamples:
+    from std/sequtils import toSeq
+    let a = [1, 2, 3, 4, 5].toDoublyLinkedRing
+    assert a.toSeq == [1, 2, 3, 4, 5]
+
+  result = initDoublyLinkedRing[T]()
+  for elem in elems.items:
+    result.add(elem)
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim
index e2adba910..3c0d8dc0e 100644
--- a/lib/pure/collections/sequtils.nim
+++ b/lib/pure/collections/sequtils.nim
@@ -82,7 +82,8 @@ runnableExamples:
 
 import std/private/since
 
-import macros
+import std/macros
+from std/typetraits import supportsCopyMem
 
 when defined(nimPreviewSlimSystem):
   import std/assertions
@@ -140,6 +141,22 @@ func concat*[T](seqs: varargs[seq[T]]): seq[T] =
       result[i] = itm
       inc(i)
 
+func addUnique*[T](s: var seq[T], x: sink T) =
+  ## Adds `x` to the container `s` if it is not already present. 
+  ## Uses `==` to check if the item is already present.
+  runnableExamples:
+    var a = @[1, 2, 3]
+    a.addUnique(4)
+    a.addUnique(4)
+    assert a == @[1, 2, 3, 4]
+
+  for i in 0..high(s):
+    if s[i] == x: return
+  when declared(ensureMove):
+    s.add ensureMove(x)
+  else:
+    s.add x
+
 func count*[T](s: openArray[T], x: T): int =
   ## Returns the number of occurrences of the item `x` in the container `s`.
   ##
@@ -1086,8 +1103,12 @@ template newSeqWith*(len: int, init: untyped): untyped =
     import std/random
     var seqRand = newSeqWith(20, rand(1.0))
     assert seqRand[0] != seqRand[1]
+  type T = typeof(init)
   let newLen = len
-  var result = newSeq[typeof(init)](newLen)
+  when supportsCopyMem(T) and declared(newSeqUninit):
+    var result = newSeqUninit[T](newLen)
+  else: # TODO: use `newSeqUnsafe` when that's available
+    var result = newSeq[T](newLen)
   for i in 0 ..< newLen:
     result[i] = init
   move(result) # refs bug #7295
diff --git a/lib/pure/collections/setimpl.nim b/lib/pure/collections/setimpl.nim
index dbd4ce1d5..360a075d6 100644
--- a/lib/pure/collections/setimpl.nim
+++ b/lib/pure/collections/setimpl.nim
@@ -87,7 +87,9 @@ proc exclImpl[A](s: var HashSet[A], key: A): bool {.inline.} =
       var j = i # The correctness of this depends on (h+1) in nextTry,
       var r = j # though may be adaptable to other simple sequences.
       s.data[i].hcode = 0 # mark current EMPTY
-      s.data[i].key = default(typeof(s.data[i].key))
+      {.push warning[UnsafeDefault]:off.}
+      reset(s.data[i].key)
+      {.pop.}
       doWhile((i >= r and r > j) or (r > j and j > i) or (j > i and i >= r)):
         i = (i + 1) and msk # increment mod table size
         if isEmpty(s.data[i].hcode): # end of collision cluster; So all done
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim
index 62abd68d4..af13135aa 100644
--- a/lib/pure/collections/sets.nim
+++ b/lib/pure/collections/sets.nim
@@ -50,7 +50,7 @@
 
 
 import
-  hashes, math
+  std/[hashes, math]
 
 when not defined(nimHasEffectsOf):
   {.pragma: effectsOf.}
@@ -382,7 +382,9 @@ proc clear*[A](s: var HashSet[A]) =
   s.counter = 0
   for i in 0 ..< s.data.len:
     s.data[i].hcode = 0
-    s.data[i].key = default(typeof(s.data[i].key))
+    {.push warning[UnsafeDefault]:off.}
+    reset(s.data[i].key)
+    {.pop.}
 
 
 proc union*[A](s1, s2: HashSet[A]): HashSet[A] =
@@ -816,7 +818,9 @@ proc clear*[A](s: var OrderedSet[A]) =
   for i in 0 ..< s.data.len:
     s.data[i].hcode = 0
     s.data[i].next = 0
-    s.data[i].key = default(typeof(s.data[i].key))
+    {.push warning[UnsafeDefault]:off.}
+    reset(s.data[i].key)
+    {.pop.}
 
 proc len*[A](s: OrderedSet[A]): int {.inline.} =
   ## Returns the number of elements in `s`.
diff --git a/lib/pure/collections/sharedlist.nim b/lib/pure/collections/sharedlist.nim
index e61883220..ec8f1cd86 100644
--- a/lib/pure/collections/sharedlist.nim
+++ b/lib/pure/collections/sharedlist.nim
@@ -16,7 +16,7 @@
 {.push stackTrace: off.}
 
 import
-  locks
+  std/locks
 
 const
   ElemsPerNode = 100
diff --git a/lib/pure/collections/sharedtables.nim b/lib/pure/collections/sharedtables.nim
index 8b49066ac..b474ecd31 100644
--- a/lib/pure/collections/sharedtables.nim
+++ b/lib/pure/collections/sharedtables.nim
@@ -17,7 +17,7 @@
 {.deprecated.}
 
 import
-  hashes, math, locks
+  std/[hashes, math, locks]
 
 type
   KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B]
diff --git a/lib/pure/collections/tableimpl.nim b/lib/pure/collections/tableimpl.nim
index 112aaa7d0..3542741fa 100644
--- a/lib/pure/collections/tableimpl.nim
+++ b/lib/pure/collections/tableimpl.nim
@@ -45,7 +45,7 @@ template addImpl(enlarge) {.dirty.} =
   rawInsert(t, t.data, key, val, hc, j)
   inc(t.counter)
 
-template maybeRehashPutImpl(enlarge) {.dirty.} =
+template maybeRehashPutImpl(enlarge, val) {.dirty.} =
   checkIfInitialized()
   if mustRehash(t):
     enlarge(t)
@@ -59,7 +59,7 @@ template putImpl(enlarge) {.dirty.} =
   var hc: Hash = default(Hash)
   var index = rawGet(t, key, hc)
   if index >= 0: t.data[index].val = val
-  else: maybeRehashPutImpl(enlarge)
+  else: maybeRehashPutImpl(enlarge, val)
 
 template mgetOrPutImpl(enlarge) {.dirty.} =
   checkIfInitialized()
@@ -67,17 +67,30 @@ template mgetOrPutImpl(enlarge) {.dirty.} =
   var index = rawGet(t, key, hc)
   if index < 0:
     # not present: insert (flipping index)
-    maybeRehashPutImpl(enlarge)
+    when declared(val):
+      maybeRehashPutImpl(enlarge, val)
+    else:
+      maybeRehashPutImpl(enlarge, default(B))
   # either way return modifiable val
   result = t.data[index].val
 
+# template mgetOrPutDefaultImpl(enlarge) {.dirty.} =
+#   checkIfInitialized()
+#   var hc: Hash = default(Hash)
+#   var index = rawGet(t, key, hc)
+#   if index < 0:
+#     # not present: insert (flipping index)
+#     maybeRehashPutImpl(enlarge, default(B))
+#   # either way return modifiable val
+#   result = t.data[index].val
+
 template hasKeyOrPutImpl(enlarge) {.dirty.} =
   checkIfInitialized()
   var hc: Hash = default(Hash)
   var index = rawGet(t, key, hc)
   if index < 0:
     result = false
-    maybeRehashPutImpl(enlarge)
+    maybeRehashPutImpl(enlarge, val)
   else: result = true
 
 # delImplIdx is KnuthV3 Algo6.4R adapted to i=i+1 (from i=i-1) which has come to
@@ -119,8 +132,10 @@ template delImplIdx(t, i, makeEmpty, cellEmpty, cellHash) =
         var j = i         # The correctness of this depends on (h+1) in nextTry
         var r = j         # though may be adaptable to other simple sequences.
         makeEmpty(i)                     # mark current EMPTY
-        t.data[i].key = default(typeof(t.data[i].key))
-        t.data[i].val = default(typeof(t.data[i].val))
+        {.push warning[UnsafeDefault]:off.}
+        reset(t.data[i].key)
+        reset(t.data[i].val)
+        {.pop.}
         while true:
           i = (i + 1) and msk            # increment mod table size
           if cellEmpty(i):               # end of collision cluster; So all done
@@ -151,8 +166,10 @@ template clearImpl() {.dirty.} =
   for i in 0 ..< t.dataLen:
     when compiles(t.data[i].hcode): # CountTable records don't contain a hcode
       t.data[i].hcode = 0
-    t.data[i].key = default(typeof(t.data[i].key))
-    t.data[i].val = default(typeof(t.data[i].val))
+    {.push warning[UnsafeDefault]:off.}
+    reset(t.data[i].key)
+    reset(t.data[i].val)
+    {.pop.}
   t.counter = 0
 
 template ctAnd(a, b): bool =
diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim
index 39dcddb5a..d414caeed 100644
--- a/lib/pure/collections/tables.nim
+++ b/lib/pure/collections/tables.nim
@@ -194,7 +194,7 @@ runnableExamples:
 
 
 import std/private/since
-import hashes, math, algorithm
+import std/[hashes, math, algorithm]
 
 
 when not defined(nimHasEffectsOf):
@@ -278,6 +278,7 @@ proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
     let
       a = initTable[int, string]()
       b = initTable[char, seq[int]]()
+  result = default(Table[A, B])
   initImpl(result, initialSize)
 
 proc `[]=`*[A, B](t: var Table[A, B], key: A, val: sink B) =
@@ -312,7 +313,7 @@ proc toTable*[A, B](pairs: openArray[(A, B)]): Table[A, B] =
   result = initTable[A, B](pairs.len)
   for key, val in items(pairs): result[key] = val
 
-proc `[]`*[A, B](t: Table[A, B], key: A): B =
+proc `[]`*[A, B](t: Table[A, B], key: A): lent B =
   ## Retrieves the value at `t[key]`.
   ##
   ## If `key` is not in `t`, the `KeyError` exception is raised.
@@ -474,6 +475,18 @@ proc mgetOrPut*[A, B](t: var Table[A, B], key: A, val: B): var B =
 
   mgetOrPutImpl(enlarge)
 
+proc mgetOrPut*[A, B](t: var Table[A, B], key: A): var B =
+  ## Retrieves the value at `t[key]` or puts the
+  ## default initialization value for type `B` (e.g. 0 for any
+  ## integer type).
+  runnableExamples:
+    var a = {'a': 5}.newTable
+    doAssert a.mgetOrPut('a') == 5
+    a.mgetOrPut('z').inc
+    doAssert a == {'a': 5, 'z': 1}.newTable
+
+  mgetOrPutImpl(enlarge)
+
 proc len*[A, B](t: Table[A, B]): int =
   ## Returns the number of keys in `t`.
   runnableExamples:
@@ -1013,6 +1026,18 @@ proc mgetOrPut*[A, B](t: TableRef[A, B], key: A, val: B): var B =
     doAssert t[25] == @[25, 35]
   t[].mgetOrPut(key, val)
 
+proc mgetOrPut*[A, B](t: TableRef[A, B], key: A): var B =
+  ## Retrieves the value at `t[key]` or puts the
+  ## default initialization value for type `B` (e.g. 0 for any
+  ## integer type).
+  runnableExamples:
+    var a = {'a': 5}.newTable
+    doAssert a.mgetOrPut('a') == 5
+    a.mgetOrPut('z').inc
+    doAssert a == {'a': 5, 'z': 1}.newTable
+
+  t[].mgetOrPut(key)
+
 proc len*[A, B](t: TableRef[A, B]): int =
   ## Returns the number of keys in `t`.
   runnableExamples:
@@ -1322,6 +1347,7 @@ proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A,
     let
       a = initOrderedTable[int, string]()
       b = initOrderedTable[char, seq[int]]()
+  result = default(OrderedTable[A, B])
   initImpl(result, initialSize)
 
 proc `[]=`*[A, B](t: var OrderedTable[A, B], key: A, val: sink B) =
@@ -1357,7 +1383,7 @@ proc toOrderedTable*[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B] =
   result = initOrderedTable[A, B](pairs.len)
   for key, val in items(pairs): result[key] = val
 
-proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B =
+proc `[]`*[A, B](t: OrderedTable[A, B], key: A): lent B =
   ## Retrieves the value at `t[key]`.
   ##
   ## If `key` is not in `t`, the  `KeyError` exception is raised.
@@ -1413,7 +1439,7 @@ proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool =
     doAssert a.hasKey('a') == true
     doAssert a.hasKey('z') == false
 
-  var hc: Hash
+  var hc: Hash = default(Hash)
   result = rawGet(t, key, hc) >= 0
 
 proc contains*[A, B](t: OrderedTable[A, B], key: A): bool =
@@ -1503,6 +1529,18 @@ proc mgetOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): var B =
 
   mgetOrPutImpl(enlarge)
 
+proc mgetOrPut*[A, B](t: var OrderedTable[A, B], key: A): var B =
+  ## Retrieves the value at `t[key]` or puts the
+  ## default initialization value for type `B` (e.g. 0 for any
+  ## integer type).
+  runnableExamples:
+    var a = {'a': 5}.toOrderedTable
+    doAssert a.mgetOrPut('a') == 5
+    a.mgetOrPut('z').inc
+    doAssert a == {'a': 5, 'z': 1}.toOrderedTable
+
+  mgetOrPutImpl(enlarge)
+
 proc len*[A, B](t: OrderedTable[A, B]): int {.inline.} =
   ## Returns the number of keys in `t`.
   runnableExamples:
@@ -1992,6 +2030,18 @@ proc mgetOrPut*[A, B](t: OrderedTableRef[A, B], key: A, val: B): var B =
 
   result = t[].mgetOrPut(key, val)
 
+proc mgetOrPut*[A, B](t: OrderedTableRef[A, B], key: A): var B =
+  ## Retrieves the value at `t[key]` or puts the
+  ## default initialization value for type `B` (e.g. 0 for any
+  ## integer type).
+  runnableExamples:
+    var a = {'a': 5}.toOrderedTable
+    doAssert a.mgetOrPut('a') == 5
+    a.mgetOrPut('z').inc
+    doAssert a == {'a': 5, 'z': 1}.toOrderedTable
+
+  t[].mgetOrPut(key)
+
 proc len*[A, B](t: OrderedTableRef[A, B]): int {.inline.} =
   ## Returns the number of keys in `t`.
   runnableExamples:
@@ -2288,6 +2338,7 @@ proc initCountTable*[A](initialSize = defaultInitialSize): CountTable[A] =
   ## * `toCountTable proc<#toCountTable,openArray[A]>`_
   ## * `newCountTable proc<#newCountTable>`_ for creating a
   ##   `CountTableRef`
+  result = default(CountTable[A])
   initImpl(result, initialSize)
 
 proc toCountTable*[A](keys: openArray[A]): CountTable[A] =
=752052e903c8f238a6e3a6f67ae36ee7e0943801'>752052e90 ^
fd4e62990 ^
752052e90 ^






1d47617d1 ^





fd4e62990 ^
752052e90 ^


fd4e62990 ^
e6d17e627 ^
fd4e62990 ^




b4e25a637 ^





fd4e62990 ^
2e5265bef ^
fd4e62990 ^

2e5265bef ^
fd4e62990 ^

2e5265bef ^
10335fd72 ^
2e5265bef ^

10335fd72 ^
2e5265bef ^

10335fd72 ^
2e5265bef ^

fd4e62990 ^
2e5265bef ^



fd4e62990 ^
2e5265bef ^



fd4e62990 ^
2e5265bef ^



fd4e62990 ^
2e5265bef ^



fd4e62990 ^
2e5265bef ^


c7ba6f5eb ^
b5b5e6e76 ^
752052e90 ^
b5b5e6e76 ^







752052e90 ^

fd4e62990 ^
e6d17e627 ^
c7ba6f5eb ^
b5b5e6e76 ^






b4844a189 ^
fd4e62990 ^
e6d17e627 ^
f9426bfcd ^


fd4e62990 ^
9a1be7a9f ^
2e5265bef ^
fd4e62990 ^
752052e90 ^
2e5265bef ^


fd4e62990 ^
2e5265bef ^


fd4e62990 ^
b2f577df2 ^

fd4e62990 ^
b2f577df2 ^





fd4e62990 ^
2e5265bef ^
b2f577df2 ^



2e5265bef ^
fd4e62990 ^
2e5265bef ^
b2f577df2 ^



2e5265bef ^
fd4e62990 ^
2e5265bef ^


4523b29d7 ^
2e5265bef ^



fd4e62990 ^
32d0ac01d ^

fd4e62990 ^
32d0ac01d ^






a6ce70bd8 ^
4523b29d7 ^
f46336ae8 ^
32d0ac01d ^




1b691d874 ^
32d0ac01d ^









a6ce70bd8 ^
fd4e62990 ^
2e5265bef ^


b54dfbce1 ^
2e5265bef ^
fd4e62990 ^
2e5265bef ^




fd4e62990 ^
2e5265bef ^




dc3a0bc00 ^





fd4e62990 ^

2e5265bef ^





1e6aef62b ^
fd4e62990 ^
2e5265bef ^






fd4e62990 ^
2e5265bef ^





fd4e62990 ^
094d7fd4b ^



fd4e62990 ^
094d7fd4b ^



43eae0c11 ^




fd4e62990 ^
094d7fd4b ^



fd4e62990 ^
094d7fd4b ^



1e6aef62b ^
fd4e62990 ^
2e5265bef ^



2e5265bef ^
f9d4e39a1 ^



2e5265bef ^
fd4e62990 ^
2e5265bef ^


fd4e62990 ^
2e5265bef ^



37229df7f ^
2e5265bef ^




b4844a189 ^
2e5265bef ^








fd4e62990 ^
2e5265bef ^







37229df7f ^
2e5265bef ^




99352c1e4 ^

2e5265bef ^
3bfcfeb0c ^




2e5265bef ^


4255eb511 ^
4523b29d7 ^
2e5265bef ^





4255eb511 ^
4523b29d7 ^
2e5265bef ^



4255eb511 ^
74404de12 ^

4255eb511 ^
74404de12 ^

b168a487c ^
fd4e62990 ^
a6ce70bd8 ^
b168a487c ^

fd4e62990 ^
b168a487c ^


fd4e62990 ^
a6ce70bd8 ^


fd4e62990 ^
b168a487c ^

e360d048b ^
fd4e62990 ^
b168a487c ^


fd4e62990 ^
a6ce70bd8 ^
e360d048b ^


fd4e62990 ^
a6ce70bd8 ^
b168a487c ^


fd4e62990 ^
a6ce70bd8 ^



fd4e62990 ^
b168a487c ^

fd4e62990 ^
b168a487c ^



fd4e62990 ^
a6ce70bd8 ^



fd4e62990 ^

7177e0f69 ^










4523b29d7 ^
7177e0f69 ^










4523b29d7 ^
7177e0f69 ^



b0ad08013 ^
b168a487c ^
fd4e62990 ^
b168a487c ^


fd4e62990 ^
b168a487c ^
fd4e62990 ^
a6ce70bd8 ^
b168a487c ^

1e03a7aa8 ^
6a65d1c51 ^
b0ad08013 ^
a6ce70bd8 ^
1e03a7aa8 ^

fd4e62990 ^
b54dfbce1 ^
b168a487c ^
fd4e62990 ^

b168a487c ^
ec86d5db0 ^
a6ce70bd8 ^
ec86d5db0 ^
1e03a7aa8 ^
b168a487c ^








fd4e62990 ^

e360d048b ^

4523b29d7 ^
a6ce70bd8 ^
e360d048b ^







a6ce70bd8 ^
e360d048b ^
fd4e62990 ^
b168a487c ^



fd4e62990 ^
bf205fa85 ^
a6ce70bd8 ^
fd4e62990 ^
1e03a7aa8 ^
b168a487c ^
fd4e62990 ^
1e03a7aa8 ^
b168a487c ^

fd4e62990 ^
1e03a7aa8 ^
b168a487c ^
fd4e62990 ^
1e03a7aa8 ^
b168a487c ^


fd4e62990 ^
b168a487c ^

1e03a7aa8 ^
b168a487c ^
fd4e62990 ^
b168a487c ^
1e03a7aa8 ^
b168a487c ^



2f43fdb83 ^
b54dfbce1 ^
b168a487c ^
fd4e62990 ^
b168a487c ^
3e25d5f24 ^
b168a487c ^

bf205fa85 ^
b168a487c ^

a6ce70bd8 ^
2f43fdb83 ^
b168a487c ^
fd4e62990 ^
a6ce70bd8 ^
3e25d5f24 ^
b168a487c ^





a6ce70bd8 ^
aa1fb9a07 ^
fd4e62990 ^
a6ce70bd8 ^
b168a487c ^
fd4e62990 ^
b168a487c ^



aa1fb9a07 ^

8f5bf0652 ^
bf205fa85 ^
acc80aaed ^

a6ce70bd8 ^
b168a487c ^

fd4e62990 ^
b168a487c ^
b168a487c ^
fd4e62990 ^
b168a487c ^


fd4e62990 ^
4a0aadef4 ^

a6ce70bd8 ^
4523b29d7 ^
4a0aadef4 ^

b168a487c ^
fd4e62990 ^
b168a487c ^
a6ce70bd8 ^
b168a487c ^



fd4e62990 ^
b168a487c ^













fd4e62990 ^
b168a487c ^



a6ce70bd8 ^
a541be893 ^
a6ce70bd8 ^
fd4e62990 ^
b168a487c ^
1e03a7aa8 ^

b168a487c ^
a541be893 ^
b168a487c ^
fd4e62990 ^
b0ad08013 ^

fd4e62990 ^
b0ad08013 ^

fd4e62990 ^

b0ad08013 ^
b168a487c ^
fd4e62990 ^
b168a487c ^


b0ad08013 ^
fd4e62990 ^
b168a487c ^


b0ad08013 ^
fd4e62990 ^

b168a487c ^


fd4e62990 ^
b0ad08013 ^
b168a487c ^

0553758eb ^















b168a487c ^
b0ad08013 ^
b168a487c ^
fd4e62990 ^
b0ad08013 ^
b168a487c ^
a6ce70bd8 ^
b168a487c ^



fd4e62990 ^
b0ad08013 ^

b168a487c ^




094d7fd4b ^
4a0aadef4 ^
1e03a7aa8 ^
b168a487c ^
99352c1e4 ^

4523b29d7 ^
99352c1e4 ^


4523b29d7 ^
99352c1e4 ^




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845

 
                                  
                                         




                                                   
                        






                                                                       
                     





                                                                        
                                                 
                                             
                  
                                                
                                                 


                                                             


                            
                     
                                                      



                                                                 
                                                           
                                                             
                                            



                                                                  
                                                                 
                                                                              
                                

                        
                  


                        
                                            
                                                  


                                  
                                                             
                                       


                                 
              


                                          
                    
                          
                  

                                  

                                             
                                                                      





                                                      

                                                       

                                     
            


                                                                  
 

                                                  
                                                    
                                                                 
                        
                                                        
                                                  
                                      
           
 
                                                

    

                                             
 
                             

                                                                           

               



                                                                         




                                                                        
                                                                         

                            
                                                                     
                

                                       
                                                                    

                                                 
                                                                    
                                          
 
                                                                  
                                      
 
                                                                   
                                 
 
                                                                       
                           
 
                                                          

                                           
                                                                        
                          


                                                       
                                                                  
                                                              

                                                           
 
                                                                          

                                                              
                                                                    

                                        
                                                                       
                                                                             


                                                                             
 
                                                                      






                                                                              





                                                                             
                                                                           


                                                                             
                                                                    
 




                                                                                        





                                                                          
                                                                              
 

                                                                                
 

                                                                              
 
                                                    

                                            
                                                        

                                             
                                                  

                                          
                                                                       



                                           
                                                             



                                        
                                                                 



                                          
                                                          



                                        
                                                        


                                        
 
    
                                                             







                                                                            

                                           
                                                                      
                                               
                                                                         






                                                                     
 
                                                               
                                  


                                                                         
                                                        
                                                                          
 
                                                     
                                                                 


                               
                                                                       


                                                                      
                                             

                                         
                                             





                                                                         
                                                                   
                                                          



                                                                           
 
                                                                   
                                                          



                                                                              
 
                                                                                   


                                                                        
                        



                                        
                                                                             

                                                                             
                                                                           






                                                                               
    
                        
    




                                                                   
                                                                 









                                                                    
 
                                                              


                                                                         
                                                                             
 
                                                          




                                                                          
                                                       




                                                                           





                                                                    

                                                                





                                                                        
                                
                                                                






                                                                        
                                                                





                                                                        
                                                



                                           
                                                      



                                         




                                                
                                                        



                                       
                                                  



                                        
                                 
                                                     



                                                                     
                             



                                                                              
 
                                                            


                                                              
                                                                     



                                     
                                                                  




                                                             
                                               








                                      
                                                            







                                                              
                                                                




                                                         

                                   
       




                                   


                  
                                                              
                                                                      





                                                                          
                                                              
                                                                      



                                                                          
                                                                             

                                             
                                                                             

                                             
 
                                                             
                            

                               
                                                                    


                                             
                                                               


                                                 
                                                                   

                                                  
 
                                                            


                                                           
                                                                 
                          


                                                                    
                                                                 
                          


                                                                    
                                                                   



                                                                   
                                                                 

                                          
                                                          



                                         
                                                            



                                        

                                                                       










                                                                              
                        










                                                                               
                        



                                                             
                                                   
 
                                            


                                
                                                              
                                                  
                                                                    
                                                                        

 
     
                                                                              
                                     
                                                                     

                                     
                                                                   
                                                                  
 

                                                                                    
                                     
    
                                                                      
                                                              
                                 








                                                     

                                                               

                                       
                        
    







                                                             
 
 
                                                         



                                           
                                             
                                
 
                                                        
                        
                      
                                                                
                        

                   
                                                          
                        
                      
                                                                     
                        


                                       
                                                          

                                  
                        
                      
                                                                
                                  
                        



                                          
                                               
                                                                      
 
                                                        
                     
                  

                                
                      

                        
       
                                     
 
                                                                
                    
                  





                                  
                                      
 
                                                           
 
 
                                                  



                                         

                                       
                                
                        

                         
       

                              
                                                                              
                                          
 
                                                   


                        
                                                       

                                                           
    
                        

                                                          
        
                       
                         
              



                   
                                                                













                                             
                                     



                                                       
       
                                                                               
 
                                                           
             

                                             
       
                                                                               
 
                                                                   

                                             
                                                                  

                                            

                                                  
                                           
 
                                                                       


                              
 
                                                                      


                              
 

                                                                         


                                       
                                                    
                                

                           















                                                                    
                                                              
                                       
 
                                                                         
                                            
                                       
                            



                                   
                                                                      

                                                                     




                                     
                                        
                 
                        
 

                                           
                                                                 


                                                      
                          




                                                          
#
#
#            Nim's Runtime Library
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

include "system/inclrtl"

## This module contains the interface to the compiler's abstract syntax
## tree (`AST`:idx:). Macros operate on this tree.

## .. include:: ../doc/astspec.txt

type
  NimNodeKind* = enum
    nnkNone, nnkEmpty, nnkIdent, nnkSym,
    nnkType, nnkCharLit, nnkIntLit, nnkInt8Lit,
    nnkInt16Lit, nnkInt32Lit, nnkInt64Lit, nnkUIntLit, nnkUInt8Lit,
    nnkUInt16Lit, nnkUInt32Lit, nnkUInt64Lit, nnkFloatLit,
    nnkFloat32Lit, nnkFloat64Lit, nnkFloat128Lit, nnkStrLit, nnkRStrLit,
    nnkTripleStrLit, nnkNilLit, nnkMetaNode, nnkDotCall,
    nnkCommand, nnkCall, nnkCallStrLit, nnkInfix,
    nnkPrefix, nnkPostfix, nnkHiddenCallConv,
    nnkExprEqExpr,
    nnkExprColonExpr, nnkIdentDefs, nnkVarTuple,
    nnkPar, nnkObjConstr, nnkCurly, nnkCurlyExpr,
    nnkBracket, nnkBracketExpr, nnkPragmaExpr, nnkRange,
    nnkDotExpr, nnkCheckedFieldExpr, nnkDerefExpr, nnkIfExpr,
    nnkElifExpr, nnkElseExpr, nnkLambda, nnkDo, nnkAccQuoted,
    nnkTableConstr, nnkBind,
    nnkClosedSymChoice,
    nnkOpenSymChoice,
    nnkHiddenStdConv,
    nnkHiddenSubConv, nnkConv, nnkCast, nnkStaticExpr,
    nnkAddr, nnkHiddenAddr, nnkHiddenDeref, nnkObjDownConv,
    nnkObjUpConv, nnkChckRangeF, nnkChckRange64, nnkChckRange,
    nnkStringToCString, nnkCStringToString, nnkAsgn,
    nnkFastAsgn, nnkGenericParams, nnkFormalParams, nnkOfInherit,
    nnkImportAs, nnkProcDef, nnkMethodDef, nnkConverterDef,
    nnkMacroDef, nnkTemplateDef, nnkIteratorDef, nnkOfBranch,
    nnkElifBranch, nnkExceptBranch, nnkElse,
    nnkAsmStmt, nnkPragma, nnkPragmaBlock, nnkIfStmt, nnkWhenStmt,
    nnkForStmt, nnkParForStmt, nnkWhileStmt, nnkCaseStmt,
    nnkTypeSection, nnkVarSection, nnkLetSection, nnkConstSection,
    nnkConstDef, nnkTypeDef,
    nnkYieldStmt, nnkDefer, nnkTryStmt, nnkFinally, nnkRaiseStmt,
    nnkReturnStmt, nnkBreakStmt, nnkContinueStmt, nnkBlockStmt, nnkStaticStmt,
    nnkDiscardStmt, nnkStmtList,
    nnkImportStmt,
    nnkImportExceptStmt,
    nnkExportStmt,
    nnkExportExceptStmt,
    nnkFromStmt,
    nnkIncludeStmt,
    nnkBindStmt, nnkMixinStmt, nnkUsingStmt,
    nnkCommentStmt, nnkStmtListExpr, nnkBlockExpr,
    nnkStmtListType, nnkBlockType,
    nnkWith, nnkWithout,
    nnkTypeOfExpr, nnkObjectTy,
    nnkTupleTy, nnkTupleClassTy, nnkTypeClassTy, nnkStaticTy,
    nnkRecList, nnkRecCase, nnkRecWhen,
    nnkRefTy, nnkPtrTy, nnkVarTy,
    nnkConstTy, nnkMutableTy,
    nnkDistinctTy,
    nnkProcTy,
    nnkIteratorTy,         # iterator type
    nnkSharedTy,           # 'shared T'
    nnkEnumTy,
    nnkEnumFieldDef,
    nnkArglist, nnkPattern
    nnkReturnToken
  NimNodeKinds* = set[NimNodeKind]
  NimTypeKind* = enum
    ntyNone, ntyBool, ntyChar, ntyEmpty,
    ntyArrayConstr, ntyNil, ntyExpr, ntyStmt,
    ntyTypeDesc, ntyGenericInvocation, ntyGenericBody, ntyGenericInst,
    ntyGenericParam, ntyDistinct, ntyEnum, ntyOrdinal,
    ntyArray, ntyObject, ntyTuple, ntySet,
    ntyRange, ntyPtr, ntyRef, ntyVar,
    ntySequence, ntyProc, ntyPointer, ntyOpenArray,
    ntyString, ntyCString, ntyForward, ntyInt,
    ntyInt8, ntyInt16, ntyInt32, ntyInt64,
    ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128,
    ntyUInt, ntyUInt8, ntyUInt16, ntyUInt32, ntyUInt64,
    ntyBigNum,
    ntyConst, ntyMutable, ntyVarargs,
    ntyIter,
    ntyError,
    ntyBuiltinTypeClass, ntyConcept, ntyConceptInst, ntyComposite,
    ntyAnd, ntyOr, ntyNot

  TNimTypeKinds* {.deprecated.} = set[NimTypeKind]
  NimSymKind* = enum
    nskUnknown, nskConditional, nskDynLib, nskParam,
    nskGenericParam, nskTemp, nskModule, nskType, nskVar, nskLet,
    nskConst, nskResult,
    nskProc, nskMethod, nskIterator, nskClosureIterator,
    nskConverter, nskMacro, nskTemplate, nskField,
    nskEnumField, nskForVar, nskLabel,
    nskStub

  TNimSymKinds* {.deprecated.} = set[NimSymKind]

type
  NimIdent* = object of RootObj
    ## represents a Nim identifier in the AST

  NimSymObj = object # hidden
  NimSym* = ref NimSymObj
    ## represents a Nim *symbol* in the compiler; a *symbol* is a looked-up
    ## *ident*.

{.deprecated: [TNimrodNodeKind: NimNodeKind, TNimNodeKinds: NimNodeKinds,
    TNimrodTypeKind: NimTypeKind, TNimrodSymKind: NimSymKind,
    TNimrodIdent: NimIdent, PNimrodSymbol: NimSym].}

const
  nnkLiterals* = {nnkCharLit..nnkNilLit}
  nnkCallKinds* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand,
                   nnkCallStrLit}

proc `[]`*(n: NimNode, i: int): NimNode {.magic: "NChild", noSideEffect.}
  ## get `n`'s `i`'th child.

proc `[]=`*(n: NimNode, i: int, child: NimNode) {.magic: "NSetChild",
  noSideEffect.}
  ## set `n`'s `i`'th child to `child`.

proc `!`*(s: string): NimIdent {.magic: "StrToIdent", noSideEffect.}
  ## constructs an identifier from the string `s`

proc `$`*(i: NimIdent): string {.magic: "IdentToStr", noSideEffect.}
  ## converts a Nim identifier to a string

proc `$`*(s: NimSym): string {.magic: "IdentToStr", noSideEffect.}
  ## converts a Nim symbol to a string

proc `==`*(a, b: NimIdent): bool {.magic: "EqIdent", noSideEffect.}
  ## compares two Nim identifiers

proc `==`*(a, b: NimNode): bool {.magic: "EqNimrodNode", noSideEffect.}
  ## compares two Nim nodes

proc len*(n: NimNode): int {.magic: "NLen", noSideEffect.}
  ## returns the number of children of `n`.

proc add*(father, child: NimNode): NimNode {.magic: "NAdd", discardable,
  noSideEffect, locks: 0.}
  ## Adds the `child` to the `father` node. Returns the
  ## father node so that calls can be nested.

proc add*(father: NimNode, children: varargs[NimNode]): NimNode {.
  magic: "NAddMultiple", discardable, noSideEffect, locks: 0.}
  ## Adds each child of `children` to the `father` node.
  ## Returns the `father` node so that calls can be nested.

proc del*(father: NimNode, idx = 0, n = 1) {.magic: "NDel", noSideEffect.}
  ## deletes `n` children of `father` starting at index `idx`.

proc kind*(n: NimNode): NimNodeKind {.magic: "NKind", noSideEffect.}
  ## returns the `kind` of the node `n`.

proc intVal*(n: NimNode): BiggestInt {.magic: "NIntVal", noSideEffect.}
proc boolVal*(n: NimNode): bool {.compileTime, noSideEffect.} = n.intVal != 0
proc floatVal*(n: NimNode): BiggestFloat {.magic: "NFloatVal", noSideEffect.}
proc symbol*(n: NimNode): NimSym {.magic: "NSymbol", noSideEffect.}
proc ident*(n: NimNode): NimIdent {.magic: "NIdent", noSideEffect.}

proc getType*(n: NimNode): NimNode {.magic: "NGetType", noSideEffect.}
  ## with 'getType' you can access the node's `type`:idx:. A Nim type is
  ## mapped to a Nim AST too, so it's slightly confusing but it means the same
  ## API can be used to traverse types. Recursive types are flattened for you
  ## so there is no danger of infinite recursions during traversal. To
  ## resolve recursive types, you have to call 'getType' again. To see what
  ## kind of type it is, call `typeKind` on getType's result.

proc getType*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.}
  ## Returns the Nim type node for given type. This can be used to turn macro
  ## typedesc parameter into proper NimNode representing type, since typedesc
  ## are an exception in macro calls - they are not mapped implicitly to
  ## NimNode like any other arguments.

proc typeKind*(n: NimNode): NimTypeKind {.magic: "NGetType", noSideEffect.}
  ## Returns the type kind of the node 'n' that should represent a type, that
  ## means the node should have been obtained via `getType`.

proc strVal*(n: NimNode): string  {.magic: "NStrVal", noSideEffect.}

proc `intVal=`*(n: NimNode, val: BiggestInt) {.magic: "NSetIntVal", noSideEffect.}
proc `floatVal=`*(n: NimNode, val: BiggestFloat) {.magic: "NSetFloatVal", noSideEffect.}
proc `symbol=`*(n: NimNode, val: NimSym) {.magic: "NSetSymbol", noSideEffect.}
proc `ident=`*(n: NimNode, val: NimIdent) {.magic: "NSetIdent", noSideEffect.}
#proc `typ=`*(n: NimNode, typ: typedesc) {.magic: "NSetType".}
# this is not sound! Unfortunately forbidding 'typ=' is not enough, as you
# can easily do:
#   let bracket = semCheck([1, 2])
#   let fake = semCheck(2.0)
#   bracket[0] = fake  # constructs a mixed array with ints and floats!

proc `strVal=`*(n: NimNode, val: string) {.magic: "NSetStrVal", noSideEffect.}

proc newNimNode*(kind: NimNodeKind,
                 n: NimNode=nil): NimNode {.magic: "NNewNimNode", noSideEffect.}

proc copyNimNode*(n: NimNode): NimNode {.magic: "NCopyNimNode", noSideEffect.}
proc copyNimTree*(n: NimNode): NimNode {.magic: "NCopyNimTree", noSideEffect.}

proc error*(msg: string) {.magic: "NError", benign.}
  ## writes an error message at compile time

proc warning*(msg: string) {.magic: "NWarning", benign.}
  ## writes a warning message at compile time

proc hint*(msg: string) {.magic: "NHint", benign.}
  ## writes a hint message at compile time

proc newStrLitNode*(s: string): NimNode {.compileTime, noSideEffect.} =
  ## creates a string literal node from `s`
  result = newNimNode(nnkStrLit)
  result.strVal = s

proc newIntLitNode*(i: BiggestInt): NimNode {.compileTime.} =
  ## creates a int literal node from `i`
  result = newNimNode(nnkIntLit)
  result.intVal = i

proc newFloatLitNode*(f: BiggestFloat): NimNode {.compileTime.} =
  ## creates a float literal node from `f`
  result = newNimNode(nnkFloatLit)
  result.floatVal = f

proc newIdentNode*(i: NimIdent): NimNode {.compileTime.} =
  ## creates an identifier node from `i`
  result = newNimNode(nnkIdent)
  result.ident = i

proc newIdentNode*(i: string): NimNode {.compileTime.} =
  ## creates an identifier node from `i`
  result = newNimNode(nnkIdent)
  result.ident = !i

type
  BindSymRule* = enum    ## specifies how ``bindSym`` behaves
    brClosed,            ## only the symbols in current scope are bound
    brOpen,              ## open wrt overloaded symbols, but may be a single
                         ## symbol if not ambiguous (the rules match that of
                         ## binding in generics)
    brForceOpen          ## same as brOpen, but it will always be open even
                         ## if not ambiguous (this cannot be achieved with
                         ## any other means in the language currently)

{.deprecated: [TBindSymRule: BindSymRule].}

proc bindSym*(ident: string, rule: BindSymRule = brClosed): NimNode {.
              magic: "NBindSym", noSideEffect.}
  ## creates a node that binds `ident` to a symbol node. The bound symbol
  ## may be an overloaded symbol.
  ## If ``rule == brClosed`` either an ``nkClosedSymChoice`` tree is
  ## returned or ``nkSym`` if the symbol is not ambiguous.
  ## If ``rule == brOpen`` either an ``nkOpenSymChoice`` tree is
  ## returned or ``nkSym`` if the symbol is not ambiguous.
  ## If ``rule == brForceOpen`` always an ``nkOpenSymChoice`` tree is
  ## returned even if the symbol is not ambiguous.

proc genSym*(kind: NimSymKind = nskLet; ident = ""): NimNode {.
  magic: "NGenSym", noSideEffect.}
  ## generates a fresh symbol that is guaranteed to be unique. The symbol
  ## needs to occur in a declaration context.

proc callsite*(): NimNode {.magic: "NCallSite", benign.}
  ## returns the AST of the invocation expression that invoked this macro.

proc toStrLit*(n: NimNode): NimNode {.compileTime.} =
  ## converts the AST `n` to the concrete Nim code and wraps that
  ## in a string literal node
  return newStrLitNode(repr(n))

proc lineinfo*(n: NimNode): string {.magic: "NLineInfo", noSideEffect.}
  ## returns the position the node appears in the original source file
  ## in the form filename(line, col)

proc internalParseExpr(s: string): NimNode {.
  magic: "ParseExprToAst", noSideEffect.}

proc internalParseStmt(s: string): NimNode {.
  magic: "ParseStmtToAst", noSideEffect.}

proc internalErrorFlag*(): string {.magic: "NError", noSideEffect.}
  ## Some builtins set an error flag. This is then turned into a proper
  ## exception. **Note**: Ordinary application code should not call this.

proc parseExpr*(s: string): NimNode {.noSideEffect, compileTime.} =
  ## Compiles the passed string to its AST representation.
  ## Expects a single expression. Raises ``ValueError`` for parsing errors.
  result = internalParseExpr(s)
  let x = internalErrorFlag()
  if x.len > 0: raise newException(ValueError, x)

proc parseStmt*(s: string): NimNode {.noSideEffect, compileTime.} =
  ## Compiles the passed string to its AST representation.
  ## Expects one or more statements. Raises ``ValueError`` for parsing errors.
  result = internalParseStmt(s)
  let x = internalErrorFlag()
  if x.len > 0: raise newException(ValueError, x)

proc getAst*(macroOrTemplate: expr): NimNode {.magic: "ExpandToAst", noSideEffect.}
  ## Obtains the AST nodes returned from a macro or template invocation.
  ## Example:
  ##
  ## .. code-block:: nim
  ##
  ##   macro FooMacro() =
  ##     var ast = getAst(BarTemplate())

proc quote*(bl: stmt, op = "``"): NimNode {.magic: "QuoteAst", noSideEffect.}
  ## Quasi-quoting operator.
  ## Accepts an expression or a block and returns the AST that represents it.
  ## Within the quoted AST, you are able to interpolate NimNode expressions
  ## from the surrounding scope. If no operator is given, quoting is done using
  ## backticks. Otherwise, the given operator must be used as a prefix operator
  ## for any interpolated expression. The original meaning of the interpolation
  ## operator may be obtained by escaping it (by prefixing it with itself):
  ## e.g. `@` is escaped as `@@`, `@@` is escaped as `@@@` and so on.
  ##
  ## Example:
  ##
  ## .. code-block:: nim
  ##
  ##   macro check(ex: expr): stmt =
  ##     # this is a simplified version of the check macro from the
  ##     # unittest module.
  ##
  ##     # If there is a failed check, we want to make it easy for
  ##     # the user to jump to the faulty line in the code, so we
  ##     # get the line info here:
  ##     var info = ex.lineinfo
  ##
  ##     # We will also display the code string of the failed check:
  ##     var expString = ex.toStrLit
  ##
  ##     # Finally we compose the code to implement the check:
  ##     result = quote do:
  ##       if not `ex`:
  ##         echo `info` & ": Check failed: " & `expString`

proc expectKind*(n: NimNode, k: NimNodeKind) {.compileTime.} =
  ## checks that `n` is of kind `k`. If this is not the case,
  ## compilation aborts with an error message. This is useful for writing
  ## macros that check the AST that is passed to them.
  if n.kind != k: error("Expected a node of kind " & $k & ", got " & $n.kind)

proc expectMinLen*(n: NimNode, min: int) {.compileTime.} =
  ## checks that `n` has at least `min` children. If this is not the case,
  ## compilation aborts with an error message. This is useful for writing
  ## macros that check its number of arguments.
  if n.len < min: error("macro expects a node with " & $min & " children")

proc expectLen*(n: NimNode, len: int) {.compileTime.} =
  ## checks that `n` has exactly `len` children. If this is not the case,
  ## compilation aborts with an error message. This is useful for writing
  ## macros that check its number of arguments.
  if n.len != len: error("macro expects a node with " & $len & " children")

proc newTree*(kind: NimNodeKind,
              children: varargs[NimNode]): NimNode {.compileTime.} =
  ## produces a new node with children.
  result = newNimNode(kind)
  result.add(children)

proc newCall*(theProc: NimNode,
              args: varargs[NimNode]): NimNode {.compileTime.} =
  ## produces a new call node. `theProc` is the proc that is called with
  ## the arguments ``args[0..]``.
  result = newNimNode(nnkCall)
  result.add(theProc)
  result.add(args)

proc newCall*(theProc: NimIdent,
              args: varargs[NimNode]): NimNode {.compileTime.} =
  ## produces a new call node. `theProc` is the proc that is called with
  ## the arguments ``args[0..]``.
  result = newNimNode(nnkCall)
  result.add(newIdentNode(theProc))
  result.add(args)

proc newCall*(theProc: string,
              args: varargs[NimNode]): NimNode {.compileTime.} =
  ## produces a new call node. `theProc` is the proc that is called with
  ## the arguments ``args[0..]``.
  result = newNimNode(nnkCall)
  result.add(newIdentNode(theProc))
  result.add(args)

proc newLit*(c: char): NimNode {.compileTime.} =
  ## produces a new character literal node.
  result = newNimNode(nnkCharLit)
  result.intVal = ord(c)

proc newLit*(i: BiggestInt): NimNode {.compileTime.} =
  ## produces a new integer literal node.
  result = newNimNode(nnkIntLit)
  result.intVal = i

proc newLit*(b: bool): NimNode {.compileTime.} =
  ## produces a new boolean literal node.
  result = newNimNode(nnkIntLit)
  result.intVal = ord(b)

proc newLit*(f: BiggestFloat): NimNode {.compileTime.} =
  ## produces a new float literal node.
  result = newNimNode(nnkFloatLit)
  result.floatVal = f

proc newLit*(s: string): NimNode {.compileTime.} =
  ## produces a new string literal node.
  result = newNimNode(nnkStrLit)
  result.strVal = s

proc nestList*(theProc: NimIdent,
               x: NimNode): NimNode {.compileTime.} =
  ## nests the list `x` into a tree of call expressions:
  ## ``[a, b, c]`` is transformed into ``theProc(a, theProc(c, d))``.
  var L = x.len
  result = newCall(theProc, x[L-2], x[L-1])
  for i in countdown(L-3, 0):
    # XXX the 'copyNimTree' here is necessary due to a bug in the evaluation
    # engine that would otherwise create an endless loop here. :-(
    # This could easily user code and so should be fixed in evals.nim somehow.
    result = newCall(theProc, x[i], copyNimTree(result))

proc treeRepr*(n: NimNode): string {.compileTime, benign.} =
  ## Convert the AST `n` to a human-readable tree-like string.
  ##
  ## See also `repr` and `lispRepr`.
  proc traverse(res: var string, level: int, n: NimNode) {.benign.} =
    for i in 0..level-1: res.add "  "
    res.add(($n.kind).substr(3))

    case n.kind
    of nnkEmpty: discard # same as nil node in this representation
    of nnkNilLit: res.add(" nil")
    of nnkCharLit..nnkInt64Lit: res.add(" " & $n.intVal)
    of nnkFloatLit..nnkFloat64Lit: res.add(" " & $n.floatVal)
    of nnkStrLit..nnkTripleStrLit: res.add(" " & $n.strVal)
    of nnkIdent: res.add(" !\"" & $n.ident & '"')
    of nnkSym: res.add(" \"" & $n.symbol & '"')
    of nnkNone: assert false
    else:
      for j in 0..n.len-1:
        res.add "\n"
        traverse(res, level + 1, n[j])

  result = ""
  traverse(result, 0, n)

proc lispRepr*(n: NimNode): string {.compileTime, benign.} =
  ## Convert the AST `n` to a human-readable lisp-like string,
  ##
  ## See also `repr` and `treeRepr`.

  result = ($n.kind).substr(3)
  add(result, "(")

  case n.kind
  of nnkEmpty: discard # same as nil node in this representation
  of nnkNilLit: add(result, "nil")
  of nnkCharLit..nnkInt64Lit: add(result, $n.intVal)
  of nnkFloatLit..nnkFloat64Lit: add(result, $n.floatVal)
  of nnkStrLit..nnkTripleStrLit: add(result, $n.strVal)
  of nnkIdent: add(result, "!\"" & $n.ident & '"')
  of nnkSym: add(result, $n.symbol)
  of nnkNone: assert false
  else:
    if n.len > 0:
      add(result, lispRepr(n[0]))
      for j in 1..n.len-1:
        add(result, ", ")
        add(result, lispRepr(n[j]))

  add(result, ")")

macro dumpTree*(s: stmt): stmt {.immediate.} = echo s.treeRepr
  ## Accepts a block of nim code and prints the parsed abstract syntax
  ## tree using the `toTree` function. Printing is done *at compile time*.
  ##
  ## You can use this as a tool to explore the Nimrod's abstract syntax
  ## tree and to discover what kind of nodes must be created to represent
  ## a certain expression/statement.

macro dumpLisp*(s: stmt): stmt {.immediate.} = echo s.lispRepr
  ## Accepts a block of nim code and prints the parsed abstract syntax
  ## tree using the `toLisp` function. Printing is done *at compile time*.
  ##
  ## See `dumpTree`.

macro dumpTreeImm*(s: stmt): stmt {.immediate, deprecated.} = echo s.treeRepr
  ## The ``immediate`` version of `dumpTree`.

macro dumpLispImm*(s: stmt): stmt {.immediate, deprecated.} = echo s.lispRepr
  ## The ``immediate`` version of `dumpLisp`.


proc newEmptyNode*(): NimNode {.compileTime, noSideEffect.} =
  ## Create a new empty node
  result = newNimNode(nnkEmpty)

proc newStmtList*(stmts: varargs[NimNode]): NimNode {.compileTime.}=
  ## Create a new statement list
  result = newNimNode(nnkStmtList).add(stmts)

proc newPar*(exprs: varargs[NimNode]): NimNode {.compileTime.}=
  ## Create a new parentheses-enclosed expression
  newNimNode(nnkPar).add(exprs)

proc newBlockStmt*(label, body: NimNode): NimNode {.compileTime.} =
  ## Create a new block statement with label
  return newNimNode(nnkBlockStmt).add(label, body)

proc newBlockStmt*(body: NimNode): NimNode {.compiletime.} =
  ## Create a new block: stmt
  return newNimNode(nnkBlockStmt).add(newEmptyNode(), body)

proc newVarStmt*(name, value: NimNode): NimNode {.compiletime.} =
  ## Create a new var stmt
  return newNimNode(nnkVarSection).add(
    newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))

proc newLetStmt*(name, value: NimNode): NimNode {.compiletime.} =
  ## Create a new let stmt
  return newNimNode(nnkLetSection).add(
    newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))

proc newConstStmt*(name, value: NimNode): NimNode {.compileTime.} =
  ## Create a new const stmt
  newNimNode(nnkConstSection).add(
    newNimNode(nnkConstDef).add(name, newNimNode(nnkEmpty), value))

proc newAssignment*(lhs, rhs: NimNode): NimNode {.compileTime.} =
  return newNimNode(nnkAsgn).add(lhs, rhs)

proc newDotExpr*(a, b: NimNode): NimNode {.compileTime.} =
  ## Create new dot expression
  ## a.dot(b) ->  `a.b`
  return newNimNode(nnkDotExpr).add(a, b)

proc newColonExpr*(a, b: NimNode): NimNode {.compileTime.} =
  ## Create new colon expression
  ## newColonExpr(a, b) ->  `a: b`
  newNimNode(nnkExprColonExpr).add(a, b)

proc newIdentDefs*(name, kind: NimNode;
                   default = newEmptyNode()): NimNode {.compileTime.} =
  ## Creates a new ``nnkIdentDefs`` node of a specific kind and value.
  ##
  ## ``nnkIdentDefs`` need to have at least three children, but they can have
  ## more: first comes a list of identifiers followed by a type and value
  ## nodes. This helper proc creates a three node subtree, the first subnode
  ## being a single identifier name. Both the ``kind`` node and ``default``
  ## (value) nodes may be empty depending on where the ``nnkIdentDefs``
  ## appears: tuple or object definitions will have an empty ``default`` node,
  ## ``let`` or ``var`` blocks may have an empty ``kind`` node if the
  ## identifier is being assigned a value. Example:
  ##
  ## .. code-block:: nim
  ##
  ##   var varSection = newNimNode(nnkVarSection).add(
  ##     newIdentDefs(ident("a"), ident("string")),
  ##     newIdentDefs(ident("b"), newEmptyNode(), newLit(3)))
  ##   # --> var
  ##   #       a: string
  ##   #       b = 3
  ##
  ## If you need to create multiple identifiers you need to use the lower level
  ## ``newNimNode``:
  ##
  ## .. code-block:: nim
  ##
  ##   result = newNimNode(nnkIdentDefs).add(
  ##     ident("a"), ident("b"), ident("c"), ident("string"),
  ##       newStrLitNode("Hello"))
  newNimNode(nnkIdentDefs).add(name, kind, default)

proc newNilLit*(): NimNode {.compileTime.} =
  ## New nil literal shortcut
  result = newNimNode(nnkNilLit)

proc high*(node: NimNode): int {.compileTime.} = len(node) - 1
  ## Return the highest index available for a node
proc last*(node: NimNode): NimNode {.compileTime.} = node[node.high]
  ## Return the last item in nodes children. Same as `node[node.high()]`


const
  RoutineNodes* = {nnkProcDef, nnkMethodDef, nnkDo, nnkLambda, nnkIteratorDef}
  AtomicNodes* = {nnkNone..nnkNilLit}
  CallNodes* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand,
    nnkCallStrLit, nnkHiddenCallConv}

proc expectKind*(n: NimNode; k: set[NimNodeKind]) {.compileTime.} =
  assert n.kind in k, "Expected one of " & $k & ", got " & $n.kind

proc newProc*(name = newEmptyNode(); params: openArray[NimNode] = [newEmptyNode()];
    body: NimNode = newStmtList(), procType = nnkProcDef): NimNode {.compileTime.} =
  ## shortcut for creating a new proc
  ##
  ## The ``params`` array must start with the return type of the proc,
  ## followed by a list of IdentDefs which specify the params.
  assert procType in RoutineNodes
  result = newNimNode(procType).add(
    name,
    newEmptyNode(),
    newEmptyNode(),
    newNimNode(nnkFormalParams).add(params), ##params
    newEmptyNode(),  ## pragmas
    newEmptyNode(),
    body)

proc newIfStmt*(branches: varargs[tuple[cond, body: NimNode]]):
                NimNode {.compiletime.} =
  ## Constructor for ``if`` statements.
  ##
  ## .. code-block:: nim
  ##
  ##    newIfStmt(
  ##      (Ident, StmtList),
  ##      ...
  ##    )
  ##
  result = newNimNode(nnkIfStmt)
  for i in branches:
    result.add(newNimNode(nnkElifBranch).add(i.cond, i.body))


proc copyChildrenTo*(src, dest: NimNode) {.compileTime.}=
  ## Copy all children from `src` to `dest`
  for i in 0 .. < src.len:
    dest.add src[i].copyNimTree

template expectRoutine(node: NimNode): stmt =
  expectKind(node, RoutineNodes)

proc name*(someProc: NimNode): NimNode {.compileTime.} =
  someProc.expectRoutine
  result = someProc[0]
proc `name=`*(someProc: NimNode; val: NimNode) {.compileTime.} =
  someProc.expectRoutine
  someProc[0] = val

proc params*(someProc: NimNode): NimNode {.compileTime.} =
  someProc.expectRoutine
  result = someProc[3]
proc `params=`* (someProc: NimNode; params: NimNode) {.compileTime.}=
  someProc.expectRoutine
  assert params.kind == nnkFormalParams
  someProc[3] = params

proc pragma*(someProc: NimNode): NimNode {.compileTime.} =
  ## Get the pragma of a proc type
  ## These will be expanded
  someProc.expectRoutine
  result = someProc[4]
proc `pragma=`*(someProc: NimNode; val: NimNode){.compileTime.}=
  ## Set the pragma of a proc type
  someProc.expectRoutine
  assert val.kind in {nnkEmpty, nnkPragma}
  someProc[4] = val


template badNodeKind(k; f): stmt{.immediate.} =
  assert false, "Invalid node kind " & $k & " for macros.`" & $f & "`"

proc body*(someProc: NimNode): NimNode {.compileTime.} =
  case someProc.kind:
  of RoutineNodes:
    return someProc[6]
  of nnkBlockStmt, nnkWhileStmt:
    return someProc[1]
  of nnkForStmt:
    return someProc.last
  else:
    badNodeKind someProc.kind, "body"

proc `body=`*(someProc: NimNode, val: NimNode) {.compileTime.} =
  case someProc.kind
  of RoutineNodes:
    someProc[6] = val
  of nnkBlockStmt, nnkWhileStmt:
    someProc[1] = val
  of nnkForStmt:
    someProc[high(someProc)] = val
  else:
    badNodeKind someProc.kind, "body="

proc basename*(a: NimNode): NimNode {.compiletime, benign.}


proc `$`*(node: NimNode): string {.compileTime.} =
  ## Get the string of an identifier node
  case node.kind
  of nnkIdent:
    result = $node.ident
  of nnkPostfix:
    result = $node.basename.ident & "*"
  of nnkStrLit..nnkTripleStrLit:
    result = node.strVal
  of nnkSym:
    result = $node.symbol
  else:
    badNodeKind node.kind, "$"

proc ident*(name: string): NimNode {.compileTime,inline.} = newIdentNode(name)
  ## Create a new ident node from a string

iterator children*(n: NimNode): NimNode {.inline.}=
  for i in 0 .. high(n):
    yield n[i]

template findChild*(n: NimNode; cond: expr): NimNode {.
  immediate, dirty.} =
  ## Find the first child node matching condition (or nil).
  ##
  ## .. code-block:: nim
  ##   var res = findChild(n, it.kind == nnkPostfix and
  ##                          it.basename.ident == !"foo")
  block:
    var result: NimNode
    for it in n.children:
      if cond:
        result = it
        break
    result

proc insert*(a: NimNode; pos: int; b: NimNode) {.compileTime.} =
  ## Insert node B into A at pos
  if high(a) < pos:
    ## add some empty nodes first
    for i in high(a)..pos-2:
      a.add newEmptyNode()
    a.add b
  else:
    ## push the last item onto the list again
    ## and shift each item down to pos up one
    a.add(a[a.high])
    for i in countdown(high(a) - 2, pos):
      a[i + 1] = a[i]
    a[pos] = b

proc basename*(a: NimNode): NimNode =
  ## Pull an identifier from prefix/postfix expressions
  case a.kind
  of nnkIdent: return a
  of nnkPostfix, nnkPrefix: return a[1]
  else:
    quit "Do not know how to get basename of (" & treeRepr(a) & ")\n" & repr(a)

proc `basename=`*(a: NimNode; val: string) {.compileTime.}=
  case a.kind
  of nnkIdent: macros.`ident=`(a,  !val)
  of nnkPostfix, nnkPrefix: a[1] = ident(val)
  else:
    quit "Do not know how to get basename of (" & treeRepr(a) & ")\n" & repr(a)

proc postfix*(node: NimNode; op: string): NimNode {.compileTime.} =
  newNimNode(nnkPostfix).add(ident(op), node)

proc prefix*(node: NimNode; op: string): NimNode {.compileTime.} =
  newNimNode(nnkPrefix).add(ident(op), node)

proc infix*(a: NimNode; op: string;
            b: NimNode): NimNode {.compileTime.} =
  newNimNode(nnkInfix).add(ident(op), a, b)

proc unpackPostfix*(node: NimNode): tuple[node: NimNode; op: string] {.
  compileTime.} =
  node.expectKind nnkPostfix
  result = (node[0], $node[1])

proc unpackPrefix*(node: NimNode): tuple[node: NimNode; op: string] {.
  compileTime.} =
  node.expectKind nnkPrefix
  result = (node[0], $node[1])

proc unpackInfix*(node: NimNode): tuple[left: NimNode; op: string;
                                        right: NimNode] {.compileTime.} =
  assert node.kind == nnkInfix
  result = (node[0], $node[1], node[2])

proc copy*(node: NimNode): NimNode {.compileTime.} =
  ## An alias for copyNimTree().
  return node.copyNimTree()

proc cmpIgnoreStyle(a, b: cstring): int {.noSideEffect.} =
  proc toLower(c: char): char {.inline.} =
    if c in {'A'..'Z'}: result = chr(ord(c) + (ord('a') - ord('A')))
    else: result = c
  var i = 0
  var j = 0
  while true:
    while a[i] == '_': inc(i)
    while b[j] == '_': inc(j) # BUGFIX: typo
    var aa = toLower(a[i])
    var bb = toLower(b[j])
    result = ord(aa) - ord(bb)
    if result != 0 or aa == '\0': break
    inc(i)
    inc(j)

proc eqIdent* (a, b: string): bool = cmpIgnoreStyle(a, b) == 0
  ## Check if two idents are identical.

proc hasArgOfName* (params: NimNode; name: string): bool {.compiletime.}=
  ## Search nnkFormalParams for an argument.
  assert params.kind == nnkFormalParams
  for i in 1 .. <params.len:
    template node: expr = params[i]
    if name.eqIdent( $ node[0]):
      return true

proc addIdentIfAbsent*(dest: NimNode, ident: string) {.compiletime.} =
  ## Add ident to dest if it is not present. This is intended for use
  ## with pragmas.
  for node in dest.children:
    case node.kind
    of nnkIdent:
      if ident.eqIdent($node): return
    of nnkExprColonExpr:
      if ident.eqIdent($node[0]): return
    else: discard
  dest.add(ident(ident))

when not defined(booting):
  template emit*(e: static[string]): stmt =
    ## accepts a single string argument and treats it as nim code
    ## that should be inserted verbatim in the program
    ## Example:
    ##
    ## .. code-block:: nim
    ##   emit("echo " & '"' & "hello world".toUpper & '"')
    ##
    macro payload: stmt {.gensym.} =
      result = parseStmt(e)
    payload()