tmacros_various.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. discard """
  2. nimout: '''
  3. Infix
  4. Ident "=>"
  5. Call
  6. Ident "name"
  7. Ident "a"
  8. ExprColonExpr
  9. Ident "b"
  10. Ident "cint"
  11. NilLit
  12. '''
  13. output: '''
  14. x = 10
  15. x + y = 30
  16. proc foo[T, N: static[int]]()
  17. proc foo[T; N: static[int]]()
  18. a[0]: 42
  19. a[1]: 45
  20. x: some string
  21. '''
  22. """
  23. import macros, sugar
  24. block tdump:
  25. let
  26. x = 10
  27. y = 20
  28. dump x
  29. dump(x + y)
  30. block texprcolonexpr:
  31. macro def(x): untyped =
  32. echo treeRepr(x)
  33. def name(a, b:cint) => nil
  34. block tgenericparams:
  35. macro test():string =
  36. let expr0 = "proc foo[T, N: static[int]]()"
  37. let expr1 = "proc foo[T; N: static[int]]()"
  38. $toStrLit(parseExpr(expr0)) & "\n" & $toStrLit(parseExpr(expr1))
  39. echo test()
  40. block tidgen:
  41. # Test compile-time state in same module
  42. var gid {.compileTime.} = 3
  43. macro genId(): int =
  44. result = newIntLitNode(gid)
  45. inc gid
  46. proc Id1(): int {.compileTime.} = return genId()
  47. proc Id2(): int {.compileTime.} = return genId()
  48. doAssert Id1() == 3
  49. doAssert Id2() == 4
  50. block tlexerex:
  51. macro match(s: cstring|string; pos: int; sections: varargs[untyped]): untyped =
  52. for sec in sections:
  53. expectKind sec, nnkOfBranch
  54. expectLen sec, 2
  55. result = newStmtList()
  56. var input = "the input"
  57. var pos = 0
  58. match input, pos:
  59. of r"[a-zA-Z_]\w+": echo "an identifier"
  60. of r"\d+": echo "an integer"
  61. of r".": echo "something else"
  62. block tlineinfo:
  63. # issue #5617, feature request
  64. type Test = object
  65. macro mixer(n: typed): untyped =
  66. let x = newIdentNode("echo")
  67. x.copyLineInfo(n)
  68. result = newLit(x.lineInfo == n.lineInfo)
  69. var z = mixer(Test)
  70. doAssert z
  71. block tdebugstmt:
  72. macro debug(n: varargs[untyped]): untyped =
  73. result = newNimNode(nnkStmtList, n)
  74. for i in 0..n.len-1:
  75. add(result, newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
  76. add(result, newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
  77. add(result, newCall("writeLine", newIdentNode("stdout"), n[i]))
  78. var
  79. a: array[0..10, int]
  80. x = "some string"
  81. a[0] = 42
  82. a[1] = 45
  83. debug(a[0], a[1], x)