-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparse.go
89 lines (82 loc) · 1.82 KB
/
parse.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
package main
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"reflect"
"strings"
)
func parseFile(code string) []byte {
fst := token.NewFileSet()
f, _ := parser.ParseFile(fst, "main.go", code, parser.ParseComments)
m := walk(fst, f)
res, _ := json.Marshal(m)
return res
}
func walk(fst *token.FileSet, node interface{}) map[string]interface{} {
if node == nil {
return nil
}
m := make(map[string]interface{})
if _, ok := node.(*ast.Scope); ok {
return nil
}
if _, ok := node.(*ast.Object); ok {
return nil
}
val := reflect.ValueOf(node)
if val.IsNil() {
return nil
}
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
ty := val.Type()
m["_type"] = ty.Name()
for i := 0; i < ty.NumField(); i++ {
field := ty.Field(i)
val := val.Field(i)
if strings.HasSuffix(field.Name, "Pos") {
continue
}
switch field.Type.Kind() {
case reflect.Array, reflect.Slice:
list := make([]interface{}, 0, val.Len())
for i := 0; i < val.Len(); i++ {
if item := walk(fst, val.Index(i).Interface()); item != nil {
list = append(list, item)
}
}
m[field.Name] = list
case reflect.Ptr:
if child := walk(fst, val.Interface()); child != nil {
m[field.Name] = child
}
case reflect.Interface:
if child := walk(fst, val.Interface()); child != nil {
m[field.Name] = child
}
case reflect.String:
m[field.Name] = val.String()
case reflect.Int:
if field.Type.Name() == "Token" {
m[field.Name] = token.Token(val.Int()).String()
} else {
m[field.Name] = val.Int()
}
case reflect.Bool:
m[field.Name] = val.Bool()
default:
fmt.Fprintln(os.Stderr, field)
}
}
if n, ok := node.(ast.Node); ok {
start := fst.Position(n.Pos())
end := fst.Position(n.End())
m["Loc"] = map[string]interface{}{"Start": start, "End": end}
}
return m
}