forked from nokia/ntt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dump.go
127 lines (109 loc) · 2.39 KB
/
dump.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"bytes"
"fmt"
"os"
"reflect"
"strings"
"github.com/nokia/ntt/internal/fs"
"github.com/nokia/ntt/ttcn3"
"github.com/nokia/ntt/ttcn3/printer"
"github.com/nokia/ntt/ttcn3/syntax"
"github.com/spf13/cobra"
)
var (
indent = 0
DumpCommand = &cobra.Command{
Use: "dump",
Short: "Dump TTCN-3 syntax trees",
RunE: func(cmd *cobra.Command, args []string) error {
srcs, _ := fs.TTCN3Files(Project.Sources...)
imports, _ := fs.TTCN3Files(Project.Imports...)
files := append(srcs, imports...)
for _, file := range files {
tree := ttcn3.ParseFile(file)
if useTTCN3 {
printer.Print(os.Stdout, tree.Root)
} else if useDot {
dot(tree.Root)
} else {
dump(reflect.ValueOf(tree.Root), "Root: ")
}
}
return nil
},
}
useTTCN3 = false
useDot = false
)
func init() {
DumpCommand.PersistentFlags().BoolVarP(&useTTCN3, "ttcn3", "", false, "formatted TTCN-3 output")
DumpCommand.PersistentFlags().BoolVarP(&useDot, "dot", "", false, "graphviz output")
}
func dump(v reflect.Value, f string) {
if !v.IsValid() || v.IsZero() {
return
}
if v.Kind() != reflect.Interface && v.CanInterface() {
switch x := v.Interface().(type) {
case syntax.Token:
if x != nil {
Prefix(x, f)
fmt.Printf("[35m%s[0m", x.String())
Suffix(x)
}
case syntax.Node:
if x != nil {
Prefix(x, f)
fmt.Printf("[0m%s[0m", strings.TrimPrefix(v.Type().String(), "*syntax."))
Suffix(x)
}
}
}
switch v.Kind() {
case reflect.Ptr:
if v2 := v.Elem(); v2.IsValid() {
dump(v.Elem(), "")
}
case reflect.Interface:
if v2 := v.Elem(); v2.IsValid() {
dump(v2, f)
}
case reflect.Struct:
indent++
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
tf := v.Type().Field(i)
dump(f, fmt.Sprintf("%v: ", tf.Name))
}
indent--
case reflect.Slice:
Prefix(nil, f)
Suffix(nil)
indent++
for i := 0; i < v.Len(); i++ {
dump(v.Index(i), fmt.Sprintf("%d: ", i))
}
indent--
}
}
func Prefix(n syntax.Node, f string) {
fmt.Printf("%-15s %s[1m%s[0m", Pos(n), Indent(), f)
}
func Suffix(n syntax.Node) {
fmt.Println()
}
func Pos(n syntax.Node) string {
if n == nil {
return ""
}
return fmt.Sprintf("[%d-%d)", n.Pos()-1, n.End()-1)
}
func Indent() string {
var buf bytes.Buffer
fmt.Fprint(&buf, "[0;1m")
for i := 0; i < indent; i++ {
fmt.Fprint(&buf, "[37;0m· [0m")
}
return buf.String()
}