tclosuremacro.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. discard """
  2. output: '''
  3. noReturn
  4. calling mystuff
  5. yes
  6. calling mystuff
  7. yes
  8. '''
  9. """
  10. import sugar, macros
  11. proc twoParams(x: (int, int) -> int): int =
  12. result = x(5, 5)
  13. proc oneParam(x: int -> int): int =
  14. x(5)
  15. proc noParams(x: () -> int): int =
  16. result = x()
  17. proc noReturn(x: () -> void) =
  18. x()
  19. proc doWithOneAndTwo(f: (int, int) -> int): int =
  20. f(1,2)
  21. doAssert twoParams(proc (a, b: auto): auto = a + b) == 10
  22. doAssert twoParams((x, y) => x + y) == 10
  23. doAssert oneParam(x => x+5) == 10
  24. doAssert noParams(() => 3) == 3
  25. doAssert doWithOneAndTwo((x, y) => x + y) == 3
  26. noReturn((() -> void) => echo("noReturn"))
  27. proc pass2(f: (int, int) -> int): (int) -> int =
  28. ((x: int) -> int) => f(2, x)
  29. doAssert pass2((x, y) => x + y)(4) == 6
  30. const fun = (x, y: int) {.noSideEffect.} => x + y
  31. doAssert typeof(fun) is (proc (x, y: int): int {.nimcall.})
  32. doAssert fun(3, 4) == 7
  33. proc register(name: string; x: proc()) =
  34. echo "calling ", name
  35. x()
  36. register("mystuff", proc () =
  37. echo "yes"
  38. )
  39. proc helper(x: NimNode): NimNode =
  40. if x.kind == nnkProcDef:
  41. result = copyNimTree(x)
  42. result[0] = newEmptyNode()
  43. result = newCall("register", newLit($x[0]), result)
  44. else:
  45. result = copyNimNode(x)
  46. for i in 0..<x.len:
  47. result.add helper(x[i])
  48. macro m(x: untyped): untyped =
  49. result = helper(x)
  50. m:
  51. proc mystuff() =
  52. echo "yes"
  53. const typedParamAndPragma = (x, y: int) -> int => x + y
  54. doAssert typedParamAndPragma(1, 2) == 3
  55. type
  56. Bot = object
  57. call: proc (): string {.noSideEffect.}
  58. var myBot = Bot()
  59. myBot.call = () {.noSideEffect.} => "I'm a bot."
  60. doAssert myBot.call() == "I'm a bot."