ttypedesc1.nim 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import unittest, typetraits
  2. type
  3. TFoo[T, U] = object
  4. x: T
  5. y: U
  6. proc getTypeName1(t: typedesc): string = t.name
  7. proc getTypeName2(t: type): string = t.name
  8. proc foo(T: type float, a: auto): string =
  9. result = "float " & $(a.len > 5)
  10. proc foo(T: typedesc[TFoo], a: int): string =
  11. result = "TFoo " & $(a)
  12. proc foo(T: type[int or bool]): string =
  13. var a: T
  14. a = 10
  15. result = "int or bool " & ($a)
  16. template foo(T: typedesc[seq]): string = "seq"
  17. test "types can be used as proc params":
  18. # XXX: `check` needs to know that TFoo[int, float] is a type and
  19. # cannot be assigned for a local variable for later inspection
  20. check ((string.getTypeName1 == "string"))
  21. check ((getTypeName2(int) == "int"))
  22. check ((foo(TFoo[int, float], 1000) == "TFoo 1000"))
  23. var f = 10.0
  24. check ((foo(float, "long string") == "float true"))
  25. check ((foo(type(f), [1, 2, 3]) == "float false"))
  26. check ((foo(int) == "int or bool 10"))
  27. check ((foo(seq[int]) == "seq"))
  28. check ((foo(seq[TFoo[bool, string]]) == "seq"))
  29. template accept(x) =
  30. static: assert(compiles(x))
  31. template reject(x) =
  32. static: assert(not compiles(x))
  33. var
  34. si: seq[int]
  35. ss: seq[string]
  36. proc foo(T: typedesc[seq], s: T) =
  37. discard
  38. accept:
  39. foo seq[int], si
  40. reject:
  41. foo seq[string], si
  42. reject:
  43. foo seq[int], ss
  44. # issue #12398
  45. reject:
  46. let xs = [int, float, string]
  47. reject:
  48. let data = @[int, typedesc]