diff options
Diffstat (limited to 'lib/std/with.nim')
-rw-r--r-- | lib/std/with.nim | 33 |
1 files changed, 15 insertions, 18 deletions
diff --git a/lib/std/with.nim b/lib/std/with.nim index c1ac96fcb..c2eaa4bef 100644 --- a/lib/std/with.nim +++ b/lib/std/with.nim @@ -7,20 +7,21 @@ # distribution, for details about the copyright. # -## This module implements the ``with`` macro for easy +## 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. +## **Since:** version 1.2. -import macros, private / underscored_calls +import std/[macros, private / underscored_calls] macro with*(arg: typed; calls: varargs[untyped]): untyped = - ## This macro provides the `chaining`:idx: of function calls. + ## This macro provides `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!** + ## + ## .. caution:: This evaluates `arg` multiple times! runnableExamples: var x = "yay" with x: @@ -34,18 +35,14 @@ macro with*(arg: typed; calls: varargs[untyped]): untyped = -= 5 doAssert a == 43 + # Nesting works for object types too! + var foo = (bar: 1, qux: (baz: 2)) + with foo: + bar = 2 + with qux: + baz = 3 + doAssert foo.bar == 2 + doAssert foo.qux.baz == 3 + result = newNimNode(nnkStmtList, arg) underscoredCalls(result, calls, arg) - -when isMainModule: - type - Foo = object - col, pos: 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 - |