t21184.nim 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. discard """
  2. matrix: "--mm:orc"
  3. """
  4. import std/[with]
  5. type
  6. Node* {.acyclic.} = ref object of RootObj
  7. name: string
  8. data: pointer
  9. children: seq[Node]
  10. TextNode = ref object of Node
  11. text: string
  12. proc fakeEcho(s: string) =
  13. if s.len < 0:
  14. echo s
  15. proc newNode[T: Node](parent: Node): T =
  16. new result
  17. result.data = alloc0(250)
  18. parent.children.add(result)
  19. proc newRootNode(): Node =
  20. new result
  21. result.data = alloc0(250)
  22. method printNode(node: Node) {.base.} =
  23. fakeEcho node.name
  24. method printNode(node: TextNode) =
  25. procCall printNode(Node(node))
  26. fakeEcho node.text
  27. proc printChildren(node: Node) =
  28. for child in node.children:
  29. child.printNode()
  30. printChildren(child)
  31. proc free(node: Node) =
  32. for child in node.children:
  33. free(child)
  34. dealloc(node.data)
  35. template node(parent: Node, body: untyped): untyped =
  36. var node = newNode[Node](parent)
  37. with node:
  38. body
  39. proc textNode(parent: Node, text: string) =
  40. var node = newNode[TextNode](parent)
  41. node.text = text
  42. template withRootNode(body: untyped): untyped =
  43. var root = newRootNode()
  44. root.name = "root"
  45. with root:
  46. body
  47. root.printNode()
  48. printChildren(root)
  49. root.free()
  50. proc doTest() =
  51. withRootNode:
  52. node:
  53. name = "child1"
  54. node:
  55. name = "child2"
  56. node:
  57. name = "child3"
  58. textNode "Hello, world!"
  59. # bug #21171
  60. if isMainModule:
  61. for i in 0..100000:
  62. doTest()