-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringify.go
52 lines (45 loc) · 950 Bytes
/
stringify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package condition
import (
"bytes"
"fmt"
"io"
)
func Stringify(root *Node) string {
buf := bytes.NewBuffer(nil)
stringify(buf, root, "")
return buf.String()
}
func getNodeName(n *Node) string {
if n == nil {
return "NULL"
}
switch n.Type {
case NodeTypeLiteral:
return fmt.Sprintf("%s", n.Token.String())
case NodeTypeArray:
return "ARRAY"
case NodeTypeFunction:
return fmt.Sprintf("FUNCTION<%s>", n.Token.Value.(string))
}
return "UNKNOWN"
}
func stringify(w io.Writer, node *Node, prefix string) {
fmt.Fprintf(w, "%s%s\n", prefix, getNodeName(node))
if len(prefix) >= 4 {
pos := len(prefix) - 4
if prefix[pos] == '|' {
prefix = prefix[:pos] + "| "
} else {
prefix = prefix[:pos] + " "
}
}
if len(node.Children) > 0 {
for i, child := range node.Children {
if i == len(node.Children)-1 {
stringify(w, child, prefix+" \\_ ")
} else {
stringify(w, child, prefix+"|__ ")
}
}
}
}