with.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the ``with`` macro for easy
  10. ## function chaining. See https://github.com/nim-lang/RFCs/issues/193
  11. ## and https://github.com/nim-lang/RFCs/issues/192 for details leading to this
  12. ## particular design.
  13. ##
  14. ## **Since** version 1.2.
  15. import macros, private / underscored_calls
  16. macro with*(arg: typed; calls: varargs[untyped]): untyped =
  17. ## This macro provides the `chaining`:idx: of function calls.
  18. ## It does so by patching every call in `calls` to
  19. ## use `arg` as the first argument.
  20. ## **This evaluates `arg` multiple times!**
  21. runnableExamples:
  22. var x = "yay"
  23. with x:
  24. add "abc"
  25. add "efg"
  26. doAssert x == "yayabcefg"
  27. var a = 44
  28. with a:
  29. += 4
  30. -= 5
  31. doAssert a == 43
  32. result = newNimNode(nnkStmtList, arg)
  33. underscoredCalls(result, calls, arg)
  34. when isMainModule:
  35. type
  36. Foo = object
  37. col, pos: string
  38. name: string
  39. proc setColor(f: var Foo; r, g, b: int) = f.col = $(r, g, b)
  40. proc setPosition(f: var Foo; x, y: float) = f.pos = $(x, y)
  41. var f: Foo
  42. with(f, setColor(2, 3, 4), setPosition(0.0, 1.0))
  43. echo f
  44. f = Foo()
  45. with f:
  46. col = $(2, 3, 4)
  47. pos = $(0.0, 1.0)
  48. _.name = "bar"
  49. echo f