tusertypeclasses.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. discard """
  2. output: '''Sortable
  3. Sortable
  4. Container
  5. TObj
  6. int
  7. 111 111
  8. (id: @[1, 2, 3], name: @["Vas", "Pas", "NafNaf"], age: @[10, 16, 18])
  9. '''
  10. """
  11. import typetraits
  12. template reject(expr) = assert(not compiles(x))
  13. type
  14. TObj = object
  15. x: int
  16. JSonValue = object
  17. val: string
  18. Sortable = concept x, y
  19. (x < y) is bool
  20. ObjectContainer = concept C
  21. C.len is Ordinal
  22. for v in items(C):
  23. v.type is tuple|object
  24. proc foo(c: ObjectContainer) =
  25. echo "Container"
  26. proc foo(x: Sortable) =
  27. echo "Sortable"
  28. foo 10
  29. foo "test"
  30. foo(@[TObj(x: 10), TObj(x: 20)])
  31. proc intval(x: int): int = 10
  32. type
  33. TFoo = concept o, type T, ref r, var v, ptr p, static s
  34. o.x
  35. y(o) is int
  36. var str: string
  37. var intref: ref int
  38. refproc(ref T, ref int)
  39. varproc(var T)
  40. ptrproc(ptr T, str)
  41. staticproc(static[T])
  42. typeproc T
  43. T.typeproc
  44. typeproc o.type
  45. o.type.typeproc
  46. o.to(type string)
  47. o.to(type JsonValue)
  48. refproc(r, intref)
  49. varproc(v)
  50. p.ptrproc(string)
  51. staticproc s
  52. typeproc(T)
  53. const TypeName = T.name
  54. type MappedType = type(o.y)
  55. intval y(o)
  56. let z = intval(o.y)
  57. static:
  58. assert T.name.len == 4
  59. reject o.name
  60. reject o.typeproc
  61. reject staticproc(o)
  62. reject o.varproc
  63. reject T.staticproc
  64. reject p.staticproc
  65. proc y(x: TObj): int = 10
  66. proc varproc(x: var TObj) = discard
  67. proc refproc(x: ref TObj, y: ref int) = discard
  68. proc ptrproc(x: ptr TObj, y: string) = discard
  69. proc staticproc(x: static[TObj]) = discard
  70. proc typeproc(t: type TObj) = discard
  71. proc to(x: TObj, t: type string) = discard
  72. proc to(x: TObj, t: type JSonValue) = discard
  73. proc testFoo(x: TFoo) =
  74. echo x.TypeName
  75. echo x.MappedType.name
  76. testFoo(TObj(x: 10))
  77. # bug #7092
  78. type stringTest = concept x
  79. x is string
  80. let usedToFail: stringTest = "111"
  81. let working: string = "111"
  82. echo usedToFail, " ", working
  83. # bug #5868
  84. type TaggedType[T; Key: static[string]] = T
  85. proc setKey*[DT](dt: DT, key: static[string]): TaggedType[DT, key] =
  86. result = cast[type(result)](dt)
  87. type Students = object
  88. id : seq[int]
  89. name : seq[string]
  90. age: seq[int]
  91. let
  92. stud = Students(id : @[1,2,3], name : @["Vas", "Pas", "NafNaf"], age : @[10,16,18])
  93. stud2 = stud.setkey("id")
  94. echo stud2