typetraits.nim 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. export system.`$`
  12. proc name*(t: typedesc): string {.magic: "TypeTrait".}
  13. ## Alias for system.`$`(t) since Nim v0.20.0.
  14. proc arity*(t: typedesc): int {.magic: "TypeTrait".} =
  15. ## Returns the arity of the given type. This is the number of "type" components or
  16. ## the number of generic parameters a given type ``t`` has.
  17. runnableExamples:
  18. assert arity(seq[string]) == 1
  19. assert arity(array[3, int]) == 2
  20. assert arity((int, int, float, string)) == 4
  21. proc genericHead*(t: typedesc): typedesc {.magic: "TypeTrait".}
  22. ## Accepts an instantiated generic type and returns its
  23. ## uninstantiated form.
  24. ##
  25. ## For example:
  26. ## seq[int].genericHead will be just seq
  27. ## seq[int].genericHead[float] will be seq[float]
  28. ##
  29. ## A compile-time error will be produced if the supplied type
  30. ## is not generic.
  31. proc stripGenericParams*(t: typedesc): typedesc {.magic: "TypeTrait".}
  32. ## This trait is similar to `genericHead`, but instead of producing
  33. ## error for non-generic types, it will just return them unmodified.
  34. proc supportsCopyMem*(t: typedesc): bool {.magic: "TypeTrait".}
  35. ## This trait returns true iff the type ``t`` is safe to use for
  36. ## `copyMem`:idx:. Other languages name a type like these `blob`:idx:.
  37. when isMainModule:
  38. static:
  39. doAssert $type(42) == "int"
  40. doAssert int.name == "int"
  41. const a1 = name(int)
  42. const a2 = $(int)
  43. const a3 = $int
  44. doAssert a1 == "int"
  45. doAssert a2 == "int"
  46. doAssert a3 == "int"
  47. proc fun[T: typedesc](t: T) =
  48. const a1 = name(t)
  49. const a2 = $(t)
  50. const a3 = $t
  51. doAssert a1 == "int"
  52. doAssert a2 == "int"
  53. doAssert a3 == "int"
  54. fun(int)