outparams.nim 931 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2022 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## `outParamsAt` macro for easy writing code that works with both 2.0 and 1.x.
  10. import macros
  11. macro outParamsAt*(positions: static openArray[int]; n: untyped): untyped =
  12. ## Use this macro to annotate `out` parameters in a portable way.
  13. runnableExamples:
  14. proc p(x: var int) {.outParamsAt: [1].} =
  15. discard "x is really an 'out int' if the Nim compiler supports 'out' parameters"
  16. result = n
  17. when defined(nimHasOutParams):
  18. var p = n.params
  19. for po in positions:
  20. p[po][^2].expectKind nnkVarTy
  21. p[po][^2] = newTree(nnkOutTy, p[po][^2][0])
  22. when isMainModule:
  23. {.experimental: "strictDefs".}
  24. proc main(x: var int) {.outParamsAt: [1].} =
  25. x = 3
  26. proc us =
  27. var x: int
  28. main x
  29. echo x
  30. us()