typetraits.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 hasDefaultValue*(t: typedesc): bool {.magic: "TypeTrait".} =
  82. ## Returns true if `t` has a valid default value.
  83. runnableExamples:
  84. {.experimental: "strictNotNil".}
  85. type
  86. NilableObject = ref object
  87. a: int
  88. Object = NilableObject not nil
  89. RequiresInit[T] = object
  90. a {.requiresInit.}: T
  91. assert hasDefaultValue(NilableObject)
  92. assert not hasDefaultValue(Object)
  93. assert hasDefaultValue(string)
  94. assert not hasDefaultValue(var string)
  95. assert not hasDefaultValue(RequiresInit[int])
  96. proc isNamedTuple*(T: typedesc): bool {.magic: "TypeTrait".} =
  97. ## Returns true for named tuples, false for any other type.
  98. runnableExamples:
  99. doAssert not isNamedTuple(int)
  100. doAssert not isNamedTuple((string, int))
  101. doAssert isNamedTuple(tuple[name: string, age: int])
  102. template pointerBase*[T](_: typedesc[ptr T | ref T]): typedesc =
  103. ## Returns `T` for `ref T | ptr T`.
  104. runnableExamples:
  105. assert (ref int).pointerBase is int
  106. type A = ptr seq[float]
  107. assert A.pointerBase is seq[float]
  108. assert (ref A).pointerBase is A # not seq[float]
  109. assert (var s = "abc"; s[0].addr).typeof.pointerBase is char
  110. T
  111. proc distinctBase*(T: typedesc, recursive: static bool = true): typedesc {.magic: "TypeTrait".} =
  112. ## Returns the base type for distinct types, or the type itself otherwise.
  113. ## If `recursive` is false, only the immediate distinct base will be returned.
  114. ##
  115. ## **See also:**
  116. ## * `distinctBase template <#distinctBase.t,T,static[bool]>`_
  117. runnableExamples:
  118. type MyInt = distinct int
  119. type MyOtherInt = distinct MyInt
  120. doAssert distinctBase(MyInt) is int
  121. doAssert distinctBase(MyOtherInt) is int
  122. doAssert distinctBase(MyOtherInt, false) is MyInt
  123. doAssert distinctBase(int) is int
  124. since (1, 1):
  125. template distinctBase*[T](a: T, recursive: static bool = true): untyped =
  126. ## Overload of `distinctBase <#distinctBase,typedesc,static[bool]>`_ for values.
  127. runnableExamples:
  128. type MyInt = distinct int
  129. type MyOtherInt = distinct MyInt
  130. doAssert 12.MyInt.distinctBase == 12
  131. doAssert 12.MyOtherInt.distinctBase == 12
  132. doAssert 12.MyOtherInt.distinctBase(false) is MyInt
  133. doAssert 12.distinctBase == 12
  134. when T is distinct:
  135. distinctBase(typeof(a), recursive)(a)
  136. else: # avoids hint ConvFromXtoItselfNotNeeded
  137. a
  138. proc tupleLen*(T: typedesc[tuple]): int {.magic: "TypeTrait".} =
  139. ## Returns the number of elements of the tuple type `T`.
  140. ##
  141. ## **See also:**
  142. ## * `tupleLen template <#tupleLen.t>`_
  143. runnableExamples:
  144. doAssert tupleLen((int, int, float, string)) == 4
  145. doAssert tupleLen(tuple[name: string, age: int]) == 2
  146. template tupleLen*(t: tuple): int =
  147. ## Returns the number of elements of the tuple `t`.
  148. ##
  149. ## **See also:**
  150. ## * `tupleLen proc <#tupleLen,typedesc>`_
  151. runnableExamples:
  152. doAssert tupleLen((1, 2)) == 2
  153. tupleLen(typeof(t))
  154. template get*(T: typedesc[tuple], i: static int): untyped =
  155. ## Returns the `i`-th element of `T`.
  156. # Note: `[]` currently gives: `Error: no generic parameters allowed for ...`
  157. runnableExamples:
  158. doAssert get((int, int, float, string), 2) is float
  159. typeof(default(T)[i])
  160. type StaticParam*[value: static type] = object
  161. ## Used to wrap a static value in `genericParams <#genericParams.t,typedesc>`_.
  162. since (1, 3, 5):
  163. template elementType*(a: untyped): typedesc =
  164. ## Returns the element type of `a`, which can be any iterable (over which you
  165. ## can iterate).
  166. runnableExamples:
  167. iterator myiter(n: int): auto =
  168. for i in 0 ..< n:
  169. yield i
  170. doAssert elementType(@[1,2]) is int
  171. doAssert elementType("asdf") is char
  172. doAssert elementType(myiter(3)) is int
  173. typeof(block: (for ai in a: ai))
  174. import macros
  175. macro enumLen*(T: typedesc[enum]): int =
  176. ## Returns the number of items in the enum `T`.
  177. runnableExamples:
  178. type Foo = enum
  179. fooItem1
  180. fooItem2
  181. doAssert Foo.enumLen == 2
  182. let bracketExpr = getType(T)
  183. expectKind(bracketExpr, nnkBracketExpr)
  184. let enumTy = bracketExpr[1]
  185. expectKind(enumTy, nnkEnumTy)
  186. result = newLit(enumTy.len - 1)
  187. macro genericParamsImpl(T: typedesc): untyped =
  188. # auxiliary macro needed, can't do it directly in `genericParams`
  189. result = newNimNode(nnkTupleConstr)
  190. var impl = getTypeImpl(T)
  191. expectKind(impl, nnkBracketExpr)
  192. impl = impl[1]
  193. while true:
  194. case impl.kind
  195. of nnkSym:
  196. impl = impl.getImpl
  197. of nnkTypeDef:
  198. impl = impl[2]
  199. of nnkTypeOfExpr:
  200. impl = getTypeInst(impl[0])
  201. of nnkBracketExpr:
  202. for i in 1..<impl.len:
  203. let ai = impl[i]
  204. var ret: NimNode = nil
  205. case ai.typeKind
  206. of ntyTypeDesc:
  207. ret = ai
  208. of ntyStatic: raiseAssert "unreachable"
  209. else:
  210. # getType from a resolved symbol might return a typedesc symbol.
  211. # If so, use it directly instead of wrapping it in StaticParam.
  212. if (ai.kind == nnkSym and ai.symKind == nskType) or
  213. (ai.kind == nnkBracketExpr and ai[0].kind == nnkSym and
  214. ai[0].symKind == nskType) or ai.kind in {nnkRefTy, nnkVarTy, nnkPtrTy, nnkProcTy}:
  215. ret = ai
  216. elif ai.kind == nnkInfix and ai[0].kind == nnkIdent and
  217. ai[0].strVal == "..":
  218. # For built-in array types, the "2" is translated to "0..1" then
  219. # automagically translated to "range[0..1]". However this is not
  220. # reflected in the AST, thus requiring manual transformation here.
  221. #
  222. # We will also be losing some context here:
  223. # var a: array[10, int]
  224. # will be translated to:
  225. # var a: array[0..9, int]
  226. # after typecheck. This means that we can't get the exact
  227. # definition as typed by the user, which will cause confusion for
  228. # users expecting:
  229. # genericParams(typeof(a)) is (StaticParam(10), int)
  230. # to be true while in fact the result will be:
  231. # genericParams(typeof(a)) is (range[0..9], int)
  232. ret = newTree(nnkBracketExpr, @[bindSym"range", ai])
  233. else:
  234. since (1, 1):
  235. ret = newTree(nnkBracketExpr, @[bindSym"StaticParam", ai])
  236. result.add ret
  237. break
  238. else:
  239. error "wrong kind: " & $impl.kind, impl
  240. since (1, 1):
  241. template genericParams*(T: typedesc): untyped =
  242. ## Returns the tuple of generic parameters for the generic type `T`.
  243. ##
  244. ## **Note:** For the builtin array type, the index generic parameter will
  245. ## **always** become a range type after it's bound to a variable.
  246. runnableExamples:
  247. type Foo[T1, T2] = object
  248. doAssert genericParams(Foo[float, string]) is (float, string)
  249. type Bar[N: static float, T] = object
  250. doAssert genericParams(Bar[1.0, string]) is (StaticParam[1.0], string)
  251. doAssert genericParams(Bar[1.0, string]).get(0).value == 1.0
  252. doAssert genericParams(seq[Bar[2.0, string]]).get(0) is Bar[2.0, string]
  253. var s: seq[Bar[3.0, string]]
  254. doAssert genericParams(typeof(s)) is (Bar[3.0, string],)
  255. doAssert genericParams(array[10, int]) is (StaticParam[10], int)
  256. var a: array[10, int]
  257. doAssert genericParams(typeof(a)) is (range[0..9], int)
  258. type T2 = T
  259. genericParamsImpl(T2)
  260. proc hasClosureImpl(n: NimNode): bool = discard "see compiler/vmops.nim"
  261. proc hasClosure*(fn: NimNode): bool {.since: (1, 5, 1).} =
  262. ## Returns true if the func/proc/etc `fn` has `closure`.
  263. ## `fn` has to be a resolved symbol of kind `nnkSym`. This
  264. ## implies that the macro that calls this proc should accept `typed`
  265. ## arguments and not `untyped` arguments.
  266. expectKind fn, nnkSym
  267. result = hasClosureImpl(fn)
  268. template toUnsigned*(T: typedesc[SomeInteger and not range]): untyped =
  269. ## Returns an unsigned type with same bit size as `T`.
  270. runnableExamples:
  271. assert int8.toUnsigned is uint8
  272. assert uint.toUnsigned is uint
  273. assert int.toUnsigned is uint
  274. # range types are currently unsupported:
  275. assert not compiles(toUnsigned(range[0..7]))
  276. when T is int8: uint8
  277. elif T is int16: uint16
  278. elif T is int32: uint32
  279. elif T is int64: uint64
  280. elif T is int: uint
  281. else: T
  282. template toSigned*(T: typedesc[SomeInteger and not range]): untyped =
  283. ## Returns a signed type with same bit size as `T`.
  284. runnableExamples:
  285. assert int8.toSigned is int8
  286. assert uint16.toSigned is int16
  287. # range types are currently unsupported:
  288. assert not compiles(toSigned(range[0..7]))
  289. when T is uint8: int8
  290. elif T is uint16: int16
  291. elif T is uint32: int32
  292. elif T is uint64: int64
  293. elif T is uint: int
  294. else: T