node.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package jade
  5. import (
  6. "bytes"
  7. "io"
  8. )
  9. // var textFormat = "%s" // Changed to "%q" in tests for better error messages.
  10. // A Node is an element in the parse tree. The interface is trivial.
  11. // The interface contains an unexported method so that only
  12. // types local to this package can satisfy it.
  13. type node interface {
  14. Type() nodeType
  15. String() string
  16. WriteIn(io.Writer)
  17. // Copy does a deep copy of the Node and all its components.
  18. // To avoid type assertions, some XxxNodes also have specialized
  19. // CopyXxx methods that return *XxxNode.
  20. Copy() node
  21. position() pos // byte position of start of node in full original input string
  22. // tree returns the containing *tree.
  23. // It is unexported so all implementations of Node are in this package.
  24. tree() *tree
  25. }
  26. // pos represents a byte position in the original input text from which
  27. // this template was parsed.
  28. type pos int
  29. func (p pos) position() pos {
  30. return p
  31. }
  32. // Nodes.
  33. // listNode holds a sequence of nodes.
  34. type listNode struct {
  35. nodeType
  36. pos
  37. tr *tree
  38. Nodes []node // The element nodes in lexical order.
  39. }
  40. func (t *tree) newList(pos pos) *listNode {
  41. return &listNode{tr: t, nodeType: nodeList, pos: pos}
  42. }
  43. func (l *listNode) append(n node) {
  44. l.Nodes = append(l.Nodes, n)
  45. }
  46. func (l *listNode) tree() *tree {
  47. return l.tr
  48. }
  49. func (l *listNode) String() string {
  50. b := new(bytes.Buffer)
  51. l.WriteIn(b)
  52. return b.String()
  53. }
  54. func (l *listNode) WriteIn(b io.Writer) {
  55. for _, n := range l.Nodes {
  56. n.WriteIn(b)
  57. }
  58. }
  59. func (l *listNode) CopyList() *listNode {
  60. if l == nil {
  61. return l
  62. }
  63. n := l.tr.newList(l.pos)
  64. for _, elem := range l.Nodes {
  65. n.append(elem.Copy())
  66. }
  67. return n
  68. }
  69. func (l *listNode) Copy() node {
  70. return l.CopyList()
  71. }