File: outparams.nim

package info (click to toggle)
nim 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,911,644 kB
  • sloc: sh: 24,603; ansic: 1,761; python: 1,492; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (38 lines) | stat: -rw-r--r-- 935 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#
#
#            Nim's Runtime Library
#        (c) Copyright 2022 Nim contributors
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## `outParamsAt` macro for easy writing code that works with both 2.0 and 1.x.

import std/macros

macro outParamsAt*(positions: static openArray[int]; n: untyped): untyped =
  ## Use this macro to annotate `out` parameters in a portable way.
  runnableExamples:
    proc p(x: var int) {.outParamsAt: [1].} =
      discard "x is really an 'out int' if the Nim compiler supports 'out' parameters"

  result = n
  when defined(nimHasOutParams):
    var p = n.params
    for po in positions:
      p[po][^2].expectKind nnkVarTy
      p[po][^2] = newTree(nnkOutTy, p[po][^2][0])

when isMainModule:
  {.experimental: "strictDefs".}

  proc main(x: var int) {.outParamsAt: [1].} =
    x = 3

  proc us =
    var x: int
    main x
    echo x

  us()