tdecls.nim 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import std/decls
  2. block:
  3. var s = @[10,11,12]
  4. var a {.byaddr.} = s[0]
  5. a+=100
  6. doAssert s == @[110,11,12]
  7. doAssert a is int
  8. var b {.byaddr.}: int = s[0]
  9. doAssert a.addr == b.addr
  10. doAssert not compiles(block:
  11. # redeclaration not allowed
  12. var foo = 0
  13. var foo {.byaddr.} = s[0])
  14. doAssert not compiles(block:
  15. # ditto
  16. var foo {.byaddr.} = s[0]
  17. var foo {.byaddr.} = s[0])
  18. block:
  19. var b {.byaddr.} = s[1] # redeclaration ok in sub scope
  20. b = 123
  21. doAssert s == @[110,123,12]
  22. b = b * 10
  23. doAssert s == @[1100,123,12]
  24. doAssert not compiles(block:
  25. var b2 {.byaddr.}: float = s[2])
  26. doAssert compiles(block:
  27. var b2 {.byaddr.}: int = s[2])
  28. ## We can define custom pragmas in user code
  29. template byUnsafeAddr(lhs, typ, expr) =
  30. when typ is type(nil):
  31. let tmp = unsafeAddr(expr)
  32. else:
  33. let tmp: ptr typ = unsafeAddr(expr)
  34. template lhs: untyped = tmp[]
  35. block:
  36. let s = @["foo", "bar"]
  37. let a {.byUnsafeAddr.} = s[0]
  38. doAssert a == "foo"
  39. doAssert a[0].unsafeAddr == s[0][0].unsafeAddr
  40. block: # nkAccQuoted
  41. # shows using a keyword, which requires nkAccQuoted
  42. template `cast`(lhs, typ, expr) =
  43. when typ is type(nil):
  44. let tmp = unsafeAddr(expr)
  45. else:
  46. let tmp: ptr typ = unsafeAddr(expr)
  47. template lhs: untyped = tmp[]
  48. block:
  49. let s = @["foo", "bar"]
  50. let a {.`byUnsafeAddr`.} = s[0]
  51. doAssert a == "foo"
  52. doAssert a[0].unsafeAddr == s[0][0].unsafeAddr
  53. block:
  54. let s = @["foo", "bar"]
  55. let a {.`cast`.} = s[0]
  56. doAssert a == "foo"
  57. doAssert a[0].unsafeAddr == s[0][0].unsafeAddr