tdotops.nim 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. block:
  19. type Foo = object
  20. var a: Foo
  21. template `.`(a: Foo, b: untyped): untyped = astToStr(b)
  22. template callme(a, f): untyped = a.f
  23. doAssert callme(a, f2) == "f2" # not `f`
  24. doAssert a.callme(f3) == "f3"
  25. type
  26. T1 = object
  27. x*: int
  28. TD = distinct T1
  29. T2 = object
  30. x: int
  31. template `.`*(v: T1, f: untyped): int =
  32. echo "reading field ", astToStr(f)
  33. v.x
  34. template `.=`(t: var T1, f: untyped, v: int) =
  35. echo "assigning ", astToStr(f), " = ", v
  36. t.x = v
  37. template `.()`(x: T1, f: untyped, args: varargs[typed]): string =
  38. echo "call to ", astToStr(f)
  39. "dot call"
  40. echo ""
  41. var t = T1(x: 10)
  42. echo t.x
  43. t.z = 20
  44. echo t.y
  45. echo t.y()
  46. var d = TD(t)
  47. assert(not compiles(d.y))
  48. template `.`(v: T2, f: untyped): int =
  49. echo "no params call to ", astToStr(f)
  50. v.x
  51. template `.`*(v: T2, f: untyped, a: int): int =
  52. echo "one param call to ", astToStr(f), " with ", a
  53. v.x
  54. var tt = T2(x: 100)
  55. echo tt.a
  56. echo tt.b()
  57. echo tt.c(10)
  58. assert(not compiles(tt.d("x")))
  59. assert(not compiles(tt.d(1, 2)))
  60. # test simple usage that delegates fields:
  61. type
  62. Other = object
  63. a: int
  64. b: string
  65. MyObject = object
  66. nested: Other
  67. x, y: int
  68. template `.`(x: MyObject; field: untyped): untyped =
  69. x.nested.field
  70. template `.=`(x: MyObject; field, value: untyped) =
  71. x.nested.field = value
  72. var m: MyObject
  73. m.a = 4
  74. m.b = "foo"
  75. echo m.x, " ", m.a