tmacros.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #[
  2. xxx macros tests need to be reorganized to makes sure each API is tested once
  3. See also:
  4. tests/macros/tdumpast.nim for treeRepr + friends
  5. ]#
  6. import std/macros
  7. block: # hasArgOfName
  8. macro m(u: untyped): untyped =
  9. for name in ["s","i","j","k","b","xs","ys"]:
  10. doAssert hasArgOfName(params u,name)
  11. doAssert not hasArgOfName(params u,"nonexistent")
  12. proc p(s: string; i,j,k: int; b: bool; xs,ys: seq[int] = @[]) {.m.} = discard
  13. block: # bug #17454
  14. proc f(v: NimNode): string {.raises: [].} = $v
  15. block: # unpackVarargs
  16. block:
  17. proc bar1(a: varargs[int]): string =
  18. for ai in a: result.add " " & $ai
  19. proc bar2(a: varargs[int]) =
  20. let s1 = bar1(a)
  21. let s2 = unpackVarargs(bar1, a) # `unpackVarargs` makes no difference here
  22. doAssert s1 == s2
  23. bar2(1, 2, 3)
  24. bar2(1)
  25. bar2()
  26. block:
  27. template call1(fun: typed; args: varargs[untyped]): untyped =
  28. unpackVarargs(fun, args)
  29. template call2(fun: typed; args: varargs[untyped]): untyped =
  30. # fun(args) # works except for last case with empty `args`, pending bug #9996
  31. when varargsLen(args) > 0: fun(args)
  32. else: fun()
  33. proc fn1(a = 0, b = 1) = discard (a, b)
  34. call1(fn1)
  35. call1(fn1, 10)
  36. call1(fn1, 10, 11)
  37. call2(fn1)
  38. call2(fn1, 10)
  39. call2(fn1, 10, 11)
  40. block:
  41. template call1(fun: typed; args: varargs[typed]): untyped =
  42. unpackVarargs(fun, args)
  43. template call2(fun: typed; args: varargs[typed]): untyped =
  44. # xxx this would give a confusing error message:
  45. # required type for a: varargs[typed] [varargs] but expression '[10]' is of type: varargs[typed] [varargs]
  46. when varargsLen(args) > 0: fun(args)
  47. else: fun()
  48. macro toString(a: varargs[typed, `$`]): string =
  49. var msg = genSym(nskVar, "msg")
  50. result = newStmtList()
  51. result.add quote do:
  52. var `msg` = ""
  53. for ai in a:
  54. result.add quote do: `msg`.add $`ai`
  55. result.add quote do: `msg`
  56. doAssert call1(toString) == ""
  57. doAssert call1(toString, 10) == "10"
  58. doAssert call1(toString, 10, 11) == "1011"