taddrof.nim 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. discard """
  2. nimout: '''
  3. true
  4. true
  5. [nil, nil, nil, nil]
  6. [MyObjectRef(123, 321), nil, nil, nil]
  7. ['A', '\x00', '\x00', '\x00']
  8. MyObjectRef(123, 321)
  9. (key: 8, val: 0)
  10. '''
  11. output: '''
  12. true
  13. true
  14. [nil, nil, nil, nil]
  15. [MyObjectRef(123, 321), nil, nil, nil]
  16. ['A', '\x00', '\x00', '\x00']
  17. MyObjectRef(123, 321)
  18. '''
  19. """
  20. type
  21. MyObjectRef = ref object
  22. a,b: int
  23. MyContainerObject = ref object
  24. member: MyObjectRef
  25. MySuperContainerObject = ref object
  26. member: MyContainerObject
  27. arr: array[4, MyObjectRef]
  28. MyOtherObject = ref object
  29. case kind: bool
  30. of true:
  31. member: MyObjectRef
  32. else:
  33. discard
  34. proc `$`(arg: MyObjectRef): string =
  35. result = "MyObjectRef("
  36. result.addInt arg.a
  37. result.add ", "
  38. result.addInt arg.b
  39. result.add ")"
  40. proc foobar(dst: var MyObjectRef) =
  41. dst = new(MyObjectRef)
  42. dst.a = 123
  43. dst.b = 321
  44. proc changeChar(c: var char) =
  45. c = 'A'
  46. proc test() =
  47. # when it comes from a var, it works
  48. var y: MyObjectRef
  49. foobar(y)
  50. echo y != nil
  51. # when it comes from a member, it fails on VM
  52. var x = new(MyContainerObject)
  53. foobar(x.member)
  54. echo x.member != nil
  55. # when it comes from an array, it fails on VM
  56. var arr: array[4, MyObjectRef]
  57. echo arr
  58. foobar(arr[0])
  59. echo arr
  60. var arr2: array[4, char]
  61. changeChar(arr2[0])
  62. echo arr2
  63. var z = MyOtherObject(kind: true)
  64. foobar(z.member)
  65. echo z.member
  66. # this still doesn't work
  67. # var sc = new(MySuperContainerObject)
  68. # sc.member = new(MyContainerObject)
  69. # foobar(sc.member.member)
  70. # echo sc.member.member
  71. # foobar(sc.arr[1])
  72. # echo sc.arr
  73. #var str = "---"
  74. #changeChar(str[1])
  75. #echo str
  76. test()
  77. static:
  78. test()
  79. type T = object
  80. f: seq[tuple[key, val: int]]
  81. proc foo(s: var seq[tuple[key, val: int]]; i: int) =
  82. s[i].key = 4*i
  83. # r4 = addr(s[i])
  84. # r4[0] = 4*i
  85. proc bar() =
  86. var s: T
  87. s.f = newSeq[tuple[key, val: int]](3)
  88. foo(s.f, 2)
  89. echo s.f[2]
  90. static:
  91. bar()