node.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. tab int
  40. }
  41. func (t *Tree) newList(pos Pos) *ListNode {
  42. return &ListNode{tr: t, NodeType: NodeList, Pos: pos, tab: t.tab}
  43. }
  44. func (l *ListNode) append(n Node) {
  45. l.Nodes = append(l.Nodes, n)
  46. }
  47. func (l *ListNode) tree() *Tree {
  48. return l.tr
  49. }
  50. func (l *ListNode) String() string {
  51. b := new(bytes.Buffer)
  52. l.WriteIn(b)
  53. return b.String()
  54. }
  55. func (l *ListNode) WriteIn(b io.Writer) {
  56. for _, n := range l.Nodes {
  57. n.WriteIn(b)
  58. }
  59. }
  60. func (l *ListNode) CopyList() *ListNode {
  61. if l == nil {
  62. return l
  63. }
  64. n := l.tr.newList(l.Pos)
  65. for _, elem := range l.Nodes {
  66. n.append(elem.Copy())
  67. }
  68. return n
  69. }
  70. func (l *ListNode) Copy() Node {
  71. return l.CopyList()
  72. }