php-parser/node/node.go

71 lines
1.4 KiB
Go
Raw Normal View History

2017-12-03 18:49:18 +00:00
package node
import (
"bytes"
"fmt"
"github.com/z7zmey/php-parser/token"
"io"
)
type Node interface {
Print(out io.Writer, indent string)
Append(nn ...Node) Node
Attribute(key string, value string) Node
}
2017-12-04 21:24:12 +00:00
type SimpleNode struct {
Name string
Children []Node
Attributes map[string]string
2017-12-03 18:49:18 +00:00
}
type tokenNode struct {
2017-12-04 21:24:12 +00:00
*SimpleNode
2017-12-03 18:49:18 +00:00
token token.Token
}
2017-12-04 21:24:12 +00:00
func (n SimpleNode) String() string {
2017-12-03 18:49:18 +00:00
buf := new(bytes.Buffer)
n.Print(buf, " ")
return buf.String()
}
2017-12-04 21:24:12 +00:00
func (n SimpleNode) Print(out io.Writer, indent string) {
if len(n.Attributes) > 0 {
fmt.Fprintf(out, "\n%v%v %s", indent, n.Name, n.Attributes)
2017-12-03 18:49:18 +00:00
} else {
2017-12-04 21:24:12 +00:00
fmt.Fprintf(out, "\n%v%v", indent, n.Name)
2017-12-03 18:49:18 +00:00
}
2017-12-04 21:24:12 +00:00
for _, nn := range n.Children {
2017-12-03 18:49:18 +00:00
nn.Print(out, indent+" ")
}
}
2017-12-04 21:24:12 +00:00
func NewSimpleNode(name string) Node {
return SimpleNode{Name: name, Attributes: make(map[string]string)}
2017-12-03 18:49:18 +00:00
}
func TokenNode(name string, t token.Token) Node {
return tokenNode{
2017-12-04 21:24:12 +00:00
&SimpleNode{Name: name, Attributes: make(map[string]string)},
2017-12-03 18:49:18 +00:00
t,
}
}
func (n tokenNode) Print(out io.Writer, indent string) {
2017-12-04 21:24:12 +00:00
fmt.Fprintf(out, "\n%v%v [%d %d] %q", indent, n.Name, n.token.StartLine, n.token.EndLine, n.token.Value)
for _, nn := range n.Children {
2017-12-03 18:49:18 +00:00
nn.Print(out, indent+" ")
}
}
2017-12-04 21:24:12 +00:00
func (n SimpleNode) Append(nn ...Node) Node {
n.Children = append(n.Children, nn...)
2017-12-03 18:49:18 +00:00
return n
}
2017-12-04 21:24:12 +00:00
func (n SimpleNode) Attribute(key string, value string) Node {
n.Attributes[key] = value
2017-12-03 18:49:18 +00:00
return n
}