tnimnode.nim 2.3 KB

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