tcallops.nim 987 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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)
  32. block: # bug #1072
  33. var x: int
  34. proc foo(some:int):int = some
  35. proc `()`(l,r:string): string = discard
  36. block:
  37. var foo = 42
  38. doAssert x.foo == 0