Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sugar: add var x syntax to => #1492

Merged
merged 1 commit into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/pure/sugar.nim
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ proc createProcType(p, b: NimNode): NimNode =
result.add prag

macro `=>`*(p, b: untyped): untyped =
## Syntax sugar for anonymous procedures. It also supports pragmas.
## Syntax sugar for anonymous procedures. It also supports pragmas. Prefixing
## a parameter name with ``var`` makes the parameter a var parameter.
##
## .. warning:: Semicolons can not be used to separate procedure arguments.
runnableExamples:
Expand Down Expand Up @@ -109,6 +110,10 @@ macro `=>`*(p, b: untyped): untyped =
identDefs.add(newIdentNode("auto"))
identDefs.add(newEmptyNode())
inc untypedBeforeColon
of nnkVarTy:
identDefs.add(c[0])
identDefs.add(newTree(nnkVarTy, newIdentNode("auto")))
identDefs.add(newEmptyNode())
of nnkInfix:
if c[0].kind == nnkIdent and c[0].eqIdent"->":
var procTy = createProcType(c[1], c[2])
Expand Down
21 changes: 21 additions & 0 deletions tests/lang_callable/macros/tsugar_closuremacro.nim
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,24 @@ type
var myBot = Bot()
myBot.call = () {.noSideEffect.} => "I'm a bot."
doAssert myBot.call() == "I'm a bot."

proc singleVar(p: (var int) -> int): int =
var x = 0
discard p(x)
x

doAssert singleVar((x: var auto) => (inc x; x)) == 1

proc trailingVar(p: (int, var int) -> int): int =
var x = 0
discard p(1, x)
x

doAssert trailingVar((x, var y) => (y += x; 0)) == 1

proc multiVar(p: (int, var int, var int) -> int): int =
var x, y = 0
discard p(1, x, y)
x

doAssert multiVar((x, var y, var z) => x) == 0
Loading