tcallops.nim 828 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import macros
  2. {.experimental: "callOperator".}
  3. type Foo[T: proc] = object
  4. callback: T
  5. macro `()`(foo: Foo, args: varargs[untyped]): untyped =
  6. result = newCall(newDotExpr(foo, ident"callback"))
  7. for a in args:
  8. result.add(a)
  9. var f1Calls = 0
  10. var f = Foo[proc()](callback: proc() = inc f1Calls)
  11. doAssert f1Calls == 0
  12. f()
  13. doAssert f1Calls == 1
  14. var f2Calls = 0
  15. f.callback = proc() = inc f2Calls
  16. doAssert f2Calls == 0
  17. f()
  18. doAssert f2Calls == 1
  19. let g = Foo[proc (x: int): int](callback: proc (x: int): int = x * 2 + 1)
  20. doAssert g(15) == 31
  21. proc `()`(args: varargs[string]): string =
  22. result = "("
  23. for a in args: result.add(a)
  24. result.add(')')
  25. let a = "1"
  26. let b = "2"
  27. let c = "3"
  28. doAssert a(b) == "(12)"
  29. doAssert a.b(c) == `()`(b, a, c)
  30. doAssert (a.b)(c) == `()`(a.b, c)
  31. doAssert `()`(a.b, c) == `()`(`()`(b, a), c)