Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / internal / lsp / cache / check.go
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package cache
6
7 import (
8         "bytes"
9         "context"
10         "fmt"
11         "go/ast"
12         "go/types"
13         "path"
14         "sort"
15         "strings"
16         "sync"
17
18         "golang.org/x/mod/module"
19         "golang.org/x/tools/go/packages"
20         "golang.org/x/tools/internal/event"
21         "golang.org/x/tools/internal/lsp/debug/tag"
22         "golang.org/x/tools/internal/lsp/source"
23         "golang.org/x/tools/internal/memoize"
24         "golang.org/x/tools/internal/span"
25         "golang.org/x/tools/internal/typesinternal"
26         errors "golang.org/x/xerrors"
27 )
28
29 type packageHandleKey string
30
31 type packageHandle struct {
32         handle *memoize.Handle
33
34         goFiles, compiledGoFiles []*parseGoHandle
35
36         // mode is the mode the files were parsed in.
37         mode source.ParseMode
38
39         // m is the metadata associated with the package.
40         m *metadata
41
42         // key is the hashed key for the package.
43         key packageHandleKey
44 }
45
46 func (ph *packageHandle) packageKey() packageKey {
47         return packageKey{
48                 id:   ph.m.id,
49                 mode: ph.mode,
50         }
51 }
52
53 // packageData contains the data produced by type-checking a package.
54 type packageData struct {
55         pkg *pkg
56         err error
57 }
58
59 // buildPackageHandle returns a packageHandle for a given package and mode.
60 func (s *snapshot) buildPackageHandle(ctx context.Context, id packageID, mode source.ParseMode) (*packageHandle, error) {
61         if ph := s.getPackage(id, mode); ph != nil {
62                 return ph, nil
63         }
64
65         // Build the packageHandle for this ID and its dependencies.
66         ph, deps, err := s.buildKey(ctx, id, mode)
67         if err != nil {
68                 return nil, err
69         }
70
71         // Do not close over the packageHandle or the snapshot in the Bind function.
72         // This creates a cycle, which causes the finalizers to never run on the handles.
73         // The possible cycles are:
74         //
75         //     packageHandle.h.function -> packageHandle
76         //     packageHandle.h.function -> snapshot -> packageHandle
77         //
78
79         m := ph.m
80         key := ph.key
81
82         h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
83                 snapshot := arg.(*snapshot)
84
85                 // Begin loading the direct dependencies, in parallel.
86                 var wg sync.WaitGroup
87                 for _, dep := range deps {
88                         wg.Add(1)
89                         go func(dep *packageHandle) {
90                                 dep.check(ctx, snapshot)
91                                 wg.Done()
92                         }(dep)
93                 }
94
95                 data := &packageData{}
96                 data.pkg, data.err = typeCheck(ctx, snapshot, m, mode, deps)
97                 // Make sure that the workers above have finished before we return,
98                 // especially in case of cancellation.
99                 wg.Wait()
100
101                 return data
102         })
103         ph.handle = h
104
105         // Cache the handle in the snapshot. If a package handle has already
106         // been cached, addPackage will return the cached value. This is fine,
107         // since the original package handle above will have no references and be
108         // garbage collected.
109         ph = s.addPackageHandle(ph)
110
111         return ph, nil
112 }
113
114 // buildKey computes the key for a given packageHandle.
115 func (s *snapshot) buildKey(ctx context.Context, id packageID, mode source.ParseMode) (*packageHandle, map[packagePath]*packageHandle, error) {
116         m := s.getMetadata(id)
117         if m == nil {
118                 return nil, nil, errors.Errorf("no metadata for %s", id)
119         }
120         goFiles, err := s.parseGoHandles(ctx, m.goFiles, mode)
121         if err != nil {
122                 return nil, nil, err
123         }
124         compiledGoFiles, err := s.parseGoHandles(ctx, m.compiledGoFiles, mode)
125         if err != nil {
126                 return nil, nil, err
127         }
128         ph := &packageHandle{
129                 m:               m,
130                 goFiles:         goFiles,
131                 compiledGoFiles: compiledGoFiles,
132                 mode:            mode,
133         }
134         // Make sure all of the depList are sorted.
135         depList := append([]packageID{}, m.deps...)
136         sort.Slice(depList, func(i, j int) bool {
137                 return depList[i] < depList[j]
138         })
139
140         deps := make(map[packagePath]*packageHandle)
141
142         // Begin computing the key by getting the depKeys for all dependencies.
143         var depKeys []packageHandleKey
144         for _, depID := range depList {
145                 depHandle, err := s.buildPackageHandle(ctx, depID, s.workspaceParseMode(depID))
146                 if err != nil {
147                         event.Error(ctx, fmt.Sprintf("%s: no dep handle for %s", id, depID), err, tag.Snapshot.Of(s.id))
148                         if ctx.Err() != nil {
149                                 return nil, nil, ctx.Err()
150                         }
151                         // One bad dependency should not prevent us from checking the entire package.
152                         // Add a special key to mark a bad dependency.
153                         depKeys = append(depKeys, packageHandleKey(fmt.Sprintf("%s import not found", id)))
154                         continue
155                 }
156                 deps[depHandle.m.pkgPath] = depHandle
157                 depKeys = append(depKeys, depHandle.key)
158         }
159         experimentalKey := s.View().Options().ExperimentalPackageCacheKey
160         ph.key = checkPackageKey(ctx, ph.m.id, compiledGoFiles, m.config, depKeys, mode, experimentalKey)
161         return ph, deps, nil
162 }
163
164 func (s *snapshot) workspaceParseMode(id packageID) source.ParseMode {
165         if _, ws := s.isWorkspacePackage(id); ws {
166                 return source.ParseFull
167         } else {
168                 return source.ParseExported
169         }
170 }
171
172 func checkPackageKey(ctx context.Context, id packageID, pghs []*parseGoHandle, cfg *packages.Config, deps []packageHandleKey, mode source.ParseMode, experimentalKey bool) packageHandleKey {
173         b := bytes.NewBuffer(nil)
174         b.WriteString(string(id))
175         if !experimentalKey {
176                 // cfg was used to produce the other hashed inputs (package ID, parsed Go
177                 // files, and deps). It should not otherwise affect the inputs to the type
178                 // checker, so this experiment omits it. This should increase cache hits on
179                 // the daemon as cfg contains the environment and working directory.
180                 b.WriteString(hashConfig(cfg))
181         }
182         b.WriteByte(byte(mode))
183         for _, dep := range deps {
184                 b.WriteString(string(dep))
185         }
186         for _, cgf := range pghs {
187                 b.WriteString(cgf.file.FileIdentity().String())
188         }
189         return packageHandleKey(hashContents(b.Bytes()))
190 }
191
192 // hashConfig returns the hash for the *packages.Config.
193 func hashConfig(config *packages.Config) string {
194         b := bytes.NewBuffer(nil)
195
196         // Dir, Mode, Env, BuildFlags are the parts of the config that can change.
197         b.WriteString(config.Dir)
198         b.WriteString(string(rune(config.Mode)))
199
200         for _, e := range config.Env {
201                 b.WriteString(e)
202         }
203         for _, f := range config.BuildFlags {
204                 b.WriteString(f)
205         }
206         return hashContents(b.Bytes())
207 }
208
209 func (ph *packageHandle) Check(ctx context.Context, s source.Snapshot) (source.Package, error) {
210         return ph.check(ctx, s.(*snapshot))
211 }
212
213 func (ph *packageHandle) check(ctx context.Context, s *snapshot) (*pkg, error) {
214         v, err := ph.handle.Get(ctx, s.generation, s)
215         if err != nil {
216                 return nil, err
217         }
218         data := v.(*packageData)
219         return data.pkg, data.err
220 }
221
222 func (ph *packageHandle) CompiledGoFiles() []span.URI {
223         return ph.m.compiledGoFiles
224 }
225
226 func (ph *packageHandle) ID() string {
227         return string(ph.m.id)
228 }
229
230 func (ph *packageHandle) cached(g *memoize.Generation) (*pkg, error) {
231         v := ph.handle.Cached(g)
232         if v == nil {
233                 return nil, errors.Errorf("no cached type information for %s", ph.m.pkgPath)
234         }
235         data := v.(*packageData)
236         return data.pkg, data.err
237 }
238
239 func (s *snapshot) parseGoHandles(ctx context.Context, files []span.URI, mode source.ParseMode) ([]*parseGoHandle, error) {
240         pghs := make([]*parseGoHandle, 0, len(files))
241         for _, uri := range files {
242                 fh, err := s.GetFile(ctx, uri)
243                 if err != nil {
244                         return nil, err
245                 }
246                 pghs = append(pghs, s.parseGoHandle(ctx, fh, mode))
247         }
248         return pghs, nil
249 }
250
251 func typeCheck(ctx context.Context, snapshot *snapshot, m *metadata, mode source.ParseMode, deps map[packagePath]*packageHandle) (*pkg, error) {
252         ctx, done := event.Start(ctx, "cache.importer.typeCheck", tag.Package.Of(string(m.id)))
253         defer done()
254
255         var rawErrors []error
256         for _, err := range m.errors {
257                 rawErrors = append(rawErrors, err)
258         }
259
260         fset := snapshot.view.session.cache.fset
261         pkg := &pkg{
262                 m:               m,
263                 mode:            mode,
264                 goFiles:         make([]*source.ParsedGoFile, len(m.goFiles)),
265                 compiledGoFiles: make([]*source.ParsedGoFile, len(m.compiledGoFiles)),
266                 imports:         make(map[packagePath]*pkg),
267                 typesSizes:      m.typesSizes,
268                 typesInfo: &types.Info{
269                         Types:      make(map[ast.Expr]types.TypeAndValue),
270                         Defs:       make(map[*ast.Ident]types.Object),
271                         Uses:       make(map[*ast.Ident]types.Object),
272                         Implicits:  make(map[ast.Node]types.Object),
273                         Selections: make(map[*ast.SelectorExpr]*types.Selection),
274                         Scopes:     make(map[ast.Node]*types.Scope),
275                 },
276         }
277         // If this is a replaced module in the workspace, the version is
278         // meaningless, and we don't want clients to access it.
279         if m.module != nil {
280                 version := m.module.Version
281                 if source.IsWorkspaceModuleVersion(version) {
282                         version = ""
283                 }
284                 pkg.version = &module.Version{
285                         Path:    m.module.Path,
286                         Version: version,
287                 }
288         }
289         var (
290                 files        = make([]*ast.File, len(m.compiledGoFiles))
291                 parseErrors  = make([]error, len(m.compiledGoFiles))
292                 actualErrors = make([]error, len(m.compiledGoFiles))
293                 wg           sync.WaitGroup
294
295                 mu             sync.Mutex
296                 skipTypeErrors bool
297         )
298         for i, cgf := range m.compiledGoFiles {
299                 wg.Add(1)
300                 go func(i int, cgf span.URI) {
301                         defer wg.Done()
302                         fh, err := snapshot.GetFile(ctx, cgf)
303                         if err != nil {
304                                 actualErrors[i] = err
305                                 return
306                         }
307                         pgh := snapshot.parseGoHandle(ctx, fh, mode)
308                         pgf, fixed, err := snapshot.parseGo(ctx, pgh)
309                         if err != nil {
310                                 actualErrors[i] = err
311                                 return
312                         }
313                         pkg.compiledGoFiles[i] = pgf
314                         files[i], parseErrors[i], actualErrors[i] = pgf.File, pgf.ParseErr, err
315
316                         mu.Lock()
317                         skipTypeErrors = skipTypeErrors || fixed
318                         mu.Unlock()
319                 }(i, cgf)
320         }
321         for i, gf := range m.goFiles {
322                 wg.Add(1)
323                 // We need to parse the non-compiled go files, but we don't care about their errors.
324                 go func(i int, gf span.URI) {
325                         defer wg.Done()
326                         fh, err := snapshot.GetFile(ctx, gf)
327                         if err != nil {
328                                 return
329                         }
330                         pgf, _ := snapshot.ParseGo(ctx, fh, mode)
331                         pkg.goFiles[i] = pgf
332                 }(i, gf)
333         }
334         wg.Wait()
335         for _, err := range actualErrors {
336                 if err != nil {
337                         return nil, err
338                 }
339         }
340
341         for _, e := range parseErrors {
342                 if e != nil {
343                         rawErrors = append(rawErrors, e)
344                 }
345         }
346
347         var i int
348         for _, f := range files {
349                 if f != nil {
350                         files[i] = f
351                         i++
352                 }
353         }
354         files = files[:i]
355
356         // Use the default type information for the unsafe package.
357         if pkg.m.pkgPath == "unsafe" {
358                 pkg.types = types.Unsafe
359                 // Don't type check Unsafe: it's unnecessary, and doing so exposes a data
360                 // race to Unsafe.completed.
361                 return pkg, nil
362         } else if len(files) == 0 { // not the unsafe package, no parsed files
363                 // Try to attach errors messages to the file as much as possible.
364                 var found bool
365                 for _, e := range rawErrors {
366                         srcErr, err := sourceError(ctx, snapshot, pkg, e)
367                         if err != nil {
368                                 continue
369                         }
370                         found = true
371                         pkg.errors = append(pkg.errors, srcErr)
372                 }
373                 if found {
374                         return pkg, nil
375                 }
376                 return nil, errors.Errorf("no parsed files for package %s, expected: %v, list errors: %v", pkg.m.pkgPath, pkg.compiledGoFiles, rawErrors)
377         } else {
378                 pkg.types = types.NewPackage(string(m.pkgPath), string(m.name))
379         }
380
381         cfg := &types.Config{
382                 Error: func(e error) {
383                         // If we have fixed parse errors in any of the files,
384                         // we should hide type errors, as they may be completely nonsensical.
385                         if skipTypeErrors {
386                                 return
387                         }
388                         rawErrors = append(rawErrors, e)
389                 },
390                 Importer: importerFunc(func(pkgPath string) (*types.Package, error) {
391                         // If the context was cancelled, we should abort.
392                         if ctx.Err() != nil {
393                                 return nil, ctx.Err()
394                         }
395                         dep := resolveImportPath(pkgPath, pkg, deps)
396                         if dep == nil {
397                                 return nil, errors.Errorf("no package for import %s", pkgPath)
398                         }
399                         if !isValidImport(m.pkgPath, dep.m.pkgPath) {
400                                 return nil, errors.Errorf("invalid use of internal package %s", pkgPath)
401                         }
402                         depPkg, err := dep.check(ctx, snapshot)
403                         if err != nil {
404                                 return nil, err
405                         }
406                         pkg.imports[depPkg.m.pkgPath] = depPkg
407                         return depPkg.types, nil
408                 }),
409         }
410         // We want to type check cgo code if go/types supports it.
411         // We passed typecheckCgo to go/packages when we Loaded.
412         typesinternal.SetUsesCgo(cfg)
413
414         check := types.NewChecker(cfg, fset, pkg.types, pkg.typesInfo)
415
416         // Type checking errors are handled via the config, so ignore them here.
417         _ = check.Files(files)
418         // If the context was cancelled, we may have returned a ton of transient
419         // errors to the type checker. Swallow them.
420         if ctx.Err() != nil {
421                 return nil, ctx.Err()
422         }
423
424         // We don't care about a package's errors unless we have parsed it in full.
425         if mode == source.ParseFull {
426                 expandErrors(rawErrors)
427                 for _, e := range rawErrors {
428                         srcErr, err := sourceError(ctx, snapshot, pkg, e)
429                         if err != nil {
430                                 event.Error(ctx, "unable to compute error positions", err, tag.Package.Of(pkg.ID()))
431                                 continue
432                         }
433                         pkg.errors = append(pkg.errors, srcErr)
434                         if err, ok := e.(extendedError); ok {
435                                 pkg.typeErrors = append(pkg.typeErrors, err.primary)
436                         }
437                 }
438         }
439
440         return pkg, nil
441 }
442
443 type extendedError struct {
444         primary     types.Error
445         secondaries []types.Error
446 }
447
448 func (e extendedError) Error() string {
449         return e.primary.Error()
450 }
451
452 // expandErrors duplicates "secondary" errors by mapping them to their main
453 // error. Some errors returned by the type checker are followed by secondary
454 // errors which give more information about the error. These are errors in
455 // their own right, and they are marked by starting with \t. For instance, when
456 // there is a multiply-defined function, the secondary error points back to the
457 // definition first noticed.
458 //
459 // This code associates the secondary error with its primary error, which can
460 // then be used as RelatedInformation when the error becomes a diagnostic.
461 func expandErrors(errs []error) []error {
462         for i := 0; i < len(errs); {
463                 e, ok := errs[i].(types.Error)
464                 if !ok {
465                         i++
466                         continue
467                 }
468                 enew := extendedError{
469                         primary: e,
470                 }
471                 j := i + 1
472                 for ; j < len(errs); j++ {
473                         spl, ok := errs[j].(types.Error)
474                         if !ok || len(spl.Msg) == 0 || spl.Msg[0] != '\t' {
475                                 break
476                         }
477                         enew.secondaries = append(enew.secondaries, spl)
478                 }
479                 errs[i] = enew
480                 i = j
481         }
482         return errs
483 }
484
485 // resolveImportPath resolves an import path in pkg to a package from deps.
486 // It should produce the same results as resolveImportPath:
487 // https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/load/pkg.go;drc=641918ee09cb44d282a30ee8b66f99a0b63eaef9;l=990.
488 func resolveImportPath(importPath string, pkg *pkg, deps map[packagePath]*packageHandle) *packageHandle {
489         if dep := deps[packagePath(importPath)]; dep != nil {
490                 return dep
491         }
492         // We may be in GOPATH mode, in which case we need to check vendor dirs.
493         searchDir := path.Dir(pkg.PkgPath())
494         for {
495                 vdir := packagePath(path.Join(searchDir, "vendor", importPath))
496                 if vdep := deps[vdir]; vdep != nil {
497                         return vdep
498                 }
499
500                 // Search until Dir doesn't take us anywhere new, e.g. "." or "/".
501                 next := path.Dir(searchDir)
502                 if searchDir == next {
503                         break
504                 }
505                 searchDir = next
506         }
507
508         // Vendor didn't work. Let's try minimal module compatibility mode.
509         // In MMC, the packagePath is the canonical (.../vN/...) path, which
510         // is hard to calculate. But the go command has already resolved the ID
511         // to the non-versioned path, and we can take advantage of that.
512         for _, dep := range deps {
513                 if dep.ID() == importPath {
514                         return dep
515                 }
516         }
517         return nil
518 }
519
520 func isValidImport(pkgPath, importPkgPath packagePath) bool {
521         i := strings.LastIndex(string(importPkgPath), "/internal/")
522         if i == -1 {
523                 return true
524         }
525         if pkgPath == "command-line-arguments" {
526                 return true
527         }
528         return strings.HasPrefix(string(pkgPath), string(importPkgPath[:i]))
529 }
530
531 // An importFunc is an implementation of the single-method
532 // types.Importer interface based on a function value.
533 type importerFunc func(path string) (*types.Package, error)
534
535 func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }