/
definition.go
412 lines (372 loc) · 11.3 KB
/
definition.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package gounexport
import (
"fmt"
"github.com/dooman87/gounexport/fs"
"github.com/dooman87/gounexport/util"
"go/ast"
"go/token"
"go/types"
"reflect"
"strings"
)
//GetDefinitions collects information about all (exported and unexported)
//definitions and adapt them to Definition structure.
//Returns map where key is full name (package + name) of symbol.
func GetDefinitions(info *types.Info, fset *token.FileSet) map[string]*Definition {
ctx := newContext(fset)
ctx.defs = make(map[string]*Definition, 0)
processTypes(info, ctx)
processDefs(info, ctx)
processUses(info, ctx)
return ctx.defs
}
//processTypes is only filling interfaces from function signatures.
func processTypes(info *types.Info, ctx *context) {
for _, t := range info.Types {
logType(t)
if t.Type != nil {
switch t.Type.(type) {
//If it's a function signature then extracting
//all params and trying to find interfaces.
//We are doing this to find usages of interfaces
//cause methods of the interfaces could be called
// inside internal functions
case *types.Signature:
s := t.Type.(*types.Signature)
if tuple := s.Params(); tuple != nil {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
if types.IsInterface(v.Type()) {
addInterface(v, nil, ctx)
}
}
}
}
}
}
}
//processDefs going through all definitions in the next order:
// - collect info about all interfaces
// - process everthing except vars and functions to collect all structs prior vars and functions
// - process vars and functions
func processDefs(info *types.Info, ctx *context) {
//Collect all interfaces
for ident, obj := range info.Defs {
if !isValidObject(obj, ident, ctx) || !types.IsInterface(obj.Type()) {
continue
}
addInterface(obj, ident, ctx)
}
logInterfaces(ctx)
//Collect everything except vars and functions
for ident, obj := range info.Defs {
if !isValidObject(obj, ident, ctx) {
continue
}
var def *Definition
if !isVar(obj) && !isFunc(obj) && !types.IsInterface(obj.Type()) {
def = createDef(obj, ident, ctx, false)
}
updateContext(ctx, def, ident, obj)
}
for _, v := range ctx.vars {
createDef(v.obj, v.ident, ctx, false)
}
for _, v := range ctx.funcs {
createDef(v.obj, v.ident, ctx, false)
}
}
//Fill usages inside all definitions. The special case is functions
//where all params should be processed.
func processUses(info *types.Info, ctx *context) {
for ident, obj := range info.Uses {
useName := getFullName(obj, ctx, false)
if ctx.defs[useName] != nil {
ctx.defs[useName].addUsage(ctx.fset.Position(ident.Pos()))
} else {
util.Warn("can't find usage for [%s] %s\n\tObject definition - %s", useName, posToStr(ctx.fset, ident.Pos()), posToStr(ctx.fset, obj.Pos()))
}
switch obj.Type().(type) {
case *types.Signature:
s := obj.Type().(*types.Signature)
if tuple := s.Params(); tuple != nil {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
useName := getFullName(v, ctx, true)
if ctx.defs[useName] != nil {
ctx.defs[useName].addUsage(ctx.fset.Position(ident.Pos()))
}
}
}
}
}
}
func addInterface(obj types.Object, ident *ast.Ident, ctx *context) {
interfac := obj.Type().Underlying().(*types.Interface)
def := createDef(obj, ident, ctx, true)
updateContext(ctx, def, ident, obj)
util.Debug("adding interface [%s] [%v] [%v] [%v]", def.Name, def.Pkg, obj.Type().Underlying(), obj.Type())
//Adding all methods of interface
for i := 0; i < interfac.NumMethods(); i++ {
f := interfac.Method(i)
def := createDef(f, nil, ctx, false)
util.Debug("\tadding method [%v] [%s]", f, def.Name)
updateContext(ctx, def, ident, f)
}
}
func isValidObject(obj types.Object, ident *ast.Ident, ctx *context) bool {
if obj == nil {
return false
}
position := ctx.fset.Position(ident.Pos())
typeOf := reflect.TypeOf(obj)
fullName := getFullName(obj, ctx, false)
if !position.IsValid() {
util.Warn("position object is invalid for %s", ident.Name)
return false
}
if len(fullName) == 0 {
util.Warn("warning: cann't get full name for %s: %v", ident.Name, typeOf)
return false
}
if typeOf == nil {
return false
}
if ctx.defs[fullName] != nil {
return false
}
return true
}
func updateContext(ctx *context, def *Definition, ident *ast.Ident, obj types.Object) {
switch obj.(type) {
case *types.Var:
//Processing vars later to be sure that all info about structs already filled
ctx.vars = append(ctx.vars, newObjectWithIdent(obj, ident))
case *types.Func:
//Processing funcs later to be sure that all info about interfaces already filled
ctx.funcs = append(ctx.funcs, newObjectWithIdent(obj, ident))
case *types.TypeName:
//If the underlying type is struct, then filling
//positions of struct's fields (key) and struct name(value)
//to map. Then we can extract struct name for fields when
//will be analyze them.
t := obj.(*types.TypeName)
underlyingType := t.Type().Underlying()
switch underlyingType.(type) {
case *types.Struct:
s := underlyingType.(*types.Struct)
for i := 0; i < s.NumFields(); i++ {
field := s.Field(i)
ctx.structs[posToStr(ctx.fset, field.Pos())] = obj.Name()
}
}
}
//Check for interfaces
underlyingType := obj.Type().Underlying()
switch underlyingType.(type) {
case *types.Interface:
d := new(defWithInterface)
d.def = def
d.interfac = underlyingType.(*types.Interface)
ctx.interfaces = append(ctx.interfaces, d)
}
}
func isVar(obj types.Object) bool {
switch obj.(type) {
case *types.Var:
return true
}
return false
}
func isFunc(obj types.Object) bool {
switch obj.(type) {
case *types.Func:
return true
}
return false
}
func createDef(obj types.Object, ident *ast.Ident, ctx *context, isType bool) *Definition {
fullName := getFullName(obj, ctx, isType)
if def, ok := ctx.defs[fullName]; ok {
return def
}
def := new(Definition)
def.Name = fullName
def.Pkg = obj.Pkg()
def.Exported = obj.Exported()
def.TypeOf = reflect.TypeOf(obj)
def.SimpleName = obj.Name()
def.Usages = make([]*Usage, 0)
def.Interfaces = make([]*Definition, 0)
if ident != nil {
position := ctx.fset.Position(ident.Pos())
def.File = position.Filename
def.Line = position.Line
def.Offset = position.Offset
def.Col = position.Column
}
if !types.IsInterface(obj.Type()) {
fillInterfaces(def, obj, ctx)
}
ctx.defs[def.Name] = def
logDefinition(def, obj, ident, ctx)
return def
}
func fillInterfaces(def *Definition, obj types.Object, ctx *context) {
switch obj.(type) {
case *types.TypeName:
//Filling information about implemented
//interfaces to type's definition.
typ := obj.(*types.TypeName)
if typ.Type() != nil {
for _, di := range ctx.interfaces {
if di.interfac != nil && di.def != nil && implements(typ.Type(), di.interfac, typ.Pkg()) {
def.Interfaces = append(def.Interfaces, di.def)
}
}
}
case *types.Func:
f := obj.(*types.Func)
underlyingType := f.Type().Underlying()
switch underlyingType.(type) {
case *types.Signature:
s := underlyingType.(*types.Signature)
if s.Recv() != nil {
//Getting all interfaces from function's receiver and
//searching for current function in each interface.
//If found, then adding method's definition to function's
//interfaces
recvTypeName := strings.Replace(s.Recv().Type().String(), "*", "", 1)
if typeDef, ok := ctx.defs[recvTypeName]; ok {
for _, iDef := range typeDef.Interfaces {
def.Interfaces = append(def.Interfaces, iDef)
if methodDef := lookupMethod(def, iDef, ctx); methodDef != nil {
def.Interfaces = append(def.Interfaces, methodDef)
}
}
} else {
util.Debug("recv type not found [%s]", s.Recv().Type().String())
}
}
}
}
}
func lookupMethod(def *Definition, ifaceDef *Definition, ctx *context) *Definition {
methodName := ifaceDef.Name + "." + def.SimpleName
externalInterfaceMethodName := "interface." + def.SimpleName
def.Interfaces = append(def.Interfaces, ifaceDef)
if methodDef := ctx.defs[methodName]; methodDef != nil {
return methodDef
} else if methodDef := ctx.defs[externalInterfaceMethodName]; methodDef != nil {
return methodDef
} else {
util.Debug("can't find method [%s]", methodName)
}
return nil
}
func implements(t types.Type, interfac *types.Interface, pkg *types.Package) bool {
if interfac == nil || t == nil || interfac.Empty() {
return false
}
if types.Implements(t, interfac) {
return true
}
//For some reason, interfaces that comes
//already built in (not from sources) are
//not working with types.Implements method
for i := 0; i < interfac.NumMethods(); i++ {
m := interfac.Method(i)
obj, _, _ := types.LookupFieldOrMethod(t, true, pkg, m.Name())
if obj == nil {
util.Debug("method %s not found in type %v", m.Name(), t)
return false
}
}
return true
}
//getFullName is returning unique name of obj.
func getFullName(obj types.Object, ctx *context, isType bool) string {
if obj == nil {
return ""
}
if isType {
return obj.Type().String()
}
result := ""
switch obj.(type) {
case *types.Func:
f := obj.(*types.Func)
r := strings.NewReplacer("(", "", "*", "", ")", "")
result = r.Replace(f.FullName())
default:
if obj.Pkg() != nil {
result += obj.Pkg().Path()
result += "."
}
if packageName, ok := ctx.structs[posToStr(ctx.fset, obj.Pos())]; ok {
result += packageName
result += "."
}
result += obj.Name()
}
return result
}
func logDefinition(def *Definition, obj types.Object, ident *ast.Ident, ctx *context) {
if ident == nil {
return
}
util.Info("definition [%s] [%s], exported [%v], position %s", ident.Name, def.TypeOf.String(), obj.Exported(), posToStr(ctx.fset, ident.Pos()))
switch obj.(type) {
case *types.TypeName:
t := obj.(*types.TypeName)
underlyingType := t.Type().Underlying()
util.Info("\t [%s] [%s] [%s]", t.Type().String(), t.Type().Underlying().String(), reflect.TypeOf(t.Type().Underlying()).String())
switch underlyingType.(type) {
case *types.Struct:
s := underlyingType.(*types.Struct)
util.Info("\t\t[%d] fields", s.NumFields())
for i := 0; i < s.NumFields(); i++ {
field := s.Field(i)
util.Info("\t\t\t[%s]", posToStr(ctx.fset, field.Pos()))
}
}
case *types.Func:
f := obj.(*types.Func)
underlyingType := f.Type().Underlying()
util.Info("\t full name: [%s] [%s] [%s]", f.FullName(), underlyingType.String(), reflect.TypeOf(underlyingType))
}
util.Info("\tinterfaces [%d]", len(def.Interfaces))
for _, i := range def.Interfaces {
util.Info("\tinterface [%s]", i.Name)
}
}
func logInterfaces(ctx *context) {
for _, i := range ctx.interfaces {
util.Info("interface [%s]", i.def.Name)
}
}
func logType(t types.TypeAndValue) {
if t.Type != nil {
util.Debug("type [%s] [%s] [%s] [%s]", reflect.TypeOf(t.Type), t.Type.String(), reflect.TypeOf(t.Type.Underlying()), t.Type.Underlying().String())
switch t.Type.(type) {
case *types.Signature:
s := t.Type.(*types.Signature)
if s.Recv() != nil {
util.Info("\t\t[%s] [%s]", s.Recv(), s.Recv().Type().String())
}
if tuple := s.Params(); tuple != nil {
for i := 0; i < tuple.Len(); i++ {
v := tuple.At(i)
util.Debug("\t\t%s", v.Name())
if types.IsInterface(v.Type()) {
util.Debug("\t\t\t<------interface")
}
}
}
}
}
}
func posToStr(fset *token.FileSet, pos token.Pos) string {
fPos := fset.Position(pos)
return fmt.Sprintf("[%s:%d:%d]", fs.GetRelativePath(fPos.Filename), fPos.Line, fPos.Column)
}