File: with.nim

package info (click to toggle)
nim 1.4.6%2Breally1.4.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 936,800 kB
  • sloc: sh: 17,201; ansic: 4,767; makefile: 856; python: 407; sql: 298; asm: 141; xml: 13
file content (58 lines) | stat: -rw-r--r-- 1,392 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#
#
#            Nim's Runtime Library
#        (c) Copyright 2020 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module implements the ``with`` macro for easy
## function chaining. See https://github.com/nim-lang/RFCs/issues/193
## and https://github.com/nim-lang/RFCs/issues/192 for details leading to this
## particular design.
##
## **Since** version 1.2.

import macros, private / underscored_calls

macro with*(arg: typed; calls: varargs[untyped]): untyped =
  ## This macro provides the `chaining`:idx: of function calls.
  ## It does so by patching every call in `calls` to
  ## use `arg` as the first argument.
  ## **This evaluates `arg` multiple times!**
  runnableExamples:
    var x = "yay"
    with x:
      add "abc"
      add "efg"
    doAssert x == "yayabcefg"

    var a = 44
    with a:
      += 4
      -= 5
    doAssert a == 43

  result = newNimNode(nnkStmtList, arg)
  underscoredCalls(result, calls, arg)

when isMainModule:
  type
    Foo = object
      col, pos: string
      name: string

  proc setColor(f: var Foo; r, g, b: int) = f.col = $(r, g, b)
  proc setPosition(f: var Foo; x, y: float) = f.pos = $(x, y)

  var f: Foo
  with(f, setColor(2, 3, 4), setPosition(0.0, 1.0))
  echo f

  f = Foo()
  with f:
    col = $(2, 3, 4)
    pos = $(0.0, 1.0)
    _.name = "bar"
  echo f