tdefaultparam.nim 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. block:
  2. template foo(a: untyped, b: untyped = a(0)): untyped =
  3. let x = a(0)
  4. let y = b
  5. (x, y)
  6. proc bar(x: int): int = x + 1
  7. doAssert foo(bar, b = bar(0)) == (1, 1)
  8. doAssert foo(bar) == (1, 1)
  9. block: # issue #23506
  10. var a: string
  11. template foo(x: int; y = x) =
  12. a = $($x, $y)
  13. foo(1)
  14. doAssert a == "(\"1\", \"1\")"
  15. block: # untyped params with default value
  16. macro foo(x: typed): untyped =
  17. result = x
  18. template test(body: untyped, alt: untyped = (;), maxTries = 3): untyped {.foo.} =
  19. body
  20. alt
  21. var s = "a"
  22. test:
  23. s.add "b"
  24. do:
  25. s.add "c"
  26. doAssert s == "abc"
  27. template test2(body: untyped, alt: untyped = s.add("e"), maxTries = 3): untyped =
  28. body
  29. alt
  30. test2:
  31. s.add "d"
  32. doAssert s == "abcde"
  33. template test3(body: untyped = willNotCompile) =
  34. discard
  35. test3()
  36. block: # typed params with `void` default value
  37. macro foo(x: typed): untyped =
  38. result = x
  39. template test(body: untyped, alt: typed = (;), maxTries = 3): untyped {.foo.} =
  40. body
  41. alt
  42. var s = "a"
  43. test:
  44. s.add "b"
  45. do:
  46. s.add "c"
  47. doAssert s == "abc"
  48. template test2(body: untyped, alt: typed = s.add("e"), maxTries = 3): untyped =
  49. body
  50. alt
  51. test2:
  52. s.add "d"
  53. doAssert s == "abcde"