tdotops.nim 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. discard """
  2. output: '''
  3. 10
  4. assigning z = 20
  5. reading field y
  6. 20
  7. call to y
  8. dot call
  9. no params call to a
  10. 100
  11. no params call to b
  12. 100
  13. one param call to c with 10
  14. 100
  15. 0 4
  16. '''
  17. """
  18. type
  19. T1 = object
  20. x*: int
  21. TD = distinct T1
  22. T2 = object
  23. x: int
  24. template `.`*(v: T1, f: untyped): int =
  25. echo "reading field ", astToStr(f)
  26. v.x
  27. template `.=`(t: var T1, f: untyped, v: int) =
  28. echo "assigning ", astToStr(f), " = ", v
  29. t.x = v
  30. template `.()`(x: T1, f: untyped, args: varargs[typed]): string =
  31. echo "call to ", astToStr(f)
  32. "dot call"
  33. echo ""
  34. var t = T1(x: 10)
  35. echo t.x
  36. t.z = 20
  37. echo t.y
  38. echo t.y()
  39. var d = TD(t)
  40. assert(not compiles(d.y))
  41. template `.`(v: T2, f: untyped): int =
  42. echo "no params call to ", astToStr(f)
  43. v.x
  44. template `.`*(v: T2, f: untyped, a: int): int =
  45. echo "one param call to ", astToStr(f), " with ", a
  46. v.x
  47. var tt = T2(x: 100)
  48. echo tt.a
  49. echo tt.b()
  50. echo tt.c(10)
  51. assert(not compiles(tt.d("x")))
  52. assert(not compiles(tt.d(1, 2)))
  53. # test simple usage that delegates fields:
  54. type
  55. Other = object
  56. a: int
  57. b: string
  58. MyObject = object
  59. nested: Other
  60. x, y: int
  61. template `.`(x: MyObject; field: untyped): untyped =
  62. x.nested.field
  63. template `.=`(x: MyObject; field, value: untyped) =
  64. x.nested.field = value
  65. var m: MyObject
  66. m.a = 4
  67. m.b = "foo"
  68. echo m.x, " ", m.a