/
package.go
80 lines (68 loc) · 1.53 KB
/
package.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
package knife
import (
"fmt"
"go/types"
"sync"
)
var (
cache sync.Map
)
type Package struct {
TypesPackage *types.Package
Name string
Path string
Imports []*Package
Funcs map[string]*Func
FuncNames []string
Vars map[string]*Var
VarNames []string
Consts map[string]*Const
ConstNames []string
Types map[string]*TypeName
TypeNames []string
}
var _ fmt.Stringer = (*Package)(nil)
func (pkg *Package) String() string {
return pkg.TypesPackage.String()
}
func NewPackage(pkg *types.Package) *Package {
if pkg == nil {
return nil
}
v, _ := cache.Load(pkg)
cached, _ := v.(*Package)
if cached != nil {
return cached
}
var np Package
cache.Store(pkg, &np)
np.TypesPackage = pkg
np.Name = pkg.Name()
np.Path = pkg.Path()
np.Imports = make([]*Package, len(pkg.Imports()))
np.Funcs = map[string]*Func{}
np.Vars = map[string]*Var{}
np.Consts = map[string]*Const{}
np.Types = map[string]*TypeName{}
for i, p := range pkg.Imports() {
np.Imports[i] = NewPackage(p)
}
for _, n := range pkg.Scope().Names() {
obj := pkg.Scope().Lookup(n)
switch obj := obj.(type) {
case *types.Func:
np.Funcs[n] = NewFunc(obj)
np.FuncNames = append(np.FuncNames, n)
case *types.Var:
np.Vars[n] = NewVar(obj)
np.VarNames = append(np.VarNames, n)
case *types.Const:
np.Consts[n] = NewConst(obj)
np.ConstNames = append(np.ConstNames, n)
case *types.TypeName:
np.Types[n] = NewTypeName(obj)
np.TypeNames = append(np.TypeNames, n)
}
}
return &np
}