trfc405.nim 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # https://github.com/nim-lang/RFCs/issues/405
  2. template main =
  3. template fn1(a = 1, b = 2, body): auto = (a, b, astToStr(body))
  4. let a1 = fn1(10, 20):
  5. foo
  6. doAssert a1 == (10, 20, "\nfoo")
  7. template fn2(a = 1, b = 2, body): auto = (a, b, astToStr(body))
  8. let a2 = fn2(a = 10): foo
  9. doAssert a2 == (10, 2, "\nfoo")
  10. let a2b = fn2(b = 20): foo
  11. doAssert a2b == (1, 20, "\nfoo")
  12. template fn3(x: int, a = 1, b = 2, body): auto = (a, b, astToStr(body))
  13. let a3 = fn3(3, 10, 20): foo
  14. doAssert a3 == (10, 20, "\nfoo")
  15. let a3b = fn3(3, a = 10): foo
  16. doAssert a3b == (10, 2, "\nfoo")
  17. template fn4(x: int, y: int, body): auto = (x, y, astToStr(body))
  18. let a4 = fn4(1, 2): foo
  19. doAssert a4 == (1, 2, "\nfoo")
  20. template fn5(x = 1, y = 2, body: untyped = 3): auto = (x, y, astToStr(body))
  21. doAssert compiles(fn5(1, 2, foo))
  22. doAssert not compiles(fn5(1, foo))
  23. block:
  24. # with an overload
  25. var witness = 0
  26. template fn6() = discard
  27. template fn6(procname: string, body: untyped): untyped = witness.inc
  28. fn6("abc"): discard
  29. assert witness == 1
  30. block:
  31. # with overloads
  32. var witness = 0
  33. template fn6() = discard
  34. template fn6(a: int) = discard
  35. template fn6(procname: string, body: untyped): untyped = witness.inc
  36. fn6("abc"): discard
  37. assert witness == 1
  38. template fn6(b = 1.5, body: untyped): untyped = witness.inc
  39. fn6(1.3): discard
  40. assert witness == 2
  41. block:
  42. var witness = 0
  43. template fn6(a: int) = discard
  44. template fn6(a: string) = discard
  45. template fn6(ignore: string, b = 1.5, body: untyped): untyped = witness.inc
  46. fn6(""):
  47. foobar1
  48. foobar2
  49. doAssert witness == 1
  50. fn6(""): discard
  51. doAssert witness == 2
  52. block: # multi block args
  53. template fn8(a = 1, b = 2, body1: untyped, body2: untyped): auto = (a, b, astToStr(body1), astToStr(body2))
  54. let a1 = fn8():
  55. foobar1
  56. foobar2
  57. do:
  58. foobar3
  59. foobar4
  60. doAssert a1 == (1, 2, "\nfoobar1\nfoobar2", "\nfoobar3\nfoobar4")
  61. let a2 = fn8(b = 20):
  62. foobar1
  63. foobar2
  64. do:
  65. foobar3
  66. foobar4
  67. doAssert a2 == (1, 20, "\nfoobar1\nfoobar2", "\nfoobar3\nfoobar4")
  68. static: main()
  69. main()