github.com/servernoj/jade@v0.0.0-20231225191405-efec98d19db1/node.go (about) 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 5 package jade 6 7 import ( 8 "bytes" 9 "io" 10 ) 11 12 // var textFormat = "%s" // Changed to "%q" in tests for better error messages. 13 14 // A Node is an element in the parse tree. The interface is trivial. 15 // The interface contains an unexported method so that only 16 // types local to this package can satisfy it. 17 type node interface { 18 Type() nodeType 19 String() string 20 WriteIn(io.Writer) 21 // Copy does a deep copy of the Node and all its components. 22 // To avoid type assertions, some XxxNodes also have specialized 23 // CopyXxx methods that return *XxxNode. 24 Copy() node 25 position() pos // byte position of start of node in full original input string 26 // tree returns the containing *tree. 27 // It is unexported so all implementations of Node are in this package. 28 tree() *tree 29 } 30 31 // pos represents a byte position in the original input text from which 32 // this template was parsed. 33 type pos int 34 35 func (p pos) position() pos { 36 return p 37 } 38 39 // Nodes. 40 41 // listNode holds a sequence of nodes. 42 type listNode struct { 43 nodeType 44 pos 45 tr *tree 46 Nodes []node // The element nodes in lexical order. 47 } 48 49 func (t *tree) newList(pos pos) *listNode { 50 return &listNode{tr: t, nodeType: nodeList, pos: pos} 51 } 52 53 func (l *listNode) append(n node) { 54 l.Nodes = append(l.Nodes, n) 55 } 56 57 func (l *listNode) tree() *tree { 58 return l.tr 59 } 60 61 func (l *listNode) String() string { 62 b := new(bytes.Buffer) 63 l.WriteIn(b) 64 return b.String() 65 } 66 func (l *listNode) WriteIn(b io.Writer) { 67 for _, n := range l.Nodes { 68 n.WriteIn(b) 69 } 70 } 71 72 func (l *listNode) CopyList() *listNode { 73 if l == nil { 74 return l 75 } 76 n := l.tr.newList(l.pos) 77 for _, elem := range l.Nodes { 78 n.append(elem.Copy()) 79 } 80 return n 81 } 82 83 func (l *listNode) Copy() node { 84 return l.CopyList() 85 }