forked from rainycape/gondola
/
types.go
245 lines (224 loc) · 6.15 KB
/
types.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
package genutil
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"go/types"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
)
// Package represents a parsed package with all its
// dependencies. Use NewPackage to create a Package.
type Package struct {
*types.Package
dir string
pkg *_package
info *types.Info
}
// Dir returns the package source directory.
func (p *Package) Dir() string {
return p.dir
}
func (p *Package) FileSet() *token.FileSet {
return p.pkg.fset
}
func (p *Package) ASTFiles() map[string]*ast.File {
files := make(map[string]*ast.File)
for k, v := range p.pkg.files {
files[k] = v.ast
}
return files
}
func (p *Package) Info() *types.Info {
return p.info
}
func (p *Package) types(exported bool, include *regexp.Regexp, exclude *regexp.Regexp, names []string) ([]*types.Named, error) {
required := make(map[string]bool, len(names))
for _, v := range names {
required[v] = true
}
var packageTypes []*types.Named
scope := p.Scope()
for _, v := range scope.Names() {
obj := scope.Lookup(v)
if exported && !obj.Exported() {
continue
}
if _, ok := obj.(*types.Const); ok {
continue
}
if _, ok := obj.(*types.Var); ok {
continue
}
if named, ok := obj.Type().(*types.Named); ok {
name := named.Obj().Name()
delete(required, name)
if exclude != nil && exclude.MatchString(name) {
continue
}
if include != nil && !include.MatchString(name) {
continue
}
packageTypes = append(packageTypes, named)
}
}
for v := range required {
obj := scope.Lookup(v)
if obj == nil {
return nil, fmt.Errorf("can't find type %q", v)
}
typ := obj.Type()
named, ok := typ.(*types.Named)
if !ok {
return nil, fmt.Errorf("%q is not a type, it's %s", v, typ)
}
packageTypes = append(packageTypes, named)
}
return packageTypes, nil
}
// Types returns the types declared in the package which match the required constraints.
// If excluded != nil, any type matching it gets excluded. If include != nil, only types
// matching it are returned.
func (p *Package) Types(include *regexp.Regexp, exclude *regexp.Regexp) []*types.Named {
t, _ := p.types(false, include, exclude, nil)
return t
}
// ExportedTypes works like Types, but only returns types that are exported.
func (p *Package) ExportedTypes(include *regexp.Regexp, exclude *regexp.Regexp) []*types.Named {
t, _ := p.types(true, include, exclude, nil)
return t
}
// SelectedTypes works similarly to Types, but tests all types if include != nil or exclude != nil,
// otherwise it acts like p.ExportedTypes(nil, nil). Types explicitely named in the names argument
// are always included in the returned value. If any of the named types does not exist, an error
// is returned.
func (p *Package) SelectedTypes(include *regexp.Regexp, exclude *regexp.Regexp, names []string) ([]*types.Named, error) {
exported := false
if include == nil && exclude == nil {
exported = true
}
return p.types(exported, include, exclude, names)
}
type _package struct {
Path string
fset *token.FileSet
astFiles []*ast.File
files map[string]*file
}
type file struct {
fset *token.FileSet
name string
ast *ast.File
lines [][]byte
}
// NewPackage returns a new Package struct, which can be
// used to generate code related to the package. The package
// might be given as either an absolute path or an import path.
// If the package can't be found or the package is not compilable,
// this function returns an error.
func NewPackage(path string) (*Package, error) {
p := &_package{Path: path, fset: token.NewFileSet()}
pkg, err := findPackage(path)
if err != nil {
return nil, fmt.Errorf("could not find package: %s", err)
}
fileNames := packageFiles(pkg)
if len(fileNames) == 0 {
return nil, fmt.Errorf("no go files")
}
p.astFiles = make([]*ast.File, len(fileNames))
p.files = make(map[string]*file, len(fileNames))
for ii, v := range fileNames {
f, err := parseFile(p.fset, v)
if err != nil {
return nil, fmt.Errorf("could not parse %s: %s", v, err)
}
p.files[v] = f
p.astFiles[ii] = f.ast
}
context := &types.Config{
IgnoreFuncBodies: true,
FakeImportC: true,
Error: errorHandler,
}
ipath := pkg.ImportPath
if ipath == "." {
// Check won't accept a "." import
abs, err := filepath.Abs(pkg.Dir)
if err != nil {
return nil, err
}
for _, v := range strings.Split(build.Default.GOPATH, ":") {
src := filepath.Join(v, "src")
if strings.HasPrefix(abs, src) {
ipath = abs[len(src)+1:]
break
}
}
}
var info types.Info
info.Types = make(map[ast.Expr]types.TypeAndValue)
info.Defs = make(map[*ast.Ident]types.Object)
info.Uses = make(map[*ast.Ident]types.Object)
info.Implicits = make(map[ast.Node]types.Object)
info.Selections = make(map[*ast.SelectorExpr]*types.Selection)
info.Scopes = make(map[ast.Node]*types.Scope)
tpkg, err := context.Check(ipath, p.fset, p.astFiles, &info)
if err != nil {
// This error is caused by using fields in C structs, ignore it
if !strings.Contains(err.Error(), "invalid type") {
return nil, fmt.Errorf("error checking package: %s", err)
}
}
return &Package{
Package: tpkg,
dir: pkg.Dir,
pkg: p,
info: &info,
}, nil
}
func findPackage(path string) (*build.Package, error) {
ctx := build.Default
ctx.CgoEnabled = true
p, err := ctx.Import(path, ".", 0)
if err == nil {
return p, err
}
return ctx.ImportDir(path, 0)
}
func packageFiles(pkg *build.Package) []string {
var files []string
for _, v := range pkg.GoFiles {
files = append(files, filepath.Join(pkg.Dir, v))
}
for _, v := range pkg.CgoFiles {
files = append(files, filepath.Join(pkg.Dir, v))
}
return files
}
func parseFile(fset *token.FileSet, fileName string) (f *file, err error) {
rd, err := os.Open(fileName)
if err != nil {
return f, err
}
defer rd.Close()
data, err := ioutil.ReadAll(rd)
if err != nil {
return f, err
}
astFile, err := parser.ParseFile(fset, fileName, bytes.NewReader(data), parser.ParseComments)
if err != nil {
return f, fmt.Errorf("could not parse: %s", err)
}
lines := bytes.Split(data, []byte("\n"))
f = &file{fset: fset, name: fileName, ast: astFile, lines: lines}
return f, nil
}
func errorHandler(err error) {
}