typetraits.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module defines compile-time reflection procs for
  10. ## working with types.
  11. ##
  12. ## Unstable API.
  13. import std/private/since
  14. export system.`$` # for backward compatibility
  15. when defined(nimPreviewSlimSystem):
  16. import std/assertions
  17. type HoleyEnum* = (not Ordinal) and enum ## Enum with holes.
  18. type OrdinalEnum* = Ordinal and enum ## Enum without holes.
  19. runnableExamples:
  20. type A = enum a0 = 2, a1 = 4, a2
  21. type B = enum b0 = 2, b1, b2
  22. assert A is enum
  23. assert A is HoleyEnum
  24. assert A isnot OrdinalEnum
  25. assert B isnot HoleyEnum
  26. assert B is OrdinalEnum
  27. assert int isnot HoleyEnum
  28. type C[T] = enum h0 = 2, h1 = 4
  29. assert C[float] is HoleyEnum
  30. proc name*(t: typedesc): string {.magic: "TypeTrait".} =
  31. ## Returns the name of `t`.
  32. ##
  33. ## Alias for `system.\`$\`(t) <dollars.html#$,typedesc>`_ since Nim v0.20.
  34. runnableExamples:
  35. doAssert name(int) == "int"
  36. doAssert name(seq[string]) == "seq[string]"
  37. proc arity*(t: typedesc): int {.magic: "TypeTrait".} =
  38. ## Returns the arity of `t`. This is the number of "type"
  39. ## components or the number of generic parameters a given type `t` has.
  40. runnableExamples:
  41. doAssert arity(int) == 0
  42. doAssert arity(seq[string]) == 1
  43. doAssert arity(array[3, int]) == 2
  44. doAssert arity((int, int, float, string)) == 4
  45. proc genericHead*(t: typedesc): typedesc {.magic: "TypeTrait".} =
  46. ## Accepts an instantiated generic type and returns its
  47. ## uninstantiated form.
  48. ## A compile-time error will be produced if the supplied type
  49. ## is not generic.
  50. ##
  51. ## **See also:**
  52. ## * `stripGenericParams proc <#stripGenericParams,typedesc>`_
  53. runnableExamples:
  54. type
  55. Foo[T] = object
  56. FooInst = Foo[int]
  57. Foo2 = genericHead(FooInst)
  58. doAssert Foo2 is Foo and Foo is Foo2
  59. doAssert genericHead(Foo[seq[string]]) is Foo
  60. doAssert not compiles(genericHead(int))
  61. type Generic = concept f
  62. type _ = genericHead(typeof(f))
  63. proc bar(a: Generic): typeof(a) = a
  64. doAssert bar(Foo[string].default) == Foo[string]()
  65. doAssert not compiles bar(string.default)
  66. when false: # these don't work yet
  67. doAssert genericHead(Foo[int])[float] is Foo[float]
  68. doAssert seq[int].genericHead is seq
  69. proc stripGenericParams*(t: typedesc): typedesc {.magic: "TypeTrait".} =
  70. ## This trait is similar to `genericHead <#genericHead,typedesc>`_, but
  71. ## instead of producing an error for non-generic types, it will just return
  72. ## them unmodified.
  73. runnableExamples:
  74. type Foo[T] = object
  75. doAssert stripGenericParams(Foo[string]) is Foo
  76. doAssert stripGenericParams(int) is int
  77. proc supportsCopyMem*(t: typedesc): bool {.magic: "TypeTrait".}
  78. ## Returns true if `t` is safe to use for `copyMem`:idx:.
  79. ##
  80. ## Other languages name a type like these `blob`:idx:.
  81. proc isNamedTuple*(T: typedesc): bool {.magic: "TypeTrait".} =
  82. ## Returns true for named tuples, false for any other type.
  83. runnableExamples:
  84. doAssert not isNamedTuple(int)
  85. doAssert not isNamedTuple((string, int))
  86. doAssert isNamedTuple(tuple[name: string, age: int])
  87. template pointerBase*[T](_: typedesc[ptr T | ref T]): typedesc =
  88. ## Returns `T` for `ref T | ptr T`.
  89. runnableExamples:
  90. assert (ref int).pointerBase is int
  91. type A = ptr seq[float]
  92. assert A.pointerBase is seq[float]
  93. assert (ref A).pointerBase is A # not seq[float]
  94. assert (var s = "abc"; s[0].addr).typeof.pointerBase is char
  95. T
  96. proc distinctBase*(T: typedesc, recursive: static bool = true): typedesc {.magic: "TypeTrait".} =
  97. ## Returns the base type for distinct types, or the type itself otherwise.
  98. ## If `recursive` is false, only the immediate distinct base will be returned.
  99. ##
  100. ## **See also:**
  101. ## * `distinctBase template <#distinctBase.t,T,static[bool]>`_
  102. runnableExamples:
  103. type MyInt = distinct int
  104. type MyOtherInt = distinct MyInt
  105. doAssert distinctBase(MyInt) is int
  106. doAssert distinctBase(MyOtherInt) is int
  107. doAssert distinctBase(MyOtherInt, false) is MyInt
  108. doAssert distinctBase(int) is int
  109. since (1, 1):
  110. template distinctBase*[T](a: T, recursive: static bool = true): untyped =
  111. ## Overload of `distinctBase <#distinctBase,typedesc,static[bool]>`_ for values.
  112. runnableExamples:
  113. type MyInt = distinct int
  114. type MyOtherInt = distinct MyInt
  115. doAssert 12.MyInt.distinctBase == 12
  116. doAssert 12.MyOtherInt.distinctBase == 12
  117. doAssert 12.MyOtherInt.distinctBase(false) is MyInt
  118. doAssert 12.distinctBase == 12
  119. when T is distinct:
  120. distinctBase(typeof(a), recursive)(a)
  121. else: # avoids hint ConvFromXtoItselfNotNeeded
  122. a
  123. proc tupleLen*(T: typedesc[tuple]): int {.magic: "TypeTrait".} =
  124. ## Returns the number of elements of the tuple type `T`.
  125. ##
  126. ## **See also:**
  127. ## * `tupleLen template <#tupleLen.t>`_
  128. runnableExamples:
  129. doAssert tupleLen((int, int, float, string)) == 4
  130. doAssert tupleLen(tuple[name: string, age: int]) == 2
  131. template tupleLen*(t: tuple): int =
  132. ## Returns the number of elements of the tuple `t`.
  133. ##
  134. ## **See also:**
  135. ## * `tupleLen proc <#tupleLen,typedesc>`_
  136. runnableExamples:
  137. doAssert tupleLen((1, 2)) == 2
  138. tupleLen(typeof(t))
  139. template get*(T: typedesc[tuple], i: static int): untyped =
  140. ## Returns the `i`-th element of `T`.
  141. # Note: `[]` currently gives: `Error: no generic parameters allowed for ...`
  142. runnableExamples:
  143. doAssert get((int, int, float, string), 2) is float
  144. typeof(default(T)[i])
  145. type StaticParam*[value: static type] = object
  146. ## Used to wrap a static value in `genericParams <#genericParams.t,typedesc>`_.
  147. since (1, 3, 5):
  148. template elementType*(a: untyped): typedesc =
  149. ## Returns the element type of `a`, which can be any iterable (over which you
  150. ## can iterate).
  151. runnableExamples:
  152. iterator myiter(n: int): auto =
  153. for i in 0 ..< n:
  154. yield i
  155. doAssert elementType(@[1,2]) is int
  156. doAssert elementType("asdf") is char
  157. doAssert elementType(myiter(3)) is int
  158. typeof(block: (for ai in a: ai))
  159. import macros
  160. macro enumLen*(T: typedesc[enum]): int =
  161. ## Returns the number of items in the enum `T`.
  162. runnableExamples:
  163. type Foo = enum
  164. fooItem1
  165. fooItem2
  166. doAssert Foo.enumLen == 2
  167. let bracketExpr = getType(T)
  168. expectKind(bracketExpr, nnkBracketExpr)
  169. let enumTy = bracketExpr[1]
  170. expectKind(enumTy, nnkEnumTy)
  171. result = newLit(enumTy.len - 1)
  172. macro genericParamsImpl(T: typedesc): untyped =
  173. # auxiliary macro needed, can't do it directly in `genericParams`
  174. result = newNimNode(nnkTupleConstr)
  175. var impl = getTypeImpl(T)
  176. expectKind(impl, nnkBracketExpr)
  177. impl = impl[1]
  178. while true:
  179. case impl.kind
  180. of nnkSym:
  181. impl = impl.getImpl
  182. of nnkTypeDef:
  183. impl = impl[2]
  184. of nnkTypeOfExpr:
  185. impl = getTypeInst(impl[0])
  186. of nnkBracketExpr:
  187. for i in 1..<impl.len:
  188. let ai = impl[i]
  189. var ret: NimNode = nil
  190. case ai.typeKind
  191. of ntyTypeDesc:
  192. ret = ai
  193. of ntyStatic: doAssert false
  194. else:
  195. # getType from a resolved symbol might return a typedesc symbol.
  196. # If so, use it directly instead of wrapping it in StaticParam.
  197. if (ai.kind == nnkSym and ai.symKind == nskType) or
  198. (ai.kind == nnkBracketExpr and ai[0].kind == nnkSym and
  199. ai[0].symKind == nskType) or ai.kind in {nnkRefTy, nnkVarTy, nnkPtrTy, nnkProcTy}:
  200. ret = ai
  201. elif ai.kind == nnkInfix and ai[0].kind == nnkIdent and
  202. ai[0].strVal == "..":
  203. # For built-in array types, the "2" is translated to "0..1" then
  204. # automagically translated to "range[0..1]". However this is not
  205. # reflected in the AST, thus requiring manual transformation here.
  206. #
  207. # We will also be losing some context here:
  208. # var a: array[10, int]
  209. # will be translated to:
  210. # var a: array[0..9, int]
  211. # after typecheck. This means that we can't get the exact
  212. # definition as typed by the user, which will cause confusion for
  213. # users expecting:
  214. # genericParams(typeof(a)) is (StaticParam(10), int)
  215. # to be true while in fact the result will be:
  216. # genericParams(typeof(a)) is (range[0..9], int)
  217. ret = newTree(nnkBracketExpr, @[bindSym"range", ai])
  218. else:
  219. since (1, 1):
  220. ret = newTree(nnkBracketExpr, @[bindSym"StaticParam", ai])
  221. result.add ret
  222. break
  223. else:
  224. error "wrong kind: " & $impl.kind, impl
  225. since (1, 1):
  226. template genericParams*(T: typedesc): untyped =
  227. ## Returns the tuple of generic parameters for the generic type `T`.
  228. ##
  229. ## **Note:** For the builtin array type, the index generic parameter will
  230. ## **always** become a range type after it's bound to a variable.
  231. runnableExamples:
  232. type Foo[T1, T2] = object
  233. doAssert genericParams(Foo[float, string]) is (float, string)
  234. type Bar[N: static float, T] = object
  235. doAssert genericParams(Bar[1.0, string]) is (StaticParam[1.0], string)
  236. doAssert genericParams(Bar[1.0, string]).get(0).value == 1.0
  237. doAssert genericParams(seq[Bar[2.0, string]]).get(0) is Bar[2.0, string]
  238. var s: seq[Bar[3.0, string]]
  239. doAssert genericParams(typeof(s)) is (Bar[3.0, string],)
  240. doAssert genericParams(array[10, int]) is (StaticParam[10], int)
  241. var a: array[10, int]
  242. doAssert genericParams(typeof(a)) is (range[0..9], int)
  243. type T2 = T
  244. genericParamsImpl(T2)
  245. proc hasClosureImpl(n: NimNode): bool = discard "see compiler/vmops.nim"
  246. proc hasClosure*(fn: NimNode): bool {.since: (1, 5, 1).} =
  247. ## Returns true if the func/proc/etc `fn` has `closure`.
  248. ## `fn` has to be a resolved symbol of kind `nnkSym`. This
  249. ## implies that the macro that calls this proc should accept `typed`
  250. ## arguments and not `untyped` arguments.
  251. expectKind fn, nnkSym
  252. result = hasClosureImpl(fn)
  253. template toUnsigned*(T: typedesc[SomeInteger and not range]): untyped =
  254. ## Returns an unsigned type with same bit size as `T`.
  255. runnableExamples:
  256. assert int8.toUnsigned is uint8
  257. assert uint.toUnsigned is uint
  258. assert int.toUnsigned is uint
  259. # range types are currently unsupported:
  260. assert not compiles(toUnsigned(range[0..7]))
  261. when T is int8: uint8
  262. elif T is int16: uint16
  263. elif T is int32: uint32
  264. elif T is int64: uint64
  265. elif T is int: uint
  266. else: T
  267. template toSigned*(T: typedesc[SomeInteger and not range]): untyped =
  268. ## Returns a signed type with same bit size as `T`.
  269. runnableExamples:
  270. assert int8.toSigned is int8
  271. assert uint16.toSigned is int16
  272. # range types are currently unsupported:
  273. assert not compiles(toSigned(range[0..7]))
  274. when T is uint8: int8
  275. elif T is uint16: int16
  276. elif T is uint32: int32
  277. elif T is uint64: int64
  278. elif T is uint: int
  279. else: T