tdumpast.nim 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Dump the contents of a NimNode
  2. import macros
  3. template plus(a, b: untyped): untyped {.dirty} =
  4. a + b
  5. macro call(e: untyped): untyped =
  6. result = newCall("foo", newStrLitNode("bar"))
  7. macro dumpAST(n: untyped): untyped =
  8. # dump AST as a side-effect and return the inner node
  9. let n = callsite()
  10. echo n.lispRepr
  11. echo n.treeRepr
  12. var plusAst = getAst(plus(1, 2))
  13. echo plusAst.lispRepr
  14. var callAst = getAst(call(4))
  15. echo callAst.lispRepr
  16. var e = parseExpr("foo(bar + baz)")
  17. echo e.lispRepr
  18. result = n[1]
  19. dumpAST:
  20. proc add(x, y: int): int =
  21. return x + y
  22. proc sub(x, y: int): int = return x - y
  23. macro fun() =
  24. let n = quote do:
  25. 1+1 == 2
  26. doAssert n.repr == "1 + 1 == 2", n.repr
  27. fun()
  28. macro fun2(): untyped =
  29. let n = quote do:
  30. 1 + 2 * 3 == 1 + 6
  31. doAssert n.repr == "1 + 2 * 3 == 1 + 6", n.repr
  32. fun2()
  33. macro fun3(): untyped =
  34. let n = quote do:
  35. int | float | array | seq | object | ptr | pointer | float32
  36. doAssert n.repr == "int | float | array | seq | object | ptr | pointer | float32", n.repr
  37. fun3()