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. }