decls.nim 1000 B

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