typetraits.nim 2.0 KB

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