-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
100 lines (76 loc) · 1.69 KB
/
parser.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
package main
import (
"encoding/json"
"go/ast"
"go/parser"
"go/token"
"go/types"
)
type Param struct {
Name string `json:"name,omitempty"`
Type string `json:"type"`
}
type Result struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
}
type Func struct {
Name string `json:"name"`
Params []Param `json:"params,omitempty"`
Results []Result `json:"results,omitempty"`
}
var (
Funcs map[string]*Func
)
func VisitFuncs(node ast.Node) bool {
if node == nil {
return false
}
switch n := node.(type) {
case *ast.File, *ast.Ident, *ast.FuncType:
return true
case *ast.FuncDecl:
newFunc := &Func{ Name: n.Name.Name }
Funcs[n.Name.Name] = newFunc
if n.Type.Params != nil {
for _, fieldParam := range n.Type.Params.List {
param := Param{
Name: fieldParam.Names[0].Name,
Type: types.ExprString(fieldParam.Type)}
newFunc.Params = append(newFunc.Params, param)
}
}
if n.Type.Results != nil {
for _, fieldResult := range n.Type.Results.List {
result := Result{
Type: types.ExprString(fieldResult.Type)}
if len(fieldResult.Names) > 0 {
result.Name = fieldResult.Names[0].Name
}
newFunc.Results = append(newFunc.Results, result)
}
}
}
return false
}
func ParseSymbols(path string) (string, error) {
Funcs = make(map[string]*Func)
fset := token.NewFileSet()
parsed, e := parser.ParseDir(fset, path, nil, 0)
if e != nil {
return "", e
}
for _, pkg := range parsed {
ast.PackageExports(pkg)
}
for _, astpkg := range parsed {
for _, f := range astpkg.Files {
ast.Inspect(f, VisitFuncs)
}
}
res, e := json.Marshal(&Funcs)
if e != nil {
return "", e
}
return string(res), nil
}