forked from alecthomas/participle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
63 lines (51 loc) · 1.31 KB
/
printer.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
53
54
55
56
57
58
59
60
61
62
63
package participle
import (
"fmt"
"strings"
"github.com/alecthomas/participle/lexer"
)
func dumpNode(v node) string {
seen := map[node]bool{}
return nodePrinter(seen, v)
}
func nodePrinter(seen map[node]bool, v node) string {
if seen[v] {
return "<>"
}
seen[v] = true
switch n := v.(type) {
case *disjunction:
out := []string{}
for _, n := range n.nodes {
out = append(out, nodePrinter(seen, n))
}
return strings.Join(out, "|")
case *strct:
return fmt.Sprintf("strct(type=%s, expr=%s)", n.typ, nodePrinter(seen, n.expr))
case *sequence:
out := []string{}
for c := n; c != nil; c = c.next {
out = append(out, nodePrinter(seen, c.node))
}
return fmt.Sprintf("(%s)", strings.Join(out, " "))
case *capture:
return fmt.Sprintf("@(field=%s, node=%s)", n.field.Name, nodePrinter(seen, n.node))
case *reference:
return fmt.Sprintf("%s", n.identifier)
case *optional:
if n.next != nil {
return fmt.Sprintf("[%s] %s", nodePrinter(seen, n.node), nodePrinter(seen, n.next))
}
return fmt.Sprintf("[%s]", nodePrinter(seen, n.node))
case *repetition:
return fmt.Sprintf("{ %s }", nodePrinter(seen, n.node))
case *literal:
if n.t == lexer.EOF {
return fmt.Sprintf("%q", n.s)
}
return fmt.Sprintf("%q:%s", n.s, n.tt)
default:
panicf("unsupported type %T", v)
return ""
}
}