decls.nim 985 B

1234567891011121314151617181920212223242526272829303132
  1. ## This module implements syntax sugar for some declarations.
  2. import macros
  3. macro byaddr*(sect) =
  4. ## Allows a syntax for l-value references, being an exact analog to
  5. ## `auto& a = ex;` in C++.
  6. ##
  7. ## .. warning:: This makes use of 2 experimental features, namely nullary
  8. ## templates instantiated as symbols and variable macro pragmas.
  9. ## For this reason, its behavior is not stable. The current implementation
  10. ## allows redefinition, but this is not an intended consequence.
  11. runnableExamples:
  12. var s = @[10, 11, 12]
  13. var a {.byaddr.} = s[0]
  14. a += 100
  15. assert s == @[110, 11, 12]
  16. assert a is int
  17. var b {.byaddr.}: int = s[0]
  18. assert a.addr == b.addr
  19. expectLen sect, 1
  20. let def = sect[0]
  21. let
  22. lhs = def[0]
  23. typ = def[1]
  24. ex = def[2]
  25. addrTyp = if typ.kind == nnkEmpty: typ else: newTree(nnkPtrTy, typ)
  26. result = quote do:
  27. let tmp: `addrTyp` = addr(`ex`)
  28. template `lhs`: untyped = tmp[]
  29. result.copyLineInfo(def)