-
Notifications
You must be signed in to change notification settings - Fork 400
/
loader.go
349 lines (305 loc) · 9.91 KB
/
loader.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
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package loader
import (
"fmt"
"go/ast"
"go/parser"
"go/scanner"
"go/token"
"go/types"
"io/ioutil"
"os"
"sync"
"golang.org/x/tools/go/packages"
)
// Much of this is strongly inspired by the contents of go/packages,
// except that it allows for lazy loading of syntax and type-checking
// information to speed up cases where full traversal isn't needed.
// PrintErrors print errors associated with all packages
// in the given package graph, starting at the given root
// packages and traversing through all imports. It will skip
// any errors of the kinds specified in filterKinds. It will
// return true if any errors were printed.
func PrintErrors(pkgs []*Package, filterKinds ...packages.ErrorKind) bool {
pkgsRaw := make([]*packages.Package, len(pkgs))
for i, pkg := range pkgs {
pkgsRaw[i] = pkg.Package
}
toSkip := make(map[packages.ErrorKind]struct{})
for _, errKind := range filterKinds {
toSkip[errKind] = struct{}{}
}
hadErrors := false
packages.Visit(pkgsRaw, nil, func(pkgRaw *packages.Package) {
for _, err := range pkgRaw.Errors {
if _, skip := toSkip[err.Kind]; skip {
continue
}
hadErrors = true
fmt.Fprintln(os.Stderr, err)
}
})
return hadErrors
}
// Package is a single, unique Go package that can be
// lazily parsed and type-checked. Packages should not
// be constructed directly -- instead, use LoadRoots.
// For a given call to LoadRoots, only a single instance
// of each package exists, and thus they may be used as keys
// and for comparison.
type Package struct {
*packages.Package
imports map[string]*Package
loader *loader
sync.Mutex
}
// Imports returns the imports for the given package, indexed by
// package path (*not* name in any particular file).
func (p *Package) Imports() map[string]*Package {
if p.imports == nil {
p.imports = p.loader.packagesFor(p.Package.Imports)
}
return p.imports
}
// NeedTypesInfo indicates that type-checking information is needed for this package.
// Actual type-checking information can be accessed via the Types and TypesInfo fields.
func (p *Package) NeedTypesInfo() {
if p.TypesInfo != nil {
return
}
p.NeedSyntax()
p.loader.typeCheck(p)
}
// NeedSyntax indicates that a parsed AST is needed for this package.
// Actual ASTs can be accessed via the Syntax field.
func (p *Package) NeedSyntax() {
if p.Syntax != nil {
return
}
out := make([]*ast.File, len(p.CompiledGoFiles))
var wg sync.WaitGroup
wg.Add(len(p.CompiledGoFiles))
for i, filename := range p.CompiledGoFiles {
go func(i int, filename string) {
defer wg.Done()
src, err := ioutil.ReadFile(filename)
if err != nil {
p.AddError(err)
return
}
out[i], err = p.loader.parseFile(filename, src)
if err != nil {
p.AddError(err)
return
}
}(i, filename)
}
wg.Wait()
for _, file := range out {
if file == nil {
return
}
}
p.Syntax = out
}
// AddError adds an error to the errors associated with the given package.
func (p *Package) AddError(err error) {
switch typedErr := err.(type) {
case *os.PathError:
// file-reading errors
p.Errors = append(p.Errors, packages.Error{
Pos: typedErr.Path + ":1",
Msg: typedErr.Err.Error(),
Kind: packages.ParseError,
})
case scanner.ErrorList:
// parsing/scanning errors
for _, subErr := range typedErr {
p.Errors = append(p.Errors, packages.Error{
Pos: subErr.Pos.String(),
Msg: subErr.Msg,
Kind: packages.ParseError,
})
}
case types.Error:
// type-checking errors
p.Errors = append(p.Errors, packages.Error{
Pos: typedErr.Fset.Position(typedErr.Pos).String(),
Msg: typedErr.Msg,
Kind: packages.TypeError,
})
case ErrList:
for _, subErr := range typedErr {
p.AddError(subErr)
}
case PositionedError:
p.Errors = append(p.Errors, packages.Error{
Pos: p.loader.cfg.Fset.Position(typedErr.Pos).String(),
Msg: typedErr.Error(),
Kind: packages.UnknownError,
})
default:
// should only happen for external errors, like ref checking
p.Errors = append(p.Errors, packages.Error{
Pos: p.ID + ":-",
Msg: err.Error(),
Kind: packages.UnknownError,
})
}
}
// loader loads packages and their imports. Loaded packages will have
// type size, imports, and exports file information populated. Additional
// information, like ASTs and type-checking information, can be accessed
// via methods on individual packages.
type loader struct {
// Roots are the loaded "root" packages in the package graph loaded via
// LoadRoots.
Roots []*Package
// cfg contains the package loading config (initialized on demand)
cfg *packages.Config
// packages contains the cache of Packages indexed by the underlying
// package.Package, so that we don't ever produce two Packages with
// the same underlying packages.Package.
packages map[*packages.Package]*Package
packagesMu sync.Mutex
}
// packageFor returns a wrapped Package for the given packages.Package,
// ensuring that there's a one-to-one mapping between the two.
// It's *not* threadsafe -- use packagesFor for that.
func (l *loader) packageFor(pkgRaw *packages.Package) *Package {
if l.packages[pkgRaw] == nil {
l.packages[pkgRaw] = &Package{
Package: pkgRaw,
loader: l,
}
}
return l.packages[pkgRaw]
}
// packagesFor returns a map of Package objects for each packages.Package in the input
// map, ensuring that there's a one-to-one mapping between package.Package and Package
// (as per packageFor).
func (l *loader) packagesFor(pkgsRaw map[string]*packages.Package) map[string]*Package {
l.packagesMu.Lock()
defer l.packagesMu.Unlock()
out := make(map[string]*Package, len(pkgsRaw))
for name, rawPkg := range pkgsRaw {
out[name] = l.packageFor(rawPkg)
}
return out
}
// typeCheck type-checks the given package.
func (l *loader) typeCheck(pkg *Package) {
// don't conflict with typeCheckFromExportData
pkg.TypesInfo = &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Implicits: make(map[ast.Node]types.Object),
Scopes: make(map[ast.Node]*types.Scope),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
}
pkg.Fset = l.cfg.Fset
pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name)
importer := importerFunc(func(path string) (*types.Package, error) {
if path == "unsafe" {
return types.Unsafe, nil
}
// The imports map is keyed by import path.
importedPkg := pkg.Imports()[path]
if importedPkg == nil {
return nil, fmt.Errorf("no package information for %q", path)
}
if importedPkg.Types != nil && importedPkg.Types.Complete() {
return importedPkg.Types, nil
}
// if we haven't already loaded typecheck data, we don't care about this package's types
return types.NewPackage(importedPkg.PkgPath, importedPkg.Name), nil
})
var errs []error
// type-check
checkConfig := &types.Config{
Importer: importer,
IgnoreFuncBodies: true, // we only need decl-level info
Error: func(err error) {
errs = append(errs, err)
},
Sizes: pkg.TypesSizes,
}
if err := types.NewChecker(checkConfig, l.cfg.Fset, pkg.Types, pkg.TypesInfo).Files(pkg.Syntax); err != nil {
errs = append(errs, err)
}
// make sure that if a given sub-import is ill-typed, we mark this package as ill-typed as well.
illTyped := len(errs) > 0
if !illTyped {
for _, importedPkg := range pkg.Imports() {
if importedPkg.IllTyped {
illTyped = true
break
}
}
}
pkg.IllTyped = illTyped
// publish errors to the package error list.
for _, err := range errs {
pkg.AddError(err)
}
}
// parseFile parses the given file, including comments.
func (l *loader) parseFile(filename string, src []byte) (*ast.File, error) {
// skip function bodies
file, err := parser.ParseFile(l.cfg.Fset, filename, src, parser.AllErrors|parser.ParseComments)
if err != nil {
return nil, err
}
return file, nil
}
// LoadRoots loads the given "root" packages by path, transitively loading
// and all imports as well.
//
// Loaded packages will have type size, imports, and exports file information
// populated. Additional information, like ASTs and type-checking information,
// can be accessed via methods on individual packages.
func LoadRoots(roots ...string) ([]*Package, error) {
return LoadRootsWithConfig(&packages.Config{}, roots...)
}
// LoadRootsWithConfig functions like LoadRoots, except that it allows passing
// a custom loading config. The config will be modified to suit the needs of
// the loader.
//
// This is generally only useful for use in testing when you need to modify
// loading settings to load from a fake location.
func LoadRootsWithConfig(cfg *packages.Config, roots ...string) ([]*Package, error) {
l := &loader{
cfg: cfg,
packages: make(map[*packages.Package]*Package),
}
l.cfg.Mode |= packages.LoadImports | packages.NeedTypesSizes
if l.cfg.Fset == nil {
l.cfg.Fset = token.NewFileSet()
}
// put our build flags first so that callers can override them
l.cfg.BuildFlags = append([]string{"-tags", "ignore_autogenerated"}, l.cfg.BuildFlags...)
rawPkgs, err := packages.Load(l.cfg, roots...)
if err != nil {
return nil, err
}
for _, rawPkg := range rawPkgs {
l.Roots = append(l.Roots, l.packageFor(rawPkg))
}
return l.Roots, nil
}
// importFunc is an implementation of the single-method
// types.Importer interface based on a function value.
type importerFunc func(path string) (*types.Package, error)
func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }