tnimnode.nim 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import macros
  2. proc assertEq(arg0,arg1: string): void =
  3. if arg0 != arg1:
  4. raiseAssert("strings not equal:\n" & arg0 & "\n" & arg1)
  5. # a simple assignment of stmtList to another variable
  6. var node {.compileTime.}: NimNode
  7. # an assignment of stmtList into an array
  8. var nodeArray {.compileTime.}: array[1, NimNode]
  9. # an assignment of stmtList into a seq
  10. var nodeSeq {.compileTime.} = newSeq[NimNode](2)
  11. proc checkNode(arg: NimNode; name: string): void {. compileTime .} =
  12. echo "checking ", name
  13. assertEq arg.lispRepr, """(StmtList (DiscardStmt (Empty)))"""
  14. node = arg
  15. nodeArray = [arg]
  16. nodeSeq[0] = arg
  17. var seqAppend = newSeq[NimNode](0)
  18. seqAppend.add([arg]) # at the time of this writing this works
  19. seqAppend.add(arg) # bit this creates a copy
  20. arg.add newCall(ident"echo", newLit("Hello World"))
  21. assertEq arg.lispRepr, """(StmtList (DiscardStmt (Empty)) (Call (Ident "echo") (StrLit "Hello World")))"""
  22. assertEq node.lispRepr, """(StmtList (DiscardStmt (Empty)) (Call (Ident "echo") (StrLit "Hello World")))"""
  23. assertEq nodeArray[0].lispRepr, """(StmtList (DiscardStmt (Empty)) (Call (Ident "echo") (StrLit "Hello World")))"""
  24. assertEq nodeSeq[0].lispRepr, """(StmtList (DiscardStmt (Empty)) (Call (Ident "echo") (StrLit "Hello World")))"""
  25. assertEq seqAppend[0].lispRepr, """(StmtList (DiscardStmt (Empty)) (Call (Ident "echo") (StrLit "Hello World")))"""
  26. assertEq seqAppend[1].lispRepr, """(StmtList (DiscardStmt (Empty)) (Call (Ident "echo") (StrLit "Hello World")))"""
  27. echo "OK"
  28. # the root node that is used to generate the Ast
  29. var stmtList {.compileTime.}: NimNode
  30. static:
  31. stmtList = newStmtList(nnkDiscardStmt.newTree(newEmptyNode()))
  32. checkNode(stmtList, "direct construction")
  33. macro foo(stmtList: untyped): untyped =
  34. checkNode(stmtList, "untyped macro argument")
  35. foo:
  36. discard
  37. static:
  38. stmtList = quote do:
  39. discard
  40. checkNode(newTree(nnkStmtList, stmtList), "create with quote")
  41. static:
  42. echo "testing body from loop"
  43. var loop = quote do:
  44. for i in 0 ..< 10:
  45. discard
  46. let innerBody = loop[2]
  47. innerBody.add newCall(ident"echo", newLit("Hello World"))
  48. assertEq loop[2].lispRepr, innerBody.lispRepr
  49. echo "OK"
  50. static:
  51. echo "testing creation of comment node"
  52. var docComment: NimNode = newNimNode(nnkCommentStmt)
  53. docComment.strVal = "This is a doc comment"
  54. assertEq repr(docComment), "## This is a doc comment"
  55. echo "OK"