tdotops.nim 1.3 KB

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