tmacro5.nim 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import macros,json
  2. var decls{.compileTime.}: seq[NimNode] = @[]
  3. var impls{.compileTime.}: seq[NimNode] = @[]
  4. macro importImpl_forward(name, returns: untyped): untyped =
  5. result = newNimNode(nnkEmpty)
  6. var func_name = newNimNode(nnkAccQuoted)
  7. func_name.add newIdentNode("import")
  8. func_name.add name
  9. var res = newNimNode(nnkProcDef)
  10. res.add newNimNode(nnkPostfix)
  11. res[0].add newIdentNode("*")
  12. res[0].add func_name
  13. res.add newNimNode(nnkEmpty)
  14. res.add newNimNode(nnkEmpty)
  15. res.add newNimNode(nnkFormalParams)
  16. res[3].add returns
  17. var p1 = newNimNode(nnkIdentDefs)
  18. p1.add newIdentNode("dat")
  19. p1.add newIdentNOde("JsonNode")
  20. p1.add newNimNode(nnkEmpty)
  21. res[3].add p1
  22. var p2 = newNimNode(nnkIdentDefs)
  23. p2.add newIdentNode("errors")
  24. p2.add newNimNode(nnkVarTy)
  25. p2.add newNimNode(nnkEmpty)
  26. p2[1].add newNimNode(nnkBracketExpr)
  27. p2[1][0].add newIdentNode("seq")
  28. p2[1][0].add newIdentNode("string")
  29. res[3].add p2
  30. res.add newNimNode(nnkEmpty)
  31. res.add newNimNode(nnkEmpty)
  32. res.add newNimNode(nnkEmpty)
  33. decls.add res
  34. echo(repr(res))
  35. macro importImpl(name, returns, body: untyped) =
  36. #var res = getAST(importImpl_forward(name, returns))
  37. discard getAST(importImpl_forward(name, returns))
  38. var res = copyNimTree(decls[decls.high])
  39. res[6] = body
  40. echo repr(res)
  41. impls.add res
  42. macro okayy() =
  43. result = newNimNode(nnkStmtList)
  44. for node in decls: result.add node
  45. for node in impls: result.add node
  46. importImpl(Item, int):
  47. echo 42
  48. importImpl(Foo, int16):
  49. echo 77
  50. okayy