summary refs log tree commit diff stats
path: root/lib/pure
diff options
context:
space:
mode:
authorTimothee Cour <timothee.cour2@gmail.com>2020-01-09 23:51:37 -0800
committerAndreas Rumpf <rumpf_a@web.de>2020-01-10 08:51:37 +0100
commit4cd86c08427205d2e26510a07a3c6980c14e1608 (patch)
treeefab63d6385cfe3f9368f390ececb06793eb30b9 /lib/pure
parentfcd2f305ad5ad2af37284caf7b33907afb8ad834 (diff)
downloadNim-4cd86c08427205d2e26510a07a3c6980c14e1608.tar.gz
typetraits: fixes #6454; genericParams; added lenTuple; added tuple type get (#13064)
Diffstat (limited to 'lib/pure')
-rw-r--r--lib/pure/typetraits.nim40
1 files changed, 40 insertions, 0 deletions
diff --git a/lib/pure/typetraits.nim b/lib/pure/typetraits.nim
index 7a493cb6c..26cbce4d1 100644
--- a/lib/pure/typetraits.nim
+++ b/lib/pure/typetraits.nim
@@ -14,6 +14,7 @@
 
 export system.`$` # for backward compatibility
 
+include "system/inclrtl"
 
 proc name*(t: typedesc): string {.magic: "TypeTrait".}
   ## Returns the name of the given type.
@@ -70,6 +71,45 @@ proc distinctBase*(T: typedesc): typedesc {.magic: "TypeTrait".}
   ## Returns base type for distinct types, works only for distinct types.
   ## compile time error otherwise
 
+import std/macros
+
+macro lenTuple*(t: tuple): int {.since: (1, 1).} =
+  ## Return number of elements of `t`
+  newLit t.len
+
+macro lenTuple*(t: typedesc[tuple]): int {.since: (1, 1).} =
+  ## Return number of elements of `T`
+  newLit t.len
+
+when (NimMajor, NimMinor) >= (1, 1):
+  template get*(T: typedesc[tuple], i: static int): untyped =
+    ## Return `i`th element of `T`
+    # Note: `[]` currently gives: `Error: no generic parameters allowed for ...`
+    type(default(T)[i])
+
+macro genericParams*(T: typedesc): untyped {.since: (1, 1).} =
+  ## return tuple of generic params for generic `T`
+  runnableExamples:
+    type Foo[T1, T2]=object
+    doAssert genericParams(Foo[float, string]) is (float, string)
+  result = newNimNode(nnkTupleConstr)
+  var impl = getTypeImpl(T)
+  expectKind(impl, nnkBracketExpr)
+  impl = impl[1]
+  while true:
+    case impl.kind
+      of nnkSym:
+        impl = impl.getImpl
+        continue
+      of nnkTypeDef:
+        impl = impl[2]
+        continue
+      of nnkBracketExpr:
+        for i in 1..<impl.len:
+          result.add impl[i]
+        break
+      else:
+        error "wrong kind: " & $impl.kind
 
 when isMainModule:
   static: