forked from dominikh/uses
/
main.go
286 lines (240 loc) · 6.13 KB
/
main.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
import (
"code.google.com/p/go.tools/go/types"
"github.com/kisielk/gotool"
"honnef.co/go/importer"
"sort"
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
)
type stringSlice []string
func (s *stringSlice) String() string {
return strings.Join(*s, ",")
}
func (s *stringSlice) Set(val string) error {
*s = strings.Split(val, ",")
return nil
}
var (
packages stringSlice
arguments stringSlice
returns stringSlice
and bool
)
func init() {
flag.Var(&packages, "pkgs", "Comma-separated list of packages to search for functions.")
flag.Var(&arguments, "args", "Comma-separated list of argument types to match.")
flag.Var(&returns, "rets", "Comma-separated list of return types to match.")
flag.BoolVar(&and, "and", false, "Use AND instead of OR for matching functions.")
flag.Parse()
}
func parseFile(fset *token.FileSet, fileName string) (f *ast.File, err error) {
astFile, err := parser.ParseFile(fset, fileName, nil, 0)
if err != nil {
return f, fmt.Errorf("could not parse: %s", err)
}
return astFile, nil
}
type Type struct {
Object types.Object
TypeName *types.TypeName
Pointer *types.Pointer
}
type Context struct {
allImports map[string]*types.Package
context types.Context
}
func NewContext() *Context {
importer := importer.NewImporter()
ctx := &Context{
allImports: importer.Imports,
context: types.Context{
Import: importer.Import,
},
}
return ctx
}
func check(ctx *Context, name string, fset *token.FileSet, astFiles []*ast.File) (pkg *types.Package, err error) {
return ctx.context.Check(name, fset, astFiles...)
}
func (ctx *Context) getObjects(paths []string) ([]types.Object, []error) {
var errors []error
var objects []types.Object
pathLoop:
for _, path := range paths {
buildPkg, err := build.Import(path, ".", 0)
if err != nil {
errors = append(errors, fmt.Errorf("Couldn't import %s: %s", path, err))
continue
}
fset := token.NewFileSet()
var astFiles []*ast.File
var pkg *types.Package
if buildPkg.Goroot {
// TODO what if the compiled package in GoRoot is
// outdated?
pkg, err = types.GcImport(ctx.allImports, path)
if err != nil {
errors = append(errors, fmt.Errorf("Couldn't import %s: %s", path, err))
continue
}
} else {
if len(buildPkg.GoFiles) == 0 {
errors = append(errors, fmt.Errorf("Couldn't parse %s: No (non cgo) Go files", path))
continue pathLoop
}
for _, file := range buildPkg.GoFiles {
astFile, err := parseFile(fset, filepath.Join(buildPkg.Dir, file))
if err != nil {
errors = append(errors, fmt.Errorf("Couldn't parse %s: %s", err))
continue pathLoop
}
astFiles = append(astFiles, astFile)
}
pkg, err = check(ctx, path, fset, astFiles)
if err != nil {
errors = append(errors, fmt.Errorf("Couldn't parse %s: %s\n", path, err))
continue pathLoop
}
}
scope := pkg.Scope()
for i := 0; i < scope.NumEntries(); i++ {
obj := scope.At(i)
objects = append(objects, obj)
}
}
return objects, errors
}
// This struct only exists to work around issue 5815 (go/types: (*Func).Pkg() returns
// nil for methods from GcImport'ed packages)
type function struct {
*types.Func
Pkg *types.Package
}
func (ctx *Context) getFunctions(paths []string) ([]function, []error) {
var funcs []function
objects, errors := ctx.getObjects(paths)
for _, obj := range objects {
if fnc, ok := obj.(*types.Func); ok {
funcs = append(funcs, function{fnc, obj.Pkg()})
} else {
typ, ok := obj.(*types.TypeName)
if !ok {
continue
}
named, ok := typ.Type().(*types.Named)
if !ok {
continue
}
for i := 0; i < named.NumMethods(); i++ {
funcs = append(funcs, function{named.Method(i), obj.Pkg()})
}
}
}
return funcs, errors
}
func listErrors(errors []error) {
for _, err := range errors {
fmt.Println(err)
}
}
func noDot(s string) string {
index := strings.Index(s, "·")
if index == -1 {
return s
}
return s[:index]
}
func argsToString(args *types.Tuple) string {
ret := make([]string, args.Len())
for i := 0; i < args.Len(); i++ {
name := noDot(args.At(i).Name())
typ := args.At(i).Type().String()
if len(name) == 0 {
ret[i] = typ
} else {
ret[i] = name + " " + typ
}
}
return strings.Join(ret, ", ")
}
func checkTypes(args *types.Tuple, types []string) (any, all bool) {
matched := make([]bool, len(types))
for i := 0; i < args.Len(); i++ {
for k, toCheck := range types {
if args.At(i).Type().String() == toCheck {
matched[k] = true
any = true
}
}
}
for _, b := range matched {
if !b {
return any, false
}
}
return any, true
}
func sortedKeys(m map[string][]string) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func main() {
if len(packages) == 0 {
fmt.Fprintln(os.Stderr, "Need to specify at least one package to check.")
flag.Usage()
os.Exit(1)
}
if len(arguments)+len(returns) == 0 {
fmt.Fprintln(os.Stderr, "Need at least one type to search for.")
flag.Usage()
os.Exit(1)
}
var typesToCheck []string
typesToCheck = append(typesToCheck, arguments...)
typesToCheck = append(typesToCheck, returns...)
ctx := NewContext()
funcs, errs := ctx.getFunctions(gotool.ImportPaths(packages))
listErrors(errs)
signatures := make(map[string][]string)
for _, fnc := range funcs {
sig, ok := fnc.Type().(*types.Signature)
if !ok {
// Skipping over builtins
continue
}
anyArg, allArg := checkTypes(sig.Params(), arguments)
anyRet, allRet := checkTypes(sig.Results(), returns)
if (!and && (anyArg || anyRet)) || (and && allArg && allRet) {
prefix := ""
if sig.Recv() != nil {
prefix = fmt.Sprintf("(%s %s) ", noDot(sig.Recv().Name()), sig.Recv().Type().String())
}
signatures[fnc.Pkg.Path()] = append(signatures[fnc.Pkg.Path()],
fmt.Sprintf("%s%s(%s) (%s)",
prefix,
fnc.Name(),
argsToString(sig.Params()),
argsToString(sig.Results())))
}
}
for _, path := range sortedKeys(signatures) {
sigs := signatures[path]
fmt.Println(path + ":")
for _, sig := range sigs {
fmt.Println("\t" + sig)
}
fmt.Println()
}
}