This repository has been archived by the owner on Dec 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
parse.go
108 lines (93 loc) · 1.9 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func parse(filename string, rd io.Reader) (*GoFile, error) {
// Store src as []byte for doDiff
srcBytes, err := ioutil.ReadAll(rd)
if err != nil && err != io.EOF {
return nil, fmt.Errorf("readall: %s", err)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, srcBytes, 0)
if err != nil {
return nil, err
}
DebugAst(fset, f)
var funcs []string
var methods []*Method
ast.Inspect(f, func(node ast.Node) bool {
switch x := node.(type) {
case *ast.FuncDecl:
Debugf("FuncDecl: %#v", x.Name)
// receiver (methods) or nil (functions)
if x.Recv == nil {
funcs = append(funcs, x.Name.Name)
return true
}
fields := x.Recv.List
if len(fields) != 1 {
// Is this happend ..?
return true
}
field := fields[0]
t := field.Type
var recvName string
switch x2 := t.(type) {
case *ast.StarExpr:
switch x3 := x2.X.(type) {
case *ast.Ident:
recvName = x3.Name
}
case *ast.Ident:
recvName = x2.Name
default:
// Should not reach here...
return false
}
methods = append(methods, &Method{
RecvName: recvName,
Name: x.Name.Name,
})
}
return true
})
Debugf("Funcs: %#v", methods)
Debugf("Methods: %#v", methods)
return &GoFile{
PackageName: f.Name.Name,
FileName: filename,
SrcBytes: srcBytes,
Funcs: funcs,
Methods: methods,
FSet: fset,
AstFile: f,
}, nil
}
func ParseFile(path string) (*GoFile, error) {
path, err := filepath.Abs(path)
if err != nil {
return nil, err
}
if !strings.HasSuffix(path, ".go") {
return nil, fmt.Errorf("%s is not go file", path)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return nil, err
}
return parse(fi.Name(), f)
}