tclosuremacro.nim 1.2 KB

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