Debian Codegraph @

gopls/internal/cache/check.go

raw symbols SCIP
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 "crypto/sha256"
11 "fmt"
12 "go/ast"
13 "go/build"
14 "go/parser"
15 "go/scanner"
16 "go/token"
17 "go/types"
18 "regexp"
19 "runtime"
20 "slices"
21 "sort"
22 "strings"
23 "sync"
24 "sync/atomic"
25
26 "golang.org/x/mod/module"
27 "golang.org/x/sync/errgroup"
28 "golang.org/x/tools/go/ast/astutil"
29 "golang.org/x/tools/gopls/internal/bloom"
30 "golang.org/x/tools/gopls/internal/cache/metadata"
31 "golang.org/x/tools/gopls/internal/cache/parsego"
32 "golang.org/x/tools/gopls/internal/cache/typerefs"
33 "golang.org/x/tools/gopls/internal/file"
34 "golang.org/x/tools/gopls/internal/filecache"
35 "golang.org/x/tools/gopls/internal/label"
36 "golang.org/x/tools/gopls/internal/protocol"
37 "golang.org/x/tools/gopls/internal/util/bug"
38 "golang.org/x/tools/gopls/internal/util/moremaps"
39 "golang.org/x/tools/gopls/internal/util/safetoken"
40 "golang.org/x/tools/gopls/internal/util/tokeninternal"
41 "golang.org/x/tools/internal/event"
42 "golang.org/x/tools/internal/gcimporter"
43 "golang.org/x/tools/internal/packagesinternal"
44 "golang.org/x/tools/internal/typesinternal"
45 "golang.org/x/tools/internal/versions"
46 )
47
48 type unit = struct{}
49
50 // A typeCheckBatch holds data for a logical type-checking operation, which may
51 // type check many unrelated packages.
52 //
53 // It shares state such as parsed files and imports, to optimize type-checking
54 // for packages with overlapping dependency graphs.
55 type typeCheckBatch struct {
56 // handleMu guards _handles, which must only be accessed via addHandles or
57 // getHandle.
58 //
59 // An alternative would be to simply verify that package handles are present
60 // on the Snapshot, and access them directly, rather than copying maps for
61 // each caller. However, handles are accessed very frequently during type
62 // checking, and ordinary go maps are measurably faster than the
63 // persistent.Map used to store handles on the snapshot.
64 handleMu sync.Mutex
65 _handles map[PackageID]*packageHandle
66
67 parseCache *parseCache
68 fset *token.FileSet // describes all parsed or imported files
69 cpulimit chan unit // concurrency limiter for CPU-bound operations
70 syntaxPackages *futureCache[PackageID, *Package] // transient cache of in-progress syntax futures
71 importPackages *futureCache[PackageID, *types.Package] // persistent cache of imports
72 gopackagesdriver bool // for bug reporting: were packages loaded with a driver?
73 }
74
75 // addHandles is called by each goroutine joining the type check batch, to
76 // ensure that the batch has all inputs necessary for type checking.
77 func (b *typeCheckBatch) addHandles(handles map[PackageID]*packageHandle) {
78 b.handleMu.Lock()
79 defer b.handleMu.Unlock()
80 for id, ph := range handles {
81 assert(ph.state >= validKey, "invalid handle")
82
83 if alt, ok := b._handles[id]; !ok || alt.state < ph.state {
84 b._handles[id] = ph
85 }
86 }
87 }
88
89 // getHandle retrieves the packageHandle for the given id.
90 func (b *typeCheckBatch) getHandle(id PackageID) *packageHandle {
91 b.handleMu.Lock()
92 defer b.handleMu.Unlock()
93 return b._handles[id]
94 }
95
96 // TypeCheck parses and type-checks the specified packages,
97 // and returns them in the same order as the ids.
98 // The resulting packages' types may belong to different importers,
99 // so types from different packages are incommensurable.
100 //
101 // The resulting packages slice always contains len(ids) entries, though some
102 // of them may be nil if (and only if) the resulting error is non-nil.
103 //
104 // An error is returned if any of the requested packages fail to type-check.
105 // This is different from having type-checking errors: a failure to type-check
106 // indicates context cancellation or otherwise significant failure to perform
107 // the type-checking operation.
108 //
109 // In general, clients should never need to type-checked syntax for an
110 // intermediate test variant (ITV) package. Callers should apply
111 // RemoveIntermediateTestVariants (or equivalent) before this method, or any
112 // of the potentially type-checking methods below.
113 func (s *Snapshot) TypeCheck(ctx context.Context, ids ...PackageID) ([]*Package, error) {
114 pkgs := make([]*Package, len(ids))
115 post := func(i int, pkg *Package) {
116 pkgs[i] = pkg
117 }
118 return pkgs, s.forEachPackage(ctx, ids, nil, post)
119 }
120
121 // Package visiting functions used by forEachPackage; see the documentation of
122 // forEachPackage for details.
123 type (
124 preTypeCheck = func(int, *packageHandle) bool // false => don't type check
125 postTypeCheck = func(int, *Package)
126 )
127
128 // forEachPackage does a pre- and post- order traversal of the packages
129 // specified by ids using the provided pre and post functions.
130 //
131 // The pre func is optional. If set, pre is evaluated after the package
132 // handle has been constructed, but before type-checking. If pre returns false,
133 // type-checking is skipped for this package handle.
134 //
135 // post is called with a syntax package after type-checking completes
136 // successfully. It is only called if pre returned true.
137 //
138 // Both pre and post may be called concurrently.
139 func (s *Snapshot) forEachPackage(ctx context.Context, ids []PackageID, pre preTypeCheck, post postTypeCheck) error {
140 ctx, done := event.Start(ctx, "cache.forEachPackage", label.PackageCount.Of(len(ids)))
141 defer done()
142
143 var (
144 needIDs []PackageID // ids to type-check
145 indexes []int // original index of needIDs[i] in ids
146 preDone []bool // pre was already called for needIDs[i] (and returned true)
147 )
148
149 // Check for existing active packages, or packages that can be served
150 // from the filecache without type-checking.
151 //
152 // Since gopls can't depend on package identity, any instance of the
153 // requested package must be ok to return.
154 //
155 // This is an optimization to avoid redundant type-checking: following
156 // changes to an open package many LSP clients send several successive
157 // requests for package information for the modified package (semantic
158 // tokens, code lens, inlay hints, etc.)
159 for i, id := range ids {
160 s.mu.Lock()
161 ph, ok := s.packages.Get(id)
162 s.mu.Unlock()
163 if ok && ph.state >= validPackage {
164 post(i, ph.pkgData.pkg)
165 continue
166 }
167 // If the handle already has a valid key, try the pre func
168 // (typically a filecache lookup) now: on a hit we can skip
169 // this package entirely without building the dependency
170 // graph.
171 called := ok && ph.state >= validKey && pre != nil
172 if called && !pre(i, ph) {
173 continue
174 }
175 needIDs = append(needIDs, id)
176 indexes = append(indexes, i)
177 preDone = append(preDone, called)
178 }
179
180 if len(needIDs) == 0 {
181 return nil // short cut: many call sites do not handle empty ids
182 }
183
184 b, release := s.acquireTypeChecking()
185 defer release()
186
187 handles, err := s.getPackageHandles(ctx, needIDs)
188 if err != nil {
189 return err
190 }
191
192 // Wrap the pre- and post- funcs to translate indices, and to avoid
193 // calling pre a second time for packages already checked above.
194 var pre2 preTypeCheck
195 if pre != nil {
196 pre2 = func(i int, ph *packageHandle) bool {
197 if preDone[i] {
198 return true // already called above; it said "proceed"
199 }
200 return pre(indexes[i], ph)
201 }
202 }
203 post2 := func(i int, pkg *Package) {
204 id := pkg.metadata.ID
205 if ph := handles[id]; ph.isOpen && ph.state < validPackage {
206 // Cache open type checked packages.
207 ph = ph.clone()
208 ph.pkgData = &packageData{
209 fset: pkg.FileSet(),
210 imports: pkg.Types().Imports(),
211 pkg: pkg,
212 }
213 ph.state = validPackage
214
215 s.mu.Lock()
216 if alt, ok := s.packages.Get(id); !ok || alt.state < ph.state {
217 s.packages.Set(id, ph, nil)
218 }
219 s.mu.Unlock()
220 }
221
222 post(indexes[i], pkg)
223 }
224
225 return b.query(ctx, needIDs, pre2, post2, handles)
226 }
227
228 // acquireTypeChecking joins or starts a concurrent type checking batch.
229 //
230 // The batch may be queried for package information using [typeCheckBatch.query].
231 // The second result must be called when the batch is no longer needed, to
232 // release the resource.
233 func (s *Snapshot) acquireTypeChecking() (*typeCheckBatch, func()) {
234 s.typeCheckMu.Lock()
235 defer s.typeCheckMu.Unlock()
236
237 if s.batch == nil {
238 assert(s.batchRef == 0, "miscounted type checking")
239 s.batch = newTypeCheckBatch(s.view.parseCache, s.view.typ == GoPackagesDriverView)
240 }
241 s.batchRef++
242
243 return s.batch, func() {
244 s.typeCheckMu.Lock()
245 defer s.typeCheckMu.Unlock()
246 assert(s.batchRef > 0, "miscounted type checking 2")
247 s.batchRef--
248 if s.batchRef == 0 {
249 s.batch = nil
250 }
251 }
252 }
253
254 // newTypeCheckBatch creates a new type checking batch using the provided
255 // shared parseCache.
256 //
257 // If a non-nil importGraph is provided, imports in this graph will be reused.
258 func newTypeCheckBatch(parseCache *parseCache, gopackagesdriver bool) *typeCheckBatch {
259 return &typeCheckBatch{
260 _handles: make(map[PackageID]*packageHandle),
261 parseCache: parseCache,
262 fset: fileSetWithBase(reservedForParsing),
263 cpulimit: make(chan unit, runtime.GOMAXPROCS(0)),
264 syntaxPackages: newFutureCache[PackageID, *Package](false), // don't persist syntax packages
265 importPackages: newFutureCache[PackageID, *types.Package](true), // ...but DO persist imports
266 gopackagesdriver: gopackagesdriver,
267 }
268 }
269
270 // query executes a traversal of package information in the given typeCheckBatch.
271 // For each package in importIDs, the package will be loaded "for import" (sans
272 // syntax).
273 //
274 // For each package in syntaxIDs, the package will be handled following the
275 // pre- and post- traversal logic of [Snapshot.forEachPackage].
276 //
277 // Package handles must be provided for each package in the forward transitive
278 // closure of either importIDs or syntaxIDs.
279 //
280 // TODO(rfindley): simplify this API by clarifying shared import graph and
281 // package handle logic.
282 func (b *typeCheckBatch) query(ctx context.Context, syntaxIDs []PackageID, pre preTypeCheck, post postTypeCheck, handles map[PackageID]*packageHandle) error {
283 b.addHandles(handles)
284
285 // Start a single goroutine for each requested package.
286 //
287 // Other packages are reached recursively, and will not be evaluated if they
288 // are not needed.
289 var g errgroup.Group
290 for i, id := range syntaxIDs {
291 g.Go(func() error {
292 if ctx.Err() != nil {
293 return ctx.Err()
294 }
295 return b.handleSyntaxPackage(ctx, i, id, pre, post)
296 })
297 }
298 return g.Wait()
299 }
300
301 // TODO(rfindley): re-order the declarations below to read better from top-to-bottom.
302
303 // getImportPackage returns the *types.Package to use for importing the
304 // package referenced by id.
305 //
306 // This may be the package produced by type-checking syntax (as in the case
307 // where id is in the set of requested IDs), a package loaded from export data,
308 // or a package type-checked for import only.
309 func (b *typeCheckBatch) getImportPackage(ctx context.Context, id PackageID) (pkg *types.Package, err error) {
310 return b.importPackages.get(ctx, id, func(ctx context.Context) (*types.Package, error) {
311 ph := b.getHandle(id)
312
313 // "unsafe" cannot be imported or type-checked.
314 //
315 // We check PkgPath, not id, as the structure of the ID
316 // depends on the build system (in particular,
317 // Bazel+gopackagesdriver appears to use something other than
318 // "unsafe", though we aren't sure what; even 'go list' can
319 // use "p [q.test]" for testing or if PGO is enabled.
320 // See golang/go#60890.
321 if ph.mp.PkgPath == "unsafe" {
322 return types.Unsafe, nil
323 }
324
325 if data, ok := filecache.GetOrFatal(exportDataKind, ph.key, filecache.Bytes); ok {
326 return b.importPackage(ctx, ph.mp, data)
327 }
328 // No cached export data (or hit error): type-check as fast as possible.
329 return b.checkPackageForImport(ctx, ph)
330 })
331 }
332
333 // handleSyntaxPackage handles one package from the ids slice.
334 //
335 // If type checking occurred while handling the package, it returns the
336 // resulting types.Package so that it may be used for importing.
337 //
338 // handleSyntaxPackage returns (nil, nil) if pre returned false.
339 func (b *typeCheckBatch) handleSyntaxPackage(ctx context.Context, i int, id PackageID, pre preTypeCheck, post postTypeCheck) error {
340 ph := b.getHandle(id)
341 if pre != nil && !pre(i, ph) {
342 return nil // skip: not needed
343 }
344
345 // Check if we have a syntax package stored on ph.
346 //
347 // This was checked in [Snapshot.forEachPackage], but may have since changed.
348 if ph.state >= validPackage {
349 post(i, ph.pkgData.pkg)
350 return nil
351 }
352
353 pkg, err := b.getPackage(ctx, ph)
354 if err != nil {
355 return err
356 }
357
358 post(i, pkg)
359 return nil
360 }
361
362 // getPackage type checks one [Package] in the batch.
363 func (b *typeCheckBatch) getPackage(ctx context.Context, ph *packageHandle) (*Package, error) {
364 return b.syntaxPackages.get(ctx, ph.mp.ID, func(ctx context.Context) (*Package, error) {
365 // Wait for predecessors.
366 // Record imports of this package to avoid redundant work in typesConfig.
367 imports := make(map[PackagePath]*types.Package)
368 fset := b.fset
369 if ph.state >= validImports {
370 for _, imp := range ph.pkgData.imports {
371 imports[PackagePath(imp.Path())] = imp
372 }
373 // Reusing imports requires that their positions are mapped by the FileSet.
374 fset = tokeninternal.CloneFileSet(ph.pkgData.fset)
375 } else {
376 var impMu sync.Mutex
377 var g errgroup.Group
378 for depPath, depID := range ph.mp.DepsByPkgPath {
379 g.Go(func() error {
380 imp, err := b.getImportPackage(ctx, depID)
381 if err == nil {
382 impMu.Lock()
383 imports[depPath] = imp
384 impMu.Unlock()
385 }
386 return err
387 })
388 }
389 if err := g.Wait(); err != nil {
390 // Failure to import a package should not abort the whole operation.
391 // Stop only if the context was cancelled, a likely cause.
392 // Import errors will be reported as type diagnostics.
393 if ctx.Err() != nil {
394 return nil, ctx.Err()
395 }
396 }
397 }
398
399 // Wait to acquire a CPU token.
400 //
401 // Note: it is important to acquire this token only after awaiting
402 // predecessors, to avoid starvation.
403 select {
404 case <-ctx.Done():
405 return nil, ctx.Err()
406 case b.cpulimit <- unit{}:
407 defer func() {
408 <-b.cpulimit // release CPU token
409 }()
410 }
411
412 // Compute the syntax package.
413 p, err := b.checkPackage(ctx, fset, ph, imports)
414 if err != nil {
415 return nil, err // e.g. I/O error, cancelled
416 }
417
418 // Update caches.
419 go storePackageResults(ctx, ph, p) // ...and write all packages to disk
420 return p, nil
421 })
422 }
423
424 // storePackageResults serializes and writes information derived from p to the
425 // file cache.
426 // The context is used only for logging; cancellation does not affect the operation.
427 func storePackageResults(ctx context.Context, ph *packageHandle, p *Package) {
428 toCache := map[string][]byte{
429 xrefsKind: p.pkg.xrefs().Encode(),
430 methodSetsKind: p.pkg.methodsets().Encode(),
431 testsKind: p.pkg.tests().Encode(),
432 diagnosticsKind: encodeDiagnostics(p.pkg.diagnostics),
433 }
434
435 if p.metadata.PkgPath != "unsafe" { // unsafe cannot be exported
436 exportData, err := gcimporter.IExportShallow(p.pkg.fset, p.pkg.types, bug.Reportf)
437 if err != nil {
438 bug.Reportf("exporting package %v: %v", p.metadata.ID, err)
439 } else {
440 toCache[exportDataKind] = exportData
441 }
442 }
443
444 for kind, data := range toCache {
445 if err := filecache.Set(kind, ph.key, data); err != nil {
446 event.Error(ctx, fmt.Sprintf("storing %s data for %s", kind, ph.mp.ID), err)
447 }
448 }
449 }
450
451 // Metadata implements the [metadata.Source] interface.
452 func (b *typeCheckBatch) Metadata(id PackageID) *metadata.Package {
453 ph := b.getHandle(id)
454 if ph == nil {
455 return nil
456 }
457 return ph.mp
458 }
459
460 // importPackage loads the given package from its export data in p.exportData
461 // (which must already be populated).
462 func (b *typeCheckBatch) importPackage(ctx context.Context, mp *metadata.Package, data []byte) (*types.Package, error) {
463 ctx, done := event.Start(ctx, "cache.typeCheckBatch.importPackage", label.Package.Of(string(mp.ID)))
464 defer done()
465
466 importLookup := importLookup(mp, b)
467
468 thisPackage := types.NewPackage(string(mp.PkgPath), string(mp.Name))
469 getPackages := func(items []gcimporter.GetPackagesItem) error {
470 for i, item := range items {
471 var id PackageID
472 var pkg *types.Package
473 if item.Path == string(mp.PkgPath) {
474 id = mp.ID
475 pkg = thisPackage
476
477 // debugging issues #60904, #64235
478 if pkg.Name() != item.Name {
479 // This would mean that mp.Name != item.Name, so the
480 // manifest in the export data of mp.PkgPath is
481 // inconsistent with mp.Name. Or perhaps there
482 // are duplicate PkgPath items in the manifest?
483 if b.gopackagesdriver {
484 return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904) (using GOPACKAGESDRIVER)",
485 pkg.Name(), item.Name, id, item.Path)
486 } else {
487 // There's a package in the export data with the same path as the
488 // imported package, but a different name.
489 //
490 // This is observed to occur (very frequently!) in telemetry, yet
491 // we don't yet have a plausible explanation: any self import or
492 // circular import should have resulted in a broken import, which
493 // can't be referenced by export data. (Any type qualified by the
494 // broken import name will be invalid.)
495 //
496 // However, there are some mechanisms that could potentially be
497 // involved:
498 // 1. go/types will synthesize package names based on the import
499 // path for fake packages (but as mentioned above, I don't think
500 // these can be referenced by export data.)
501 // 2. Test variants have the same path as non-test variant. Could
502 // that somehow be involved? (I don't see how, particularly using
503 // the go list driver, but nevertheless it's worth considering.)
504 // 3. Command-line arguments and main packages may have special
505 // handling that we don't fully understand.
506 // Try to sort these potential causes into unique stacks, as well
507 // as a few other pathological scenarios.
508 report := func() error {
509 return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904)",
510 pkg.Name(), item.Name, id, item.Path)
511 }
512 impliedName := ""
513 if i := strings.LastIndex(item.Path, "/"); i >= 0 {
514 impliedName = item.Path[i+1:]
515 }
516 switch {
517 case pkg.Name() == "":
518 return report()
519 case item.Name == "":
520 return report()
521 case metadata.IsCommandLineArguments(mp.ID):
522 return report()
523 case mp.ForTest != "":
524 return report()
525 case len(mp.CompiledGoFiles) == 0:
526 return report()
527 case len(mp.Errors) > 0:
528 return report()
529 case impliedName != "" && impliedName != string(mp.Name):
530 return report()
531 case len(mp.CompiledGoFiles) != len(mp.GoFiles):
532 return report()
533 case mp.Module == nil:
534 return report()
535 case mp.Name == "main":
536 return report()
537 default:
538 return report()
539 }
540 }
541 }
542 } else {
543 var alt PackageID
544 id, alt = importLookup(PackagePath(item.Path))
545 if alt != "" {
546 // Any bug leading to this scenario would have already been reported
547 // in importLookup.
548 return fmt.Errorf("inconsistent metadata during import: for package path %q, found both IDs %q and %q", item.Path, id, alt)
549 }
550 var err error
551 pkg, err = b.getImportPackage(ctx, id)
552 if err != nil {
553 return err
554 }
555
556 // We intentionally duplicate the bug.Errorf calls because
557 // telemetry tells us only the program counter, not the message.
558
559 // debugging issues #60904, #64235
560 if pkg.Name() != item.Name {
561 // This means that, while reading the manifest of the
562 // export data of mp.PkgPath, one of its indirect
563 // dependencies had a name that differs from the
564 // Metadata.Name
565 return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904)",
566 pkg.Name(), item.Name, id, item.Path)
567 }
568 }
569 items[i].Pkg = pkg
570
571 }
572 return nil
573 }
574
575 // Importing is potentially expensive, and might not encounter cancellations
576 // via dependencies (e.g. if they have already been evaluated).
577 if ctx.Err() != nil {
578 return nil, ctx.Err()
579 }
580
581 imported, err := gcimporter.IImportShallow(b.fset, getPackages, data, string(mp.PkgPath), bug.Reportf)
582 if err != nil {
583 return nil, fmt.Errorf("import failed for %q: %v", mp.ID, err)
584 }
585 return imported, nil
586 }
587
588 // checkPackageForImport type checks, but skips function bodies and does not
589 // record syntax information.
590 func (b *typeCheckBatch) checkPackageForImport(ctx context.Context, ph *packageHandle) (*types.Package, error) {
591 ctx, done := event.Start(ctx, "cache.typeCheckBatch.checkPackageForImport", label.Package.Of(string(ph.mp.ID)))
592 defer done()
593
594 onError := func(e error) {
595 // Ignore errors for exporting.
596 }
597 cfg := b.typesConfig(ctx, ph.localInputs, nil, onError)
598 cfg.IgnoreFuncBodies = true
599
600 // Parse the compiled go files, bypassing the parse cache as packages checked
601 // for import are unlikely to get cache hits. Additionally, we can optimize
602 // parsing slightly by not passing parser.ParseComments.
603 pgfs := make([]*parsego.File, len(ph.localInputs.compiledGoFiles))
604 {
605 var group errgroup.Group
606 // Set an arbitrary concurrency limit; we want some parallelism but don't
607 // need GOMAXPROCS, as there is already a lot of concurrency among calls to
608 // checkPackageForImport.
609 //
610 // TODO(rfindley): is there a better way to limit parallelism here? We could
611 // have a global limit on the type-check batch, but would have to be very
612 // careful to avoid starvation.
613 group.SetLimit(4)
614 for i, fh := range ph.localInputs.compiledGoFiles {
615 group.Go(func() error {
616 pgf, err := parseGoImpl(ctx, b.fset, fh, parser.SkipObjectResolution, false)
617 pgfs[i] = pgf
618 return err
619 })
620 }
621 if err := group.Wait(); err != nil {
622 return nil, err // cancelled, or catastrophic error (e.g. missing file)
623 }
624 }
625 pkg := types.NewPackage(string(ph.localInputs.pkgPath), string(ph.localInputs.name))
626 check := types.NewChecker(cfg, b.fset, pkg, nil)
627
628 files := make([]*ast.File, len(pgfs))
629 for i, pgf := range pgfs {
630 files[i] = pgf.File
631 }
632
633 // Type checking is expensive, and we may not have encountered cancellations
634 // via parsing (e.g. if we got nothing but cache hits for parsed files).
635 if ctx.Err() != nil {
636 return nil, ctx.Err()
637 }
638
639 _ = check.Files(files) // ignore errors
640
641 // If the context was cancelled, we may have returned a ton of transient
642 // errors to the type checker. Swallow them.
643 if ctx.Err() != nil {
644 return nil, ctx.Err()
645 }
646
647 // Asynchronously record export data.
648 go func() {
649 exportData, err := gcimporter.IExportShallow(b.fset, pkg, bug.Reportf)
650 if err != nil {
651 // Internal error; the stack will have been reported via
652 // bug.Reportf within IExportShallow, so there's not much
653 // to do here (issue #71067).
654 event.Error(ctx, "IExportShallow failed", err, label.Package.Of(string(ph.mp.ID)))
655 return
656 }
657 if err := filecache.Set(exportDataKind, ph.key, exportData); err != nil {
658 event.Error(ctx, fmt.Sprintf("storing export data for %s", ph.mp.ID), err)
659 }
660 }()
661 return pkg, nil
662 }
663
664 // importLookup returns a function that may be used to look up a package ID for
665 // a given package path, based on the forward transitive closure of the initial
666 // package (id).
667 //
668 // If the second result is non-empty, it is another ID discovered in the import
669 // graph for the same package path. This means the import graph is
670 // incoherent--see #63822 and the long comment below.
671 //
672 // The resulting function is not concurrency safe.
673 func importLookup(mp *metadata.Package, source metadata.Source) func(PackagePath) (id, altID PackageID) {
674 assert(mp != nil, "nil metadata")
675
676 // This function implements an incremental depth first scan through the
677 // package imports. Previous implementations of import mapping built the
678 // entire PackagePath->PackageID mapping eagerly, but that resulted in a
679 // large amount of unnecessary work: most imports are either directly
680 // imported, or found through a shallow scan.
681
682 // impMap memoizes the lookup of package paths.
683 impMap := map[PackagePath]PackageID{
684 mp.PkgPath: mp.ID,
685 }
686
687 // altIDs records alternative IDs for the given path, to report inconsistent
688 // metadata.
689 var altIDs map[PackagePath]PackageID
690
691 // pending is a FIFO queue of package metadata that has yet to have its
692 // dependencies fully scanned.
693 // Invariant: all entries in pending are already mapped in impMap.
694 pending := []*metadata.Package{mp}
695
696 // search scans children the next package in pending, looking for pkgPath.
697 // Invariant: whenever search is called, pkgPath is not yet mapped.
698 search := func(pkgPath PackagePath) (id PackageID, found bool) {
699 pkg := pending[0]
700 pending = pending[1:]
701 for depPath, depID := range pkg.DepsByPkgPath {
702 if prevID, ok := impMap[depPath]; ok {
703 // debugging #63822
704 if prevID != depID {
705 if altIDs == nil {
706 altIDs = make(map[PackagePath]PackageID)
707 }
708 if _, ok := altIDs[depPath]; !ok {
709 altIDs[depPath] = depID
710 }
711 prev := source.Metadata(prevID)
712 curr := source.Metadata(depID)
713 switch {
714 case prev == nil || curr == nil:
715 bug.Reportf("inconsistent view of dependencies (missing dep)")
716 case prev.ForTest != curr.ForTest:
717 // This case is unfortunately understood to be possible.
718 //
719 // To explain this, consider a package a_test testing the package
720 // a, and for brevity denote by b' the intermediate test variant of
721 // the package b, which is created for the import graph of a_test,
722 // if b imports a.
723 //
724 // Now imagine that we have the following import graph, where
725 // higher packages import lower ones.
726 //
727 // a_test
728 // / \
729 // b' c
730 // / \ /
731 // a d
732 //
733 // In this graph, there is one intermediate test variant b',
734 // because b imports a and so b' must hold the test variant import.
735 //
736 // Now, imagine that an on-disk change (perhaps due to a branch
737 // switch) affects the above import graph such that d imports a.
738 //
739 // a_test
740 // / \
741 // b' c*
742 // / \ /
743 // / d*
744 // a---/
745 //
746 // In this case, c and d should really be intermediate test
747 // variants, because they reach a. However, suppose that gopls does
748 // not know this yet (as indicated by '*').
749 //
750 // Now suppose that the metadata of package c is invalidated, for
751 // example due to a change in an unrelated import or an added file.
752 // This will invalidate the metadata of c and a_test (but NOT b),
753 // and now gopls observes this graph:
754 //
755 // a_test
756 // / \
757 // b' c'
758 // /| |
759 // / d d'
760 // a-----/
761 //
762 // That is: a_test now sees c', which sees d', but since b was not
763 // invalidated, gopls still thinks that b' imports d (not d')!
764 //
765 // The problem, of course, is that gopls never observed the change
766 // to d, which would have invalidated b. This may be due to racing
767 // file watching events, in which case the problem should
768 // self-correct when gopls sees the change to d, or it may be due
769 // to d being outside the coverage of gopls' file watching glob
770 // patterns, or it may be due to buggy or entirely absent
771 // client-side file watching.
772 //
773 // TODO(rfindley): fix this, one way or another. It would be hard
774 // or impossible to repair gopls' state here, during type checking.
775 // However, we could perhaps reload metadata in Snapshot.load until
776 // we achieve a consistent state, or better, until the loaded state
777 // is consistent with our view of the filesystem, by making the Go
778 // command report digests of the files it reads. Both of those are
779 // tricker than they may seem, and have significant performance
780 // implications.
781 default:
782 bug.Reportf("inconsistent view of dependencies")
783 }
784 }
785 continue
786 }
787 impMap[depPath] = depID
788
789 dep := source.Metadata(depID)
790 assert(dep != nil, "missing dep metadata")
791
792 pending = append(pending, dep)
793 if depPath == pkgPath {
794 // Don't return early; finish processing pkg's deps.
795 id = depID
796 found = true
797 }
798 }
799 return id, found
800 }
801
802 return func(pkgPath PackagePath) (id, altID PackageID) {
803 if id, ok := impMap[pkgPath]; ok {
804 return id, altIDs[pkgPath]
805 }
806 for len(pending) > 0 {
807 if id, found := search(pkgPath); found {
808 return id, altIDs[pkgPath]
809 }
810 }
811 return "", ""
812 }
813 }
814
815 // A packageState is the state of a [packageHandle]; see below for details.
816 type packageState uint8
817
818 const (
819 validMetadata packageState = iota // the package has valid metadata
820 validLocalData // local package files have been analyzed
821 validKey // dependencies have been analyzed, and key produced
822 validImports // pkgData.fset and pkgData.imports are valid
823 validPackage // pkgData.pkg is valid
824 )
825
826 // A packageHandle holds information derived from a metadata.Package, and
827 // records its degree of validity as state changes occur: successful analysis
828 // causes the state to progress; invalidation due to changes causes it to
829 // regress.
830 //
831 // In the initial state (validMetadata), all we know is the metadata for the
832 // package itself. This is the lowest state, and it cannot become invalid
833 // because the metadata for a given snapshot never changes. (Each handle is
834 // implicitly associated with a Snapshot.)
835 //
836 // After the files of the package have been read (validLocalData), we can
837 // perform computations that are local to that package, such as parsing, or
838 // building the symbol reference graph (SRG). This information is invalidated
839 // by a change to any file in the package. The local information is thus
840 // sufficient to form a cache key for saved parsed trees or the SRG.
841 //
842 // Once all dependencies have been analyzed (validKey), we can type-check the
843 // package. This information is invalidated by any change to the package
844 // itself, or to any dependency that is transitively reachable through the SRG.
845 // The cache key for saved type information must thus incorporate information
846 // from all reachable dependencies. This reachability analysis implements what
847 // we sometimes refer to as "precise pruning", or fine-grained invalidation:
848 // https://go.dev/blog/gopls-scalability#invalidation
849 //
850 // After type checking, package information for open packages is cached in the
851 // pkgData field (validPackage), to optimize subsequent requests oriented
852 // around open files.
853 //
854 // Following a change, the packageHandle is cloned in the new snapshot with a
855 // new state set to its least known valid state, as described above: if package
856 // files changed, it is reset to validMetadata; if dependencies changed, it is
857 // reset to validLocalData. However, the derived data from its previous state
858 // is not yet removed, as keys may not have changed after they are reevaluated,
859 // in which case we can avoid recomputing the derived data. In particular, if
860 // the cache key did not change, the pkgData field (if set) remains valid. As a
861 // special case, if the cache key did change, but none of the keys of
862 // dependencies changed, the pkgData.fset and pkgData.imports fields are still
863 // valid, though the pkgData.pkg field is not (validImports).
864 //
865 // See [packageHandleBuilder.evaluatePackageHandle] for more details of the
866 // reevaluation algorithm.
867 //
868 // packageHandles are immutable once they are stored in the Snapshot.packages
869 // map: any changes to packageHandle fields evaluatePackageHandle must be made
870 // to a cloned packageHandle, and inserted back into Snapshot.packages. Data
871 // referred to by the packageHandle may be shared by multiple clones, and so
872 // referents must not be mutated.
873 type packageHandle struct {
874 mp *metadata.Package
875
876 // state indicates which data below are still valid.
877 state packageState
878
879 // Local data:
880
881 // loadDiagnostics memoizes the result of processing error messages from
882 // go/packages (i.e. `go list`).
883 //
884 // These are derived from metadata using a snapshot. Since they depend on
885 // file contents (for translating positions), they should theoretically be
886 // invalidated by file changes, but historically haven't been. In practice
887 // they are rare and indicate a fundamental error that needs to be corrected
888 // before development can continue, so it may not be worth significant
889 // engineering effort to implement accurate invalidation here.
890 //
891 // TODO(rfindley): loadDiagnostics are out of place here, as they don't
892 // directly relate to type checking. We should perhaps move the caching of
893 // load diagnostics to an entirely separate component, so that Packages need
894 // only be concerned with parsing and type checking.
895 // (Nevertheless, since the lifetime of load diagnostics matches that of the
896 // Metadata, it is convenient to memoize them here.)
897 loadDiagnostics []*Diagnostic
898 // localInputs holds all local type-checking localInputs, excluding
899 // dependencies.
900 localInputs *typeCheckInputs
901 // isOpen reports whether the package has any open files.
902 isOpen bool
903 // localKey is a hash of localInputs.
904 localKey file.Hash
905 // refs is the result of syntactic dependency analysis produced by the
906 // typerefs package. Derived from localInputs.
907 refs map[string][]typerefs.Symbol
908
909 // Keys, computed through reachability analysis of dependencies.
910
911 // depKeys records the key of each dependency that was used to calculate the
912 // key below. If state < validKey, we must re-check that each still matches.
913 depKeys map[PackageID]file.Hash
914
915 // reachable is used to filter reachable package paths for go/analysis fact
916 // importing.
917 reachable *bloom.Filter
918
919 // key is the hashed key for the package.
920 //
921 // It includes the all bits of the transitive closure of
922 // dependencies's sources.
923 key file.Hash
924
925 // pkgData caches data derived from type checking the package.
926 // This data is set during [Snapshot.forEachPackage], and may be partially
927 // invalidated in [packageHandleBuilder.evaluatePackageHandle].
928 //
929 // If state == validPackage, all fields of pkgData are valid. If state ==
930 // validImports, only fset and imports are valid.
931 pkgData *packageData
932 }
933
934 // packageData holds the (possibly partial) result of type checking this
935 // package. See the pkgData field of [packageHandle].
936 //
937 // packageData instances are immutable.
938 type packageData struct {
939 fset *token.FileSet // pkg.FileSet()
940 imports []*types.Package // pkg.Types().Imports()
941 pkg *Package // pkg, if state==validPackage; nil in lower states
942 }
943
944 // clone returns a shallow copy of the receiver.
945 func (ph *packageHandle) clone() *packageHandle {
946 clone := *ph
947 return &clone
948 }
949
950 // getPackageHandles gets package handles for all given ids and their
951 // dependencies, recursively. The resulting [packageHandle] values are fully
952 // evaluated (their state will be at least validKey).
953 func (s *Snapshot) getPackageHandles(ctx context.Context, ids []PackageID) (map[PackageID]*packageHandle, error) {
954 // perform a two-pass traversal.
955 //
956 // On the first pass, build up a bidirectional graph of handle nodes, and collect leaves.
957 // Then build package handles from bottom up.
958 b := &packageHandleBuilder{
959 s: s,
960 transitiveRefs: make(map[typerefs.IndexID]*partialRefs),
961 nodes: make(map[typerefs.IndexID]*handleNode),
962 }
963
964 meta := s.MetadataGraph()
965
966 var leaves []*handleNode
967 var makeNode func(*handleNode, PackageID) *handleNode
968 makeNode = func(from *handleNode, id PackageID) *handleNode {
969 idxID := s.view.pkgIndex.IndexID(id)
970 n, ok := b.nodes[idxID]
971 if !ok {
972 mp := meta.Packages[id]
973 if mp == nil {
974 panic(fmt.Sprintf("nil metadata for %q", id))
975 }
976 n = &handleNode{
977 mp: mp,
978 idxID: idxID,
979 unfinishedSuccs: int32(len(mp.DepsByPkgPath)),
980 }
981 if n.unfinishedSuccs == 0 {
982 leaves = append(leaves, n)
983 } else {
984 n.succs = make(map[PackageID]*handleNode, n.unfinishedSuccs)
985 }
986 b.nodes[idxID] = n
987 for _, depID := range mp.DepsByPkgPath {
988 n.succs[depID] = makeNode(n, depID)
989 }
990 }
991 // Add edge from predecessor.
992 if from != nil {
993 n.preds = append(n.preds, from)
994 }
995 return n
996 }
997 for _, id := range ids {
998 if ctx.Err() != nil {
999 return nil, ctx.Err()
1000 }
1001 makeNode(nil, id)
1002 }
1003
1004 g, ctx := errgroup.WithContext(ctx)
1005
1006 // files are preloaded, so building package handles is CPU-bound.
1007 //
1008 // Note that we can't use g.SetLimit, as that could result in starvation:
1009 // g.Go blocks until a slot is available, and so all existing goroutines
1010 // could be blocked trying to enqueue a predecessor.
1011 limiter := make(chan unit, runtime.GOMAXPROCS(0))
1012
1013 var enqueue func(*handleNode)
1014 enqueue = func(n *handleNode) {
1015 g.Go(func() error {
1016 limiter <- unit{}
1017 defer func() { <-limiter }()
1018
1019 if ctx.Err() != nil {
1020 return ctx.Err()
1021 }
1022
1023 if err := b.evaluatePackageHandle(ctx, n); err != nil {
1024 return err
1025 }
1026
1027 for _, pred := range n.preds {
1028 if atomic.AddInt32(&pred.unfinishedSuccs, -1) == 0 {
1029 enqueue(pred)
1030 }
1031 }
1032 return nil
1033 })
1034 }
1035 for _, leaf := range leaves {
1036 enqueue(leaf)
1037 }
1038
1039 if err := g.Wait(); err != nil {
1040 return nil, err
1041 }
1042
1043 // Copy handles into the result map.
1044 handles := make(map[PackageID]*packageHandle, len(b.nodes))
1045 for _, v := range b.nodes {
1046 assert(v.ph != nil, "nil handle")
1047 handles[v.mp.ID] = v.ph
1048 }
1049
1050 return handles, nil
1051 }
1052
1053 // A packageHandleBuilder computes a batch of packageHandles concurrently,
1054 // sharing computed transitive reachability sets used to compute package keys.
1055 type packageHandleBuilder struct {
1056 s *Snapshot
1057
1058 // nodes are assembled synchronously.
1059 nodes map[typerefs.IndexID]*handleNode
1060
1061 // transitiveRefs is incrementally evaluated as package handles are built.
1062 transitiveRefsMu sync.Mutex
1063 transitiveRefs map[typerefs.IndexID]*partialRefs // see getTransitiveRefs
1064 }
1065
1066 // A handleNode represents a to-be-computed packageHandle within a graph of
1067 // predecessors and successors.
1068 //
1069 // It is used to implement a bottom-up construction of packageHandles.
1070 type handleNode struct {
1071 mp *metadata.Package
1072 idxID typerefs.IndexID
1073 ph *packageHandle
1074 preds []*handleNode
1075 succs map[PackageID]*handleNode
1076 unfinishedSuccs int32
1077 }
1078
1079 // partialRefs maps names declared by a given package to their set of
1080 // transitive references.
1081 //
1082 // If complete is set, refs is known to be complete for the package in
1083 // question. Otherwise, it may only map a subset of all names declared by the
1084 // package.
1085 type partialRefs struct {
1086 refs map[string]*typerefs.PackageSet
1087 complete bool
1088 }
1089
1090 // getTransitiveRefs gets or computes the set of transitively reachable
1091 // packages for each exported name in the package specified by id.
1092 //
1093 // The operation may fail if building a predecessor failed. If and only if this
1094 // occurs, the result will be nil.
1095 func (b *packageHandleBuilder) getTransitiveRefs(pkgID PackageID) map[string]*typerefs.PackageSet {
1096 b.transitiveRefsMu.Lock()
1097 defer b.transitiveRefsMu.Unlock()
1098
1099 idxID := b.s.view.pkgIndex.IndexID(pkgID)
1100 trefs, ok := b.transitiveRefs[idxID]
1101 if !ok {
1102 trefs = &partialRefs{
1103 refs: make(map[string]*typerefs.PackageSet),
1104 }
1105 b.transitiveRefs[idxID] = trefs
1106 }
1107
1108 if !trefs.complete {
1109 trefs.complete = true
1110 node := b.nodes[idxID]
1111 for name := range node.ph.refs {
1112 if ('A' <= name[0] && name[0] <= 'Z') || token.IsExported(name) {
1113 if _, ok := trefs.refs[name]; !ok {
1114 pkgs := b.s.view.pkgIndex.NewSet()
1115 for _, sym := range node.ph.refs[name] {
1116 pkgs.Add(sym.Package)
1117 otherSet := b.getOneTransitiveRefLocked(sym)
1118 pkgs.Union(otherSet)
1119 }
1120 trefs.refs[name] = pkgs
1121 }
1122 }
1123 }
1124 }
1125
1126 return trefs.refs
1127 }
1128
1129 // getOneTransitiveRefLocked computes the full set packages transitively
1130 // reachable through the given sym reference.
1131 //
1132 // It may return nil if the reference is invalid (i.e. the referenced name does
1133 // not exist).
1134 func (b *packageHandleBuilder) getOneTransitiveRefLocked(sym typerefs.Symbol) *typerefs.PackageSet {
1135 assert(token.IsExported(sym.Name), "expected exported symbol")
1136
1137 trefs := b.transitiveRefs[sym.Package]
1138 if trefs == nil {
1139 trefs = &partialRefs{
1140 refs: make(map[string]*typerefs.PackageSet),
1141 complete: false,
1142 }
1143 b.transitiveRefs[sym.Package] = trefs
1144 }
1145
1146 pkgs, ok := trefs.refs[sym.Name]
1147 if ok && pkgs == nil {
1148 // See below, where refs is set to nil before recursing.
1149 bug.Reportf("cycle detected to %q in reference graph", sym.Name)
1150 }
1151
1152 // Note that if (!ok && trefs.complete), the name does not exist in the
1153 // referenced package, and we should not write to trefs as that may introduce
1154 // a race.
1155 if !ok && !trefs.complete {
1156 n := b.nodes[sym.Package]
1157 if n == nil {
1158 // We should always have IndexID in our node set, because symbol references
1159 // should only be recorded for packages that actually exist in the import graph.
1160 //
1161 // However, it is not easy to prove this (typerefs are serialized and
1162 // deserialized), so make this code temporarily defensive while we are on a
1163 // point release.
1164 //
1165 // TODO(rfindley): in the future, we should turn this into an assertion.
1166 bug.Reportf("missing reference to package %s", b.s.view.pkgIndex.PackageID(sym.Package))
1167 return nil
1168 }
1169
1170 // Break cycles. This is perhaps overly defensive as cycles should not
1171 // exist at this point: metadata cycles should have been broken at load
1172 // time, and intra-package reference cycles should have been contracted by
1173 // the typerefs algorithm.
1174 //
1175 // See the "cycle detected" bug report above.
1176 trefs.refs[sym.Name] = nil
1177
1178 pkgs := b.s.view.pkgIndex.NewSet()
1179 for _, sym2 := range n.ph.refs[sym.Name] {
1180 pkgs.Add(sym2.Package)
1181 otherSet := b.getOneTransitiveRefLocked(sym2)
1182 pkgs.Union(otherSet)
1183 }
1184 trefs.refs[sym.Name] = pkgs
1185 }
1186
1187 return pkgs
1188 }
1189
1190 // evaluatePackageHandle recomputes the derived information in the package handle.
1191 // On success, the handle's state is validKey.
1192 //
1193 // evaluatePackageHandle must only be called from getPackageHandles.
1194 func (b *packageHandleBuilder) evaluatePackageHandle(ctx context.Context, n *handleNode) (err error) {
1195 b.s.mu.Lock()
1196 ph, hit := b.s.packages.Get(n.mp.ID)
1197 b.s.mu.Unlock()
1198
1199 defer func() {
1200 if err == nil {
1201 assert(ph.state >= validKey, "invalid handle")
1202
1203 // Record the now valid key in the snapshot.
1204 // There may be a race, so avoid the write if the recorded handle is
1205 // already valid.
1206 b.s.mu.Lock()
1207 if alt, ok := b.s.packages.Get(n.mp.ID); !ok || alt.state < ph.state {
1208 b.s.packages.Set(n.mp.ID, ph, nil)
1209 } else {
1210 ph = alt
1211 }
1212 b.s.mu.Unlock()
1213
1214 // Initialize n.ph.
1215 n.ph = ph
1216 }
1217 }()
1218
1219 if hit && ph.state >= validKey {
1220 return nil // already valid
1221 } else {
1222 // We'll need to update the package handle. Since this could happen
1223 // concurrently, make a copy.
1224 if hit {
1225 ph = ph.clone() // state < validKey
1226 } else {
1227 ph = &packageHandle{
1228 mp: n.mp,
1229 state: validMetadata,
1230 }
1231 }
1232 }
1233
1234 // Invariant: ph is either
1235 // - a new handle in state validMetadata, or
1236 // - a clone of an existing handle in state validMetadata or validLocalData.
1237
1238 // State transition: validMetadata -> validLocalInputs.
1239 localKeyChanged := false
1240 if ph.state < validLocalData {
1241 prevLocalKey := ph.localKey // may be zero
1242 // No package handle: read and analyze the package syntax.
1243 inputs, err := b.s.typeCheckInputs(ctx, n.mp)
1244 if err != nil {
1245 return err
1246 }
1247 refs, err := b.s.typerefs(ctx, n.mp, inputs.compiledGoFiles)
1248 if err != nil {
1249 return err
1250 }
1251 ph.loadDiagnostics = computeLoadDiagnostics(ctx, b.s, n.mp)
1252 ph.localInputs = inputs
1253
1254 checkOpen:
1255 for _, files := range [][]file.Handle{inputs.goFiles, inputs.compiledGoFiles} {
1256 for _, fh := range files {
1257 if _, ok := fh.(*overlay); ok {
1258 ph.isOpen = true
1259 break checkOpen
1260 }
1261 }
1262 }
1263 if !ph.isOpen {
1264 // ensure we don't hold data for closed packages
1265 ph.pkgData = nil
1266 }
1267 ph.localKey = localPackageKey(inputs)
1268 ph.refs = refs
1269 ph.state = validLocalData
1270 localKeyChanged = ph.localKey != prevLocalKey
1271 }
1272
1273 assert(ph.state == validLocalData, "unexpected handle state")
1274
1275 // State transition: validLocalInputs -> validKey
1276
1277 // Check if any dependencies have actually changed.
1278 depsChanged := true
1279 if ph.depKeys != nil { // ph was previously evaluated
1280 depsChanged = len(ph.depKeys) != len(n.succs)
1281 if !depsChanged {
1282 for id, succ := range n.succs {
1283 oldKey, ok := ph.depKeys[id]
1284 assert(ok, "missing dep")
1285 if oldKey != succ.ph.key {
1286 depsChanged = true
1287 break
1288 }
1289 }
1290 }
1291 }
1292
1293 // Optimization: if the local package information did not change, nor did any
1294 // of the dependencies, we don't need to re-run the reachability algorithm.
1295 //
1296 // Concretely: suppose A -> B -> C -> D, where '->' means "imports". If I
1297 // type in a function body of D, I will probably invalidate types in D that C
1298 // uses, because positions change, and therefore the package key of C will
1299 // change. But B probably doesn't reach any types in D, and therefore the
1300 // package key of B will not change. We still need to re-run the reachability
1301 // algorithm on B to confirm. But if the key of B did not change, we don't
1302 // even need to run the reachability algorithm on A.
1303 if !localKeyChanged && !depsChanged {
1304 ph.state = validKey
1305 }
1306
1307 keyChanged := false
1308 if ph.state < validKey {
1309 prevKey := ph.key
1310
1311 // If we get here, it must be the case that deps have changed, so we must
1312 // run the reachability algorithm.
1313 ph.depKeys = make(map[PackageID]file.Hash)
1314
1315 // See the typerefs package: the reachable set of packages is defined to be
1316 // the set of packages containing syntax that is reachable through the
1317 // symbol reference graph starting at the exported symbols in the
1318 // dependencies of ph.
1319 reachable := b.s.view.pkgIndex.NewSet()
1320 for depID, succ := range n.succs {
1321 ph.depKeys[depID] = succ.ph.key
1322 reachable.Add(succ.idxID)
1323 trefs := b.getTransitiveRefs(succ.mp.ID)
1324 assert(trefs != nil, "nil trefs")
1325 for _, set := range trefs {
1326 reachable.Union(set)
1327 }
1328 }
1329
1330 // Collect reachable nodes.
1331 var reachableNodes []*handleNode
1332 // In the presence of context cancellation, any package may be missing.
1333 // We need all dependencies to produce a key.
1334 reachable.Elems(func(id typerefs.IndexID) {
1335 dh := b.nodes[id]
1336 if dh == nil {
1337 // Previous code reported an error (not a bug) here.
1338 bug.Reportf("missing reachable node for %v", id)
1339 } else {
1340 reachableNodes = append(reachableNodes, dh)
1341 }
1342 })
1343
1344 // Sort for stability.
1345 sort.Slice(reachableNodes, func(i, j int) bool {
1346 return reachableNodes[i].mp.ID < reachableNodes[j].mp.ID
1347 })
1348
1349 // Key is the hash of the local key of this package, and the local key of
1350 // all reachable packages.
1351 depHasher := sha256.New()
1352 depHasher.Write(ph.localKey[:])
1353 reachablePaths := make([]string, len(reachableNodes))
1354 for i, dh := range reachableNodes {
1355 depHasher.Write(dh.ph.localKey[:])
1356 reachablePaths[i] = string(dh.ph.mp.PkgPath)
1357 }
1358 depHasher.Sum(ph.key[:0])
1359 ph.reachable = bloom.NewFilter(reachablePaths)
1360 ph.state = validKey
1361 keyChanged = ph.key != prevKey
1362 }
1363
1364 assert(ph.state == validKey, "unexpected handle state")
1365
1366 // Validate ph.pkgData, upgrading state if the package or its imports are
1367 // still valid.
1368 if ph.pkgData != nil {
1369 pkgData := *ph.pkgData // make a copy
1370 ph.pkgData = &pkgData
1371 ph.state = validPackage
1372 if keyChanged || ph.pkgData.pkg == nil {
1373 ph.pkgData.pkg = nil // ensure we don't hold on to stale packages
1374 ph.state = validImports
1375 }
1376 if depsChanged {
1377 ph.pkgData = nil
1378 ph.state = validKey
1379 }
1380 }
1381
1382 // Postcondition: state >= validKey
1383
1384 return nil
1385 }
1386
1387 // typerefs returns typerefs for the package described by m and cgfs, after
1388 // either computing it or loading it from the file cache.
1389 func (s *Snapshot) typerefs(ctx context.Context, mp *metadata.Package, cgfs []file.Handle) (map[string][]typerefs.Symbol, error) {
1390 imports := make(map[ImportPath]*metadata.Package)
1391 for impPath, id := range mp.DepsByImpPath {
1392 if id != "" {
1393 imports[impPath] = s.Metadata(id)
1394 }
1395 }
1396
1397 data, err := s.typerefData(ctx, mp.ID, imports, cgfs)
1398 if err != nil {
1399 return nil, err
1400 }
1401 classes := typerefs.Decode(s.view.pkgIndex, data)
1402 refs := make(map[string][]typerefs.Symbol)
1403 for _, class := range classes {
1404 for _, decl := range class.Decls {
1405 refs[decl] = class.Refs
1406 }
1407 }
1408 return refs, nil
1409 }
1410
1411 // typerefData retrieves encoded typeref data from the filecache, or computes it on
1412 // a cache miss.
1413 func (s *Snapshot) typerefData(ctx context.Context, id PackageID, imports map[ImportPath]*metadata.Package, cgfs []file.Handle) ([]byte, error) {
1414 key := typerefsKey(id, imports, cgfs)
1415 if data, ok := filecache.GetOrFatal(typerefsKind, key, filecache.Bytes); ok {
1416 return data, nil
1417 }
1418
1419 pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), parsego.Full&^parser.ParseComments, true, cgfs...)
1420 if err != nil {
1421 return nil, err
1422 }
1423 data := typerefs.Encode(pgfs, imports)
1424
1425 // Store the resulting data in the cache.
1426 go func() {
1427 if err := filecache.Set(typerefsKind, key, data); err != nil {
1428 event.Error(ctx, fmt.Sprintf("storing typerefs data for %s", id), err)
1429 }
1430 }()
1431
1432 return data, nil
1433 }
1434
1435 // typerefsKey produces a key for the reference information produced by the
1436 // typerefs package.
1437 func typerefsKey(id PackageID, imports map[ImportPath]*metadata.Package, compiledGoFiles []file.Handle) file.Hash {
1438 hasher := sha256.New()
1439
1440 fmt.Fprintf(hasher, "typerefs: %s\n", id)
1441
1442 for importPath, imp := range moremaps.Sorted(imports) {
1443 // TODO(rfindley): strength reduce the typerefs.Export API to guarantee
1444 // that it only depends on these attributes of dependencies.
1445 fmt.Fprintf(hasher, "import %s %s %s", importPath, imp.ID, imp.Name)
1446 }
1447
1448 fmt.Fprintf(hasher, "compiledGoFiles: %d\n", len(compiledGoFiles))
1449 for _, fh := range compiledGoFiles {
1450 fmt.Fprintln(hasher, fh.Identity())
1451 }
1452
1453 var hash [sha256.Size]byte
1454 hasher.Sum(hash[:0])
1455 return hash
1456 }
1457
1458 // typeCheckInputs contains the inputs of a call to typeCheckImpl, which
1459 // type-checks a package.
1460 //
1461 // Part of the purpose of this type is to keep type checking in-sync with the
1462 // package handle key, by explicitly identifying the inputs to type checking.
1463 type typeCheckInputs struct {
1464 id PackageID
1465
1466 // Used for type checking:
1467 pkgPath PackagePath
1468 name PackageName
1469 goFiles, compiledGoFiles []file.Handle
1470 sizes types.Sizes
1471 depsByImpPath map[ImportPath]PackageID
1472 goVersion string // packages.Module.GoVersion, e.g. "1.18"
1473
1474 // Used for type check diagnostics:
1475 // TODO(rfindley): consider storing less data in gobDiagnostics, and
1476 // interpreting each diagnostic in the context of a fixed set of options.
1477 // Then these fields need not be part of the type checking inputs.
1478 supportsRelatedInformation bool
1479 linkTarget string
1480 viewType ViewType
1481 }
1482
1483 func (s *Snapshot) typeCheckInputs(ctx context.Context, mp *metadata.Package) (*typeCheckInputs, error) {
1484 // Read both lists of files of this package.
1485 //
1486 // Parallelism is not necessary here as the files will have already been
1487 // pre-read at load time.
1488 //
1489 // goFiles aren't presented to the type checker--nor
1490 // are they included in the key, unsoundly--but their
1491 // syntax trees are available from (*pkg).File(URI).
1492 // TODO(adonovan): consider parsing them on demand?
1493 // The need should be rare.
1494 goFiles, err := readFiles(ctx, s, mp.GoFiles)
1495 if err != nil {
1496 return nil, err
1497 }
1498 compiledGoFiles, err := readFiles(ctx, s, mp.CompiledGoFiles)
1499 if err != nil {
1500 return nil, err
1501 }
1502
1503 goVersion := ""
1504 if mp.Module != nil && mp.Module.GoVersion != "" {
1505 goVersion = mp.Module.GoVersion
1506 } else {
1507 // Fall back on the go version implied by the ambient Go command.
1508 goVersion = fmt.Sprintf("1.%d", s.View().GoVersion())
1509 }
1510
1511 return &typeCheckInputs{
1512 id: mp.ID,
1513 pkgPath: mp.PkgPath,
1514 name: mp.Name,
1515 goFiles: goFiles,
1516 compiledGoFiles: compiledGoFiles,
1517 sizes: mp.TypesSizes,
1518 depsByImpPath: mp.DepsByImpPath,
1519 goVersion: goVersion,
1520
1521 supportsRelatedInformation: s.Options().RelatedInformationSupported,
1522 linkTarget: s.Options().LinkTarget,
1523 viewType: s.view.typ,
1524 }, nil
1525 }
1526
1527 // readFiles reads the content of each file URL from the source
1528 // (e.g. snapshot or cache).
1529 func readFiles(ctx context.Context, fs file.Source, uris []protocol.DocumentURI) (_ []file.Handle, err error) {
1530 fhs := make([]file.Handle, len(uris))
1531 for i, uri := range uris {
1532 fhs[i], err = fs.ReadFile(ctx, uri)
1533 if err != nil {
1534 return nil, err
1535 }
1536 }
1537 return fhs, nil
1538 }
1539
1540 // localPackageKey returns a key for local inputs into type-checking, excluding
1541 // dependency information: files, metadata, and configuration.
1542 func localPackageKey(inputs *typeCheckInputs) file.Hash {
1543 hasher := sha256.New()
1544
1545 // In principle, a key must be the hash of an
1546 // unambiguous encoding of all the relevant data.
1547 // If it's ambiguous, we risk collisions.
1548
1549 // package identifiers
1550 fmt.Fprintf(hasher, "package: %s %s %s\n", inputs.id, inputs.name, inputs.pkgPath)
1551
1552 // module Go version
1553 fmt.Fprintf(hasher, "go %s\n", inputs.goVersion)
1554
1555 // import map
1556 for impPath, depID := range moremaps.Sorted(inputs.depsByImpPath) {
1557 fmt.Fprintf(hasher, "import %s %s", impPath, depID)
1558 }
1559
1560 // file names and contents
1561 fmt.Fprintf(hasher, "compiledGoFiles: %d\n", len(inputs.compiledGoFiles))
1562 for _, fh := range inputs.compiledGoFiles {
1563 fmt.Fprintln(hasher, fh.Identity())
1564 }
1565 fmt.Fprintf(hasher, "goFiles: %d\n", len(inputs.goFiles))
1566 for _, fh := range inputs.goFiles {
1567 fmt.Fprintln(hasher, fh.Identity())
1568 }
1569
1570 // types sizes
1571 wordSize := inputs.sizes.Sizeof(types.Typ[types.Int])
1572 maxAlign := inputs.sizes.Alignof(types.NewPointer(types.Typ[types.Int64]))
1573 fmt.Fprintf(hasher, "sizes: %d %d\n", wordSize, maxAlign)
1574
1575 fmt.Fprintf(hasher, "relatedInformation: %t\n", inputs.supportsRelatedInformation)
1576 fmt.Fprintf(hasher, "linkTarget: %s\n", inputs.linkTarget)
1577 fmt.Fprintf(hasher, "viewType: %d\n", inputs.viewType)
1578
1579 var hash [sha256.Size]byte
1580 hasher.Sum(hash[:0])
1581 return hash
1582 }
1583
1584 // checkPackage type checks the parsed source files in compiledGoFiles.
1585 // (The resulting pkg also holds the parsed but not type-checked goFiles.)
1586 // deps holds the future results of type-checking the direct dependencies.
1587 func (b *typeCheckBatch) checkPackage(ctx context.Context, fset *token.FileSet, ph *packageHandle, imports map[PackagePath]*types.Package) (*Package, error) {
1588 inputs := ph.localInputs
1589 ctx, done := event.Start(ctx, "cache.typeCheckBatch.checkPackage", label.Package.Of(string(inputs.id)))
1590 defer done()
1591
1592 pkg := &syntaxPackage{
1593 id: inputs.id,
1594 fset: fset, // must match parse call below
1595 types: types.NewPackage(string(inputs.pkgPath), string(inputs.name)),
1596 typesSizes: inputs.sizes,
1597 typesInfo: &types.Info{
1598 Types: make(map[ast.Expr]types.TypeAndValue),
1599 Defs: make(map[*ast.Ident]types.Object),
1600 Uses: make(map[*ast.Ident]types.Object),
1601 Implicits: make(map[ast.Node]types.Object),
1602 Instances: make(map[*ast.Ident]types.Instance),
1603 Selections: make(map[*ast.SelectorExpr]*types.Selection),
1604 Scopes: make(map[ast.Node]*types.Scope),
1605 FileVersions: make(map[*ast.File]string),
1606 },
1607 }
1608
1609 // Collect parsed files from the type check pass, capturing parse errors from
1610 // compiled files.
1611 var err error
1612 pkg.goFiles, err = b.parseCache.parseFiles(ctx, pkg.fset, parsego.Full, false, inputs.goFiles...)
1613 if err != nil {
1614 return nil, err
1615 }
1616 pkg.compiledGoFiles, err = b.parseCache.parseFiles(ctx, pkg.fset, parsego.Full, false, inputs.compiledGoFiles...)
1617 if err != nil {
1618 return nil, err
1619 }
1620 for _, pgf := range pkg.compiledGoFiles {
1621 if pgf.ParseErr != nil {
1622 pkg.parseErrors = append(pkg.parseErrors, pgf.ParseErr)
1623 }
1624 }
1625
1626 // Use the default type information for the unsafe package.
1627 if inputs.pkgPath == "unsafe" {
1628 // Don't type check Unsafe: it's unnecessary, and doing so exposes a data
1629 // race to Unsafe.completed.
1630 pkg.types = types.Unsafe
1631 } else {
1632
1633 if len(pkg.compiledGoFiles) == 0 {
1634 // No files most likely means go/packages failed.
1635 //
1636 // TODO(rfindley): in the past, we would capture go list errors in this
1637 // case, to present go list errors to the user. However we had no tests for
1638 // this behavior. It is unclear if anything better can be done here.
1639 return nil, fmt.Errorf("no parsed files for package %s", inputs.pkgPath)
1640 }
1641
1642 onError := func(e error) {
1643 pkg.typeErrors = append(pkg.typeErrors, e.(types.Error))
1644 }
1645 cfg := b.typesConfig(ctx, inputs, imports, onError)
1646 check := types.NewChecker(cfg, pkg.fset, pkg.types, pkg.typesInfo)
1647
1648 var files []*ast.File
1649 for _, cgf := range pkg.compiledGoFiles {
1650 files = append(files, cgf.File)
1651 }
1652
1653 // Type checking is expensive, and we may not have encountered cancellations
1654 // via parsing (e.g. if we got nothing but cache hits for parsed files).
1655 if ctx.Err() != nil {
1656 return nil, ctx.Err()
1657 }
1658
1659 // Type checking errors are handled via the config, so ignore them here.
1660 _ = check.Files(files) // 50us-15ms, depending on size of package
1661
1662 // If the context was cancelled, we may have returned a ton of transient
1663 // errors to the type checker. Swallow them.
1664 if ctx.Err() != nil {
1665 return nil, ctx.Err()
1666 }
1667
1668 // Collect imports by package path for the DependencyTypes API.
1669 pkg.importMap = make(map[PackagePath]*types.Package)
1670 var collectDeps func(*types.Package)
1671 collectDeps = func(p *types.Package) {
1672 pkgPath := PackagePath(p.Path())
1673 if _, ok := pkg.importMap[pkgPath]; ok {
1674 return
1675 }
1676 pkg.importMap[pkgPath] = p
1677 for _, imp := range p.Imports() {
1678 collectDeps(imp)
1679 }
1680 }
1681 collectDeps(pkg.types)
1682
1683 // Work around golang/go#61561: interface instances aren't concurrency-safe
1684 // as they are not completed by the type checker.
1685 for _, inst := range pkg.typesInfo.Instances {
1686 if iface, _ := inst.Type.Underlying().(*types.Interface); iface != nil {
1687 iface.Complete()
1688 }
1689 }
1690 }
1691
1692 // Our heuristic for whether to show type checking errors is:
1693 // + If there is a parse error _in the current file_, suppress type
1694 // errors in that file.
1695 // + Otherwise, show type errors even in the presence of parse errors in
1696 // other package files. go/types attempts to suppress follow-on errors
1697 // due to bad syntax, so on balance type checking errors still provide
1698 // a decent signal/noise ratio as long as the file in question parses.
1699
1700 // Track URIs with parse errors so that we can suppress type errors for these
1701 // files.
1702 unparsable := map[protocol.DocumentURI]bool{}
1703 for _, e := range pkg.parseErrors {
1704 diags, err := parseErrorDiagnostics(pkg, e)
1705 if err != nil {
1706 event.Error(ctx, "unable to compute positions for parse errors", err, label.Package.Of(string(inputs.id)))
1707 continue
1708 }
1709 for _, diag := range diags {
1710 unparsable[diag.URI] = true
1711 pkg.diagnostics = append(pkg.diagnostics, diag)
1712 }
1713 }
1714
1715 diags := typeErrorsToDiagnostics(pkg, inputs, pkg.typeErrors)
1716 for _, diag := range diags {
1717 // If the file didn't parse cleanly, it is highly likely that type
1718 // checking errors will be confusing or redundant. But otherwise, type
1719 // checking usually provides a good enough signal to include.
1720 if !unparsable[diag.URI] {
1721 pkg.diagnostics = append(pkg.diagnostics, diag)
1722 }
1723 }
1724
1725 return &Package{ph.mp, ph.loadDiagnostics, pkg}, nil
1726 }
1727
1728 // e.g. "go1" or "go1.2" or "go1.2.3"
1729 var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*(?:\.(0|[1-9][0-9]*)){0,2}$`)
1730
1731 func (b *typeCheckBatch) typesConfig(ctx context.Context, inputs *typeCheckInputs, imports map[PackagePath]*types.Package, onError func(e error)) *types.Config {
1732 cfg := &types.Config{
1733 Sizes: inputs.sizes,
1734 Error: onError,
1735 Importer: importerFunc(func(path string) (*types.Package, error) {
1736 // While all of the import errors could be reported
1737 // based on the metadata before we start type checking,
1738 // reporting them via types.Importer places the errors
1739 // at the correct source location.
1740 id, ok := inputs.depsByImpPath[ImportPath(path)]
1741 if !ok {
1742 // If the import declaration is broken,
1743 // go list may fail to report metadata about it.
1744 // See TestFixImportDecl for an example.
1745 return nil, fmt.Errorf("missing metadata for import of %q", path)
1746 }
1747 depPH := b.getHandle(id)
1748 if depPH == nil {
1749 // e.g. missing metadata for dependencies in buildPackageHandle
1750 return nil, missingPkgError(inputs.id, path, inputs.viewType)
1751 }
1752 if !metadata.IsValidImport(inputs.pkgPath, depPH.mp.PkgPath, inputs.viewType != GoPackagesDriverView) {
1753 return nil, fmt.Errorf("invalid use of internal package %q", path)
1754 }
1755 // For syntax packages, the set of required imports is known and
1756 // precomputed. For import packages (checkPackageForImport), imports are
1757 // constructed lazily, because they may not have been needed if we could
1758 // have imported from export data.
1759 //
1760 // TODO(rfindley): refactor to move this logic to the callsite.
1761 if imports != nil {
1762 imp, ok := imports[depPH.mp.PkgPath]
1763 if !ok {
1764 return nil, fmt.Errorf("missing import %s", id)
1765 }
1766 return imp, nil
1767 }
1768 return b.getImportPackage(ctx, id)
1769 }),
1770 }
1771
1772 if inputs.goVersion != "" {
1773 goVersion := "go" + inputs.goVersion
1774 if validGoVersion(goVersion) {
1775 cfg.GoVersion = goVersion
1776 }
1777 }
1778
1779 // We want to type check cgo code if go/types supports it.
1780 // We passed typecheckCgo to go/packages when we Loaded.
1781 typesinternal.SetUsesCgo(cfg)
1782 return cfg
1783 }
1784
1785 // validGoVersion reports whether goVersion is a valid Go version for go/types.
1786 // types.NewChecker panics if GoVersion is invalid.
1787 //
1788 // Note that, prior to go1.21, go/types required exactly two components to the
1789 // version number. For example, go types would panic with the Go version
1790 // go1.21.1. validGoVersion handles this case when built with go1.20 or earlier.
1791 func validGoVersion(goVersion string) bool {
1792 if !goVersionRx.MatchString(goVersion) {
1793 return false // malformed version string
1794 }
1795
1796 if relVer := releaseVersion(); relVer != "" && versions.Before(versions.Lang(relVer), versions.Lang(goVersion)) {
1797 return false // 'go list' is too new for go/types
1798 }
1799
1800 return true
1801 }
1802
1803 // releaseVersion reports the Go language version used to compile gopls, or ""
1804 // if it cannot be determined.
1805 func releaseVersion() string {
1806 if len(build.Default.ReleaseTags) > 0 {
1807 v := build.Default.ReleaseTags[len(build.Default.ReleaseTags)-1]
1808 var dummy int
1809 if _, err := fmt.Sscanf(v, "go1.%d", &dummy); err == nil {
1810 return v
1811 }
1812 }
1813 return ""
1814 }
1815
1816 // depsErrors creates diagnostics for each metadata error (e.g. import cycle).
1817 // These may be attached to import declarations in the transitive source files
1818 // of pkg, or to 'requires' declarations in the package's go.mod file.
1819 //
1820 // TODO(rfindley): move this to load.go
1821 func depsErrors(ctx context.Context, snapshot *Snapshot, mp *metadata.Package) ([]*Diagnostic, error) {
1822 // Select packages that can't be found, and were imported in non-workspace packages.
1823 // Workspace packages already show their own errors.
1824 var relevantErrors []*packagesinternal.PackageError
1825 for _, depsError := range mp.DepsErrors {
1826 // Up to Go 1.15, the missing package was included in the stack, which
1827 // was presumably a bug. We want the next one up.
1828 directImporterIdx := len(depsError.ImportStack) - 1
1829 if directImporterIdx < 0 {
1830 continue
1831 }
1832
1833 directImporter := depsError.ImportStack[directImporterIdx]
1834 if snapshot.IsWorkspacePackage(PackageID(directImporter)) {
1835 continue
1836 }
1837 relevantErrors = append(relevantErrors, depsError)
1838 }
1839
1840 // Don't build the import index for nothing.
1841 if len(relevantErrors) == 0 {
1842 return nil, nil
1843 }
1844
1845 // Subsequent checks require Go files.
1846 if len(mp.CompiledGoFiles) == 0 {
1847 return nil, nil
1848 }
1849
1850 // Build an index of all imports in the package.
1851 type fileImport struct {
1852 cgf *parsego.File
1853 imp *ast.ImportSpec
1854 }
1855 allImports := map[string][]fileImport{}
1856 for _, uri := range mp.CompiledGoFiles {
1857 pgf, err := parseGoURI(ctx, snapshot, uri, parsego.Header)
1858 if err != nil {
1859 return nil, err
1860 }
1861 fset := tokeninternal.FileSetFor(pgf.Tok)
1862 // TODO(adonovan): modify Imports() to accept a single token.File (cgf.Tok).
1863 for _, group := range astutil.Imports(fset, pgf.File) {
1864 for _, imp := range group {
1865 if imp.Path == nil {
1866 continue
1867 }
1868 path := strings.Trim(imp.Path.Value, `"`)
1869 allImports[path] = append(allImports[path], fileImport{pgf, imp})
1870 }
1871 }
1872 }
1873
1874 // Apply a diagnostic to any import involved in the error, stopping once
1875 // we reach the workspace.
1876 var errors []*Diagnostic
1877 for _, depErr := range relevantErrors {
1878 for _, item := range slices.Backward(depErr.ImportStack) {
1879 if snapshot.IsWorkspacePackage(PackageID(item)) {
1880 break
1881 }
1882
1883 for _, imp := range allImports[item] {
1884 rng, err := imp.cgf.NodeRange(imp.imp)
1885 if err != nil {
1886 return nil, err
1887 }
1888 diag := &Diagnostic{
1889 URI: imp.cgf.URI,
1890 Range: rng,
1891 Severity: protocol.SeverityError,
1892 Source: TypeError,
1893 Message: fmt.Sprintf("error while importing %v: %v", item, depErr.Err),
1894 SuggestedFixes: goGetQuickFixes(mp.Module != nil, imp.cgf.URI, item),
1895 }
1896 if !bundleLazyFixes(diag) {
1897 bug.Reportf("failed to bundle fixes for diagnostic %q", diag.Message)
1898 }
1899 errors = append(errors, diag)
1900 }
1901 }
1902 }
1903
1904 modFile, err := findRootPattern(ctx, mp.CompiledGoFiles[0].Dir(), "go.mod", snapshot)
1905 if err != nil {
1906 return nil, err
1907 }
1908 pm, err := parseModURI(ctx, snapshot, modFile)
1909 if err != nil {
1910 return nil, err
1911 }
1912
1913 // Add a diagnostic to the module that contained the lowest-level import of
1914 // the missing package.
1915 for _, depErr := range relevantErrors {
1916 for _, item := range slices.Backward(depErr.ImportStack) {
1917 mp := snapshot.Metadata(PackageID(item))
1918 if mp == nil || mp.Module == nil {
1919 continue
1920 }
1921 modVer := module.Version{Path: mp.Module.Path, Version: mp.Module.Version}
1922 reference := findModuleReference(pm.File, modVer)
1923 if reference == nil {
1924 continue
1925 }
1926 rng, err := pm.Mapper.OffsetRange(reference.Start.Byte, reference.End.Byte)
1927 if err != nil {
1928 return nil, err
1929 }
1930 diag := &Diagnostic{
1931 URI: pm.URI,
1932 Range: rng,
1933 Severity: protocol.SeverityError,
1934 Source: TypeError,
1935 Message: fmt.Sprintf("error while importing %v: %v", item, depErr.Err),
1936 SuggestedFixes: goGetQuickFixes(true, pm.URI, item),
1937 }
1938 if !bundleLazyFixes(diag) {
1939 bug.Reportf("failed to bundle fixes for diagnostic %q", diag.Message)
1940 }
1941 errors = append(errors, diag)
1942 break
1943 }
1944 }
1945 return errors, nil
1946 }
1947
1948 // missingPkgError returns an error message for a missing package that varies
1949 // based on the user's workspace mode.
1950 func missingPkgError(from PackageID, pkgPath string, viewType ViewType) error {
1951 switch viewType {
1952 case GoModView, GoWorkView:
1953 if metadata.IsCommandLineArguments(from) {
1954 return fmt.Errorf("current file is not included in a workspace module")
1955 } else {
1956 // Previously, we would present the initialization error here.
1957 return fmt.Errorf("no required module provides package %q", pkgPath)
1958 }
1959 case AdHocView:
1960 return fmt.Errorf("cannot find package %q in GOROOT", pkgPath)
1961 case GoPackagesDriverView:
1962 return fmt.Errorf("go/packages driver could not load %q", pkgPath)
1963 case GOPATHView:
1964 return fmt.Errorf("cannot find package %q in GOROOT or GOPATH", pkgPath)
1965 default:
1966 return fmt.Errorf("unable to load package")
1967 }
1968 }
1969
1970 // typeErrorsToDiagnostics translates a slice of types.Errors into a slice of
1971 // Diagnostics.
1972 //
1973 // In addition to simply mapping data such as position information and error
1974 // codes, this function interprets related go/types "continuation" errors as
1975 // protocol.DiagnosticRelatedInformation. Continuation errors are go/types
1976 // errors whose messages starts with "\t". By convention, these errors relate
1977 // to the previous error in the errs slice (such as if they were printed in
1978 // sequence to a terminal).
1979 //
1980 // Fields in typeCheckInputs may affect the resulting diagnostics.
1981 func typeErrorsToDiagnostics(pkg *syntaxPackage, inputs *typeCheckInputs, errs []types.Error) []*Diagnostic {
1982 var result []*Diagnostic
1983
1984 // batch records diagnostics for a set of related types.Errors.
1985 // (related[0] is the primary error.)
1986 batch := func(related []types.Error) {
1987 var diags []*Diagnostic
1988 for i, e := range related {
1989 code, start, end, ok := typesinternal.ErrorCodeStartEnd(e)
1990 if !ok || !start.IsValid() || !end.IsValid() {
1991 start, end = e.Pos, e.Pos
1992 code = 0
1993 }
1994 if !start.IsValid() {
1995 // Type checker errors may be missing position information if they
1996 // relate to synthetic syntax, such as if the file were fixed. In that
1997 // case, we should have a parse error anyway, so skipping the type
1998 // checker error is likely benign.
1999 //
2000 // TODO(golang/go#64335): we should eventually verify that all type
2001 // checked syntax has valid positions, and promote this skip to a bug
2002 // report.
2003 continue
2004 }
2005
2006 // Invariant: both start and end are IsValid.
2007 if !end.IsValid() {
2008 panic("end is invalid")
2009 }
2010
2011 posn := safetoken.StartPosition(e.Fset, start)
2012 if !posn.IsValid() {
2013 // All valid positions produced by the type checker should described by
2014 // its fileset, yet since type checker errors are associated with
2015 // positions in the AST, and AST nodes can overflow the file
2016 // (golang/go#48300), we can't rely on this.
2017 //
2018 // We should fix the parser, but in the meantime type errors are not
2019 // significant if there are parse errors, so we can safely ignore this
2020 // case.
2021 if len(pkg.parseErrors) == 0 {
2022 bug.Reportf("internal error: type checker error %q outside its Fset", e)
2023 }
2024 continue
2025 }
2026 pgf, err := pkg.File(protocol.URIFromPath(posn.Filename))
2027 if err != nil {
2028 // Sometimes type-checker errors refer to positions in other packages,
2029 // such as when a declaration duplicates a dot-imported name.
2030 //
2031 // In these cases, we don't want to report an error in the other
2032 // package (the message would be rather confusing), but we do want to
2033 // report an error in the current package (golang/go#59005).
2034 if i == 0 {
2035 if pkg.hasFixedFiles() {
2036 bug.Reportf("internal error: could not locate file for primary type checker error %v: %v (fixed files)", e, err)
2037 } else {
2038 bug.Reportf("internal error: could not locate file for primary type checker error %v: %v", e, err)
2039 }
2040 }
2041 continue
2042 }
2043
2044 // debugging golang/go#65960
2045 //
2046 // At this point, we know 'start' IsValid, and
2047 // StartPosition(start) worked (with e.Fset).
2048 //
2049 // If the asserted condition is true, 'start'
2050 // is also in range for pgf.Tok, which means
2051 // the PosRange failure must be caused by 'end'.
2052 if pgf.Tok != e.Fset.File(start) {
2053 if pkg.hasFixedFiles() {
2054 bug.Reportf("internal error: inconsistent token.Files for pos (fixed files)")
2055 } else {
2056 bug.Reportf("internal error: inconsistent token.Files for pos")
2057 }
2058 }
2059
2060 if end == start {
2061 // Expand the end position to a more meaningful span.
2062 //
2063 // TODO(adonovan): It is the type checker's responsibility
2064 // to ensure that (start, end) are meaningful; see #71803.
2065 end = typeErrorEndPos(pgf.Tok, pgf.Src, start)
2066
2067 // debugging golang/go#65960
2068 if _, err := safetoken.Offset(pgf.Tok, end); err != nil {
2069 if pkg.hasFixedFiles() {
2070 bug.Reportf("TypeErrorEndPos returned invalid end: %v (fixed files)", err)
2071 } else {
2072 bug.Reportf("TypeErrorEndPos returned invalid end: %v", err)
2073 }
2074 }
2075 } else {
2076 // TODO(adonovan): check File(start)==File(end).
2077
2078 // debugging golang/go#65960
2079 if _, err := safetoken.Offset(pgf.Tok, end); err != nil {
2080 if pkg.hasFixedFiles() {
2081 bug.Reportf("ErrorCodeStartEnd returned invalid end: %v (fixed files)", err)
2082 } else {
2083 bug.Reportf("ErrorCodeStartEnd returned invalid end: %v", err)
2084 }
2085 }
2086 }
2087
2088 rng, err := pgf.Mapper.PosRange(pgf.Tok, start, end)
2089 if err != nil {
2090 bug.Reportf("internal error: could not compute pos to range for %v: %v", e, err)
2091 continue
2092 }
2093 msg := related[0].Msg // primary
2094 if i > 0 {
2095 if inputs.supportsRelatedInformation {
2096 msg += " (see details)"
2097 } else {
2098 msg += fmt.Sprintf(" (this error: %v)", e.Msg)
2099 }
2100 }
2101 diag := &Diagnostic{
2102 URI: pgf.URI,
2103 Range: rng,
2104 Severity: protocol.SeverityError,
2105 Source: TypeError,
2106 Message: msg,
2107 }
2108 if code != 0 {
2109 diag.Code = code.String()
2110 diag.CodeHref = typesCodeHref(inputs.linkTarget, code)
2111 }
2112 if code == typesinternal.UnusedVar || code == typesinternal.UnusedImport {
2113 diag.Tags = append(diag.Tags, protocol.Unnecessary)
2114 }
2115 if match := importErrorRe.FindStringSubmatch(e.Msg); match != nil {
2116 diag.SuggestedFixes = append(diag.SuggestedFixes, goGetQuickFixes(inputs.viewType.usesModules(), pgf.URI, match[1])...)
2117 }
2118 if match := unsupportedFeatureRe.FindStringSubmatch(e.Msg); match != nil {
2119 diag.SuggestedFixes = append(diag.SuggestedFixes, editGoDirectiveQuickFix(inputs.viewType.usesModules(), pgf.URI, match[1])...)
2120 }
2121
2122 // Link up related information. For the primary error, all related errors
2123 // are treated as related information. For secondary errors, only the
2124 // primary is related.
2125 //
2126 // This is because go/types assumes that errors are read top-down, such as
2127 // in the cycle error "A refers to...". The structure of the secondary
2128 // error set likely only makes sense for the primary error.
2129 //
2130 // NOTE: len(diags) == 0 if the primary diagnostic has invalid positions.
2131 // See also golang/go#66731.
2132 if i > 0 && len(diags) > 0 {
2133 primary := diags[0]
2134 primary.Related = append(primary.Related, protocol.DiagnosticRelatedInformation{
2135 Location: diag.URI.Location(diag.Range),
2136 Message: related[i].Msg, // use the unmodified secondary error for related errors.
2137 })
2138 diag.Related = []protocol.DiagnosticRelatedInformation{{
2139 Location: primary.URI.Location(primary.Range),
2140 }}
2141 }
2142 diags = append(diags, diag)
2143 }
2144 result = append(result, diags...)
2145 }
2146
2147 // Process batches of related errors.
2148 for len(errs) > 0 {
2149 related := []types.Error{errs[0]}
2150 for i := 1; i < len(errs); i++ {
2151 spl := errs[i]
2152 if len(spl.Msg) == 0 || spl.Msg[0] != '\t' {
2153 break
2154 }
2155 spl.Msg = spl.Msg[len("\t"):]
2156 related = append(related, spl)
2157 }
2158 batch(related)
2159 errs = errs[len(related):]
2160 }
2161
2162 return result
2163 }
2164
2165 // This heuristic is ill-defined.
2166 func typeErrorEndPos(tokFile *token.File, src []byte, start token.Pos) token.Pos {
2167 // Get the end position for the type error.
2168 offset, err := safetoken.Offset(tokFile, start)
2169 if err != nil || offset > len(src) {
2170 return start
2171 }
2172 src = src[offset:]
2173
2174 // Attempt to find a reasonable end position for the type error.
2175 //
2176 // TODO(rfindley): the heuristic implemented here is unclear. It looks like
2177 // it seeks the end of the primary operand starting at start, but that is not
2178 // quite implemented (for example, given a func literal this heuristic will
2179 // return the range of the func keyword).
2180 //
2181 // We should formalize this heuristic, or deprecate it by finally proposing
2182 // to add end position to all type checker errors.
2183 //
2184 // Nevertheless, ensure that the end position at least spans the current
2185 // token at the cursor (this was golang/go#69505).
2186 end := start
2187 {
2188 var s scanner.Scanner
2189 fset := token.NewFileSet()
2190 f := fset.AddFile("", fset.Base(), len(src))
2191 s.Init(f, src, nil /* no error handler */, scanner.ScanComments)
2192 pos, tok, lit := s.Scan()
2193 if tok != token.SEMICOLON {
2194 if off, err := safetoken.Offset(f, pos); err == nil {
2195 off += len(lit)
2196 src = src[off:]
2197 end += token.Pos(off)
2198 }
2199 }
2200 }
2201
2202 // Look for bytes that might terminate the current operand. See note above:
2203 // this is imprecise.
2204 if width := bytes.IndexAny(src, " \n,():;[]+-*/"); width > 0 {
2205 end += token.Pos(width)
2206 }
2207 return end
2208 }
2209
2210 // An importFunc is an implementation of the single-method
2211 // types.Importer interface based on a function value.
2212 type importerFunc func(path string) (*types.Package, error)
2213
2214 func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }