Skip to content

Commit 24f3433

Browse files
committed
sugar: add var x syntax to =>
Summary ======= Allow prefixing parameter names with `var`, to designate the parameter as being a `var` parameter. Details ======= Type parameters cannot be inferred as `var`, and therefore it's effectively not possible to use the `=>` macro for creating anonymous procedures where the procedures needs `var` parameters. The `x: T` syntax does exist, but it applies to all preceding parameter, limiting its usefulness. To address the aforementioned shortcoming, the `var x` syntax is now supported (example: `(x, var y) => x`), assigning `var auto` as the respective parameter's type. Due a NimSkull syntax/parser limitation, `var x` cannot be used as the first parameter.
1 parent f313cfc commit 24f3433

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/pure/sugar.nim

+6-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ proc createProcType(p, b: NimNode): NimNode =
5353
result.add prag
5454

5555
macro `=>`*(p, b: untyped): untyped =
56-
## Syntax sugar for anonymous procedures. It also supports pragmas.
56+
## Syntax sugar for anonymous procedures. It also supports pragmas. Prefixing
57+
## a parameter name with ``var`` makes the parameter a var parameter.
5758
##
5859
## .. warning:: Semicolons can not be used to separate procedure arguments.
5960
runnableExamples:
@@ -109,6 +110,10 @@ macro `=>`*(p, b: untyped): untyped =
109110
identDefs.add(newIdentNode("auto"))
110111
identDefs.add(newEmptyNode())
111112
inc untypedBeforeColon
113+
of nnkVarTy:
114+
identDefs.add(c[0])
115+
identDefs.add(newTree(nnkVarTy, newIdentNode("auto")))
116+
identDefs.add(newEmptyNode())
112117
of nnkInfix:
113118
if c[0].kind == nnkIdent and c[0].eqIdent"->":
114119
var procTy = createProcType(c[1], c[2])

tests/lang_callable/macros/tsugar_closuremacro.nim

+21
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,24 @@ type
7878
var myBot = Bot()
7979
myBot.call = () {.noSideEffect.} => "I'm a bot."
8080
doAssert myBot.call() == "I'm a bot."
81+
82+
proc singleVar(p: (var int) -> int): int =
83+
var x = 0
84+
discard p(x)
85+
x
86+
87+
doAssert singleVar((x: var auto) => (inc x; x)) == 1
88+
89+
proc trailingVar(p: (int, var int) -> int): int =
90+
var x = 0
91+
discard p(1, x)
92+
x
93+
94+
doAssert trailingVar((x, var y) => (y += x; 0)) == 1
95+
96+
proc multiVar(p: (int, var int, var int) -> int): int =
97+
var x, y = 0
98+
discard p(1, x, y)
99+
x
100+
101+
doAssert multiVar((x, var y, var z) => x) == 0

0 commit comments

Comments
 (0)