Debian Codegraph @

gopls/internal/cache/load.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 "errors"
11 "fmt"
12 "go/types"
13 "path/filepath"
14 "slices"
15 "sort"
16 "strings"
17 "sync/atomic"
18 "time"
19
20 "golang.org/x/tools/go/packages"
21 "golang.org/x/tools/gopls/internal/cache/metadata"
22 "golang.org/x/tools/gopls/internal/file"
23 "golang.org/x/tools/gopls/internal/label"
24 "golang.org/x/tools/gopls/internal/protocol"
25 "golang.org/x/tools/gopls/internal/util/bug"
26 "golang.org/x/tools/gopls/internal/util/immutable"
27 "golang.org/x/tools/gopls/internal/util/pathutil"
28 "golang.org/x/tools/internal/event"
29 "golang.org/x/tools/internal/packagesinternal"
30 "golang.org/x/tools/internal/typesinternal"
31 )
32
33 var loadID uint64 // atomic identifier for loads
34
35 // errNoPackages indicates that a load query matched no packages.
36 var errNoPackages = errors.New("no packages returned")
37
38 // load calls packages.Load for the given scopes, updating package metadata,
39 // import graph, and mapped files with the result.
40 //
41 // The resulting error may wrap the moduleErrorMap error type, representing
42 // errors associated with specific modules.
43 //
44 // If scopes contains a file scope there must be exactly one scope.
45 func (s *Snapshot) load(ctx context.Context, allowNetwork AllowNetwork, scopes ...loadScope) (err error) {
46 if ctx.Err() != nil {
47 // Check context cancellation before incrementing id below: a load on a
48 // cancelled context should be a no-op.
49 return ctx.Err()
50 }
51 id := atomic.AddUint64(&loadID, 1)
52 eventName := fmt.Sprintf("go/packages.Load #%d", id) // unique name for logging
53
54 var query []string
55 var standalone bool // whether this is a load of a standalone file
56
57 // Keep track of module query -> module path so that we can later correlate query
58 // errors with errors.
59 moduleQueries := make(map[string]string)
60
61 for _, scope := range scopes {
62 switch scope := scope.(type) {
63 case packageLoadScope:
64 // The only time we pass package paths is when we're doing a
65 // partial workspace load. In those cases, the paths came back from
66 // go list and should already be GOPATH-vendorized when appropriate.
67 query = append(query, string(scope))
68
69 case fileLoadScope:
70 // Given multiple scopes, the resulting load might contain inaccurate
71 // information. For example go/packages returns at most one command-line
72 // arguments package, and does not handle a combination of standalone
73 // files and packages.
74 uri := protocol.DocumentURI(scope)
75 if len(scopes) > 1 {
76 panic(fmt.Sprintf("internal error: load called with multiple scopes when a file scope is present (file: %s)", uri))
77 }
78 fh, err := s.ReadFile(ctx, uri)
79 if err != nil || fh == nil || s.FileKind(fh) != file.Go {
80 // Don't try to load a file that doesn't exist, or isn't a go file.
81 continue
82 }
83 contents, err := fh.Content()
84 if err != nil {
85 continue
86 }
87 if isStandaloneFile(contents, s.Options().StandaloneTags) {
88 standalone = true
89 query = append(query, uri.Path())
90 } else {
91 query = append(query, fmt.Sprintf("file=%s", uri.Path()))
92 }
93
94 case moduleLoadScope:
95 modQuery := fmt.Sprintf("%s%c...", scope.dir, filepath.Separator)
96 query = append(query, modQuery)
97 moduleQueries[modQuery] = scope.modulePath
98
99 case viewLoadScope:
100 // If we are outside of GOPATH, a module, or some other known
101 // build system, don't load subdirectories.
102 if s.view.typ == AdHocView {
103 query = append(query, "./")
104 } else {
105 query = append(query, "./...")
106 }
107
108 default:
109 panic(fmt.Sprintf("unknown scope type %T", scope))
110 }
111 }
112 if len(query) == 0 {
113 return nil
114 }
115 sort.Strings(query) // for determinism
116
117 ctx, done := event.Start(ctx, "cache.snapshot.load", label.Query.Of(query))
118 defer done()
119
120 startTime := time.Now()
121
122 // Set a last resort deadline on packages.Load since it calls the go
123 // command, which may hang indefinitely if it has a bug. golang/go#42132
124 // and golang/go#42255 have more context.
125 ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
126 defer cancel()
127
128 cfg := s.config(ctx, allowNetwork)
129 pkgs, err := packages.Load(cfg, query...)
130
131 // If the context was canceled, return early. Otherwise, we might be
132 // type-checking an incomplete result. Check the context directly,
133 // because go/packages adds extra information to the error.
134 if ctx.Err() != nil {
135 return ctx.Err()
136 }
137
138 // This log message is sought for by TestReloadOnlyOnce.
139 {
140 lbls := append(s.Labels(),
141 label.Query.Of(query),
142 label.PackageCount.Of(len(pkgs)),
143 label.Duration.Of(time.Since(startTime)),
144 )
145 if err != nil {
146 event.Error(ctx, eventName, err, lbls...)
147 } else {
148 event.Log(ctx, eventName, lbls...)
149 }
150 }
151
152 if err != nil {
153 return fmt.Errorf("packages.Load error: %w", err)
154 }
155
156 if standalone {
157 // Handle standalone package result.
158 //
159 // In general, this should just be a single "command-line-arguments"
160 // package containing the requested file. However, if the file is a test
161 // file, go/packages may return test variants of the command-line-arguments
162 // package. We don't support this; theoretically we could, but it seems
163 // unnecessarily complicated.
164 //
165 // It's possible that we get no packages here, for example if the file is a
166 // cgo file and cgo is not enabled.
167 var standalonePkg *packages.Package
168 for _, pkg := range pkgs {
169 if pkg.ID == "command-line-arguments" {
170 if standalonePkg != nil {
171 return fmt.Errorf("go/packages returned multiple standalone packages")
172 }
173 standalonePkg = pkg
174 } else if pkg.ForTest == "" && !strings.HasSuffix(pkg.ID, ".test") {
175 return fmt.Errorf("go/packages returned unexpected package %q for standalone file", pkg.ID)
176 }
177 }
178 if standalonePkg == nil {
179 return fmt.Errorf("go/packages failed to return non-test standalone package")
180 }
181 if len(standalonePkg.CompiledGoFiles) > 0 {
182 pkgs = []*packages.Package{standalonePkg}
183 } else {
184 pkgs = nil
185 }
186 }
187
188 if len(pkgs) == 0 {
189 return fmt.Errorf("packages.Load error: %w", errNoPackages)
190 }
191
192 moduleErrs := make(map[string][]packages.Error) // module path -> errors
193 filterFunc := s.view.filterFunc()
194 newMetadata := make(map[PackageID]*metadata.Package)
195 for _, pkg := range pkgs {
196 if pkg.Module != nil && strings.Contains(pkg.Module.Path, "command-line-arguments") {
197 // golang/go#61543: modules containing "command-line-arguments" cause
198 // gopls to get all sorts of confused, because anything containing the
199 // string "command-line-arguments" is treated as a script. And yes, this
200 // happened in practice! (https://xkcd.com/327). Rather than try to work
201 // around this very rare edge case, just fail loudly.
202 return fmt.Errorf(`load failed: module name in %s contains "command-line-arguments", which is disallowed`, pkg.Module.GoMod)
203 }
204 // The Go command returns synthetic list results for module queries that
205 // encountered module errors.
206 //
207 // For example, given a module path a.mod, we'll query for "a.mod/..." and
208 // the go command will return a package named "a.mod/..." holding this
209 // error. Save it for later interpretation.
210 //
211 // See golang/go#50862 for more details.
212 if mod := moduleQueries[pkg.PkgPath]; mod != "" { // a synthetic result for the unloadable module
213 if len(pkg.Errors) > 0 {
214 moduleErrs[mod] = pkg.Errors
215 }
216 continue
217 }
218
219 if s.Options().VerboseOutput {
220 event.Log(ctx, eventName, append(
221 s.Labels(),
222 label.Package.Of(pkg.ID),
223 label.Files.Of(pkg.CompiledGoFiles))...)
224 }
225
226 // Ignore packages with no sources, since we will never be able to
227 // correctly invalidate that metadata.
228 if len(pkg.GoFiles) == 0 && len(pkg.CompiledGoFiles) == 0 {
229 continue
230 }
231 // Special case for the builtin package, as it has no dependencies.
232 if pkg.PkgPath == "builtin" {
233 if len(pkg.GoFiles) != 1 {
234 return fmt.Errorf("only expected 1 file for builtin, got %v", len(pkg.GoFiles))
235 }
236 s.setBuiltin(pkg.GoFiles[0])
237 continue
238 }
239 if pkg.ForTest == "builtin" {
240 // We don't care about test variants of builtin. This caused test
241 // failures in https://go.dev/cl/620196, when a test file was added to
242 // builtin.
243 continue
244 }
245 // Skip test main packages.
246 if isTestMain(pkg, s.view.folder.Env.GOCACHE) {
247 continue
248 }
249 // Skip filtered packages. They may be added anyway if they're
250 // dependencies of non-filtered packages.
251 //
252 // TODO(rfindley): why exclude metadata arbitrarily here? It should be safe
253 // to capture all metadata.
254 // TODO(rfindley): what about compiled go files?
255 if allFilesExcluded(pkg.GoFiles, filterFunc) {
256 continue
257 }
258 buildMetadata(newMetadata, cfg.Dir, standalone, pkg)
259 }
260
261 s.mu.Lock()
262
263 // Assert the invariant s.packages.Get(id).m == s.meta.metadata[id].
264 for id, ph := range s.packages.All() {
265 if s.meta.Packages[id] != ph.mp {
266 panic("inconsistent metadata")
267 }
268 }
269
270 // Compute the minimal metadata updates (for Clone)
271 // required to preserve the above invariant.
272 var files []protocol.DocumentURI // files to preload
273 seenFiles := make(map[protocol.DocumentURI]bool)
274 updates := make(map[PackageID]*metadata.Package)
275 for _, mp := range newMetadata {
276 if existing := s.meta.Packages[mp.ID]; existing == nil {
277 // Record any new files we should pre-load.
278 for _, uri := range mp.CompiledGoFiles {
279 if !seenFiles[uri] {
280 seenFiles[uri] = true
281 files = append(files, uri)
282 }
283 }
284 updates[mp.ID] = mp
285 s.shouldLoad.Delete(mp.ID)
286 }
287 }
288
289 if s.Options().VerboseOutput {
290 event.Log(ctx, fmt.Sprintf("%s: updating metadata for %d packages", eventName, len(updates)))
291 }
292
293 meta := s.meta.Update(updates)
294 workspacePackages := computeWorkspacePackagesLocked(ctx, s, meta)
295 s.meta = meta
296 s.workspacePackages = workspacePackages
297
298 s.mu.Unlock()
299
300 // Opt: preLoad files in parallel.
301 //
302 // Requesting files in batch optimizes the underlying filesystem reads.
303 // However, this is also currently necessary for correctness: populating all
304 // files in the snapshot is necessary for certain operations that rely on the
305 // completeness of the file map, e.g. computing the set of directories to
306 // watch.
307 //
308 // TODO(rfindley, golang/go#57558): determine the set of directories based on
309 // loaded packages, so that reading files here is not necessary for
310 // correctness.
311 s.preloadFiles(ctx, files)
312
313 if len(moduleErrs) > 0 {
314 return &moduleErrorMap{moduleErrs}
315 }
316
317 return nil
318 }
319
320 type moduleErrorMap struct {
321 errs map[string][]packages.Error // module path -> errors
322 }
323
324 func (m *moduleErrorMap) Error() string {
325 var paths []string // sort for stability
326 for path, errs := range m.errs {
327 if len(errs) > 0 { // should always be true, but be cautious
328 paths = append(paths, path)
329 }
330 }
331 sort.Strings(paths)
332
333 var buf bytes.Buffer
334 fmt.Fprintf(&buf, "%d modules have errors:\n", len(paths))
335 for _, path := range paths {
336 fmt.Fprintf(&buf, "\t%s:%s\n", path, m.errs[path][0].Msg)
337 }
338
339 return buf.String()
340 }
341
342 // config returns the configuration used for the snapshot's interaction with
343 // the go/packages API. It uses the given working directory.
344 //
345 // TODO(rstambler): go/packages requires that we do not provide overlays for
346 // multiple modules in one config, so buildOverlay needs to filter overlays by
347 // module.
348 // TODO(rfindley): ^^ is this still true?
349 func (s *Snapshot) config(ctx context.Context, allowNetwork AllowNetwork) *packages.Config {
350 cfg := &packages.Config{
351 Context: ctx,
352 Dir: s.view.root.Path(),
353 Env: s.view.Env(),
354 BuildFlags: slices.Clone(s.view.folder.Options.BuildFlags),
355 Mode: packages.NeedName |
356 packages.NeedFiles |
357 packages.NeedCompiledGoFiles |
358 packages.NeedImports |
359 packages.NeedDeps |
360 packages.NeedTypesSizes |
361 packages.NeedModule |
362 packages.NeedEmbedFiles |
363 packages.LoadMode(packagesinternal.DepsErrors) |
364 packages.NeedForTest,
365 Fset: nil, // we do our own parsing
366 Overlay: s.buildOverlays(),
367 Logf: func(format string, args ...any) {
368 if s.view.folder.Options.VerboseOutput {
369 event.Log(ctx, fmt.Sprintf(format, args...))
370 }
371 },
372 Tests: true,
373 }
374 if !allowNetwork {
375 cfg.Env = append(cfg.Env, "GOPROXY=off")
376 }
377 // We want to type check cgo code if go/types supports it.
378 if typesinternal.SetUsesCgo(&types.Config{}) {
379 cfg.Mode |= packages.LoadMode(packagesinternal.TypecheckCgo)
380 }
381 return cfg
382 }
383
384 // buildMetadata populates the updates map with metadata updates to
385 // apply, based on the given pkg. It recurs through pkg.Imports to ensure that
386 // metadata exists for all dependencies.
387 //
388 // Returns the metadata.Package that was built (or which was already present in
389 // updates), or nil if the package could not be built. Notably, the resulting
390 // metadata.Package may have an ID that differs from pkg.ID.
391 func buildMetadata(updates map[PackageID]*metadata.Package, loadDir string, standalone bool, pkg *packages.Package) *metadata.Package {
392 // Allow for multiple ad-hoc packages in the workspace (see #47584).
393 pkgPath := PackagePath(pkg.PkgPath)
394 id := PackageID(pkg.ID)
395
396 if metadata.IsCommandLineArguments(id) {
397 var f string // file to use as disambiguating suffix
398 if len(pkg.GoFiles) > 0 {
399 f = pkg.GoFiles[0]
400
401 // If there are multiple files, we can't use only the first. Note that we
402 // consider GoFiles, rather than CompiledGoFiles, as there can be
403 // multiple CompiledGoFiles in the presence of cgo processing, whereas a
404 // command-line-arguments package should always have exactly one nominal
405 // Go source file. (See golang/go#64557.)
406 if len(pkg.GoFiles) > 1 {
407 bug.Reportf("unexpected files in command-line-arguments package: %v", pkg.GoFiles)
408 return nil
409 }
410 } else if len(pkg.IgnoredFiles) > 0 {
411 // A file=empty.go query results in IgnoredFiles=[empty.go].
412 f = pkg.IgnoredFiles[0]
413 } else {
414 bug.Reportf("command-line-arguments package has neither GoFiles nor IgnoredFiles")
415 return nil
416 }
417 id = PackageID(pkg.ID + f)
418 pkgPath = PackagePath(pkg.PkgPath + f)
419 }
420
421 // Duplicate?
422 if existing, ok := updates[id]; ok {
423 // A package was encountered twice due to shared
424 // subgraphs (common) or cycles (rare). Although "go
425 // list" usually breaks cycles, we don't rely on it.
426 // breakImportCycles in metadataGraph.Clone takes care
427 // of it later.
428 return existing
429 }
430
431 if pkg.TypesSizes == nil {
432 panic(id + ".TypeSizes is nil")
433 }
434
435 // Recreate the metadata rather than reusing it to avoid locking.
436 mp := &metadata.Package{
437 ID: id,
438 PkgPath: pkgPath,
439 Name: PackageName(pkg.Name),
440 ForTest: PackagePath(pkg.ForTest),
441 TypesSizes: pkg.TypesSizes,
442 LoadDir: loadDir,
443 Module: pkg.Module,
444 Errors: pkg.Errors,
445 DepsErrors: packagesinternal.GetDepsErrors(pkg),
446 Standalone: standalone,
447 }
448
449 updates[id] = mp
450
451 copyURIs := func(dst *[]protocol.DocumentURI, src []string) {
452 for _, filename := range src {
453 *dst = append(*dst, protocol.URIFromPath(filename))
454 }
455 }
456 copyURIs(&mp.CompiledGoFiles, pkg.CompiledGoFiles)
457 copyURIs(&mp.GoFiles, pkg.GoFiles)
458 copyURIs(&mp.IgnoredFiles, pkg.IgnoredFiles)
459 copyURIs(&mp.OtherFiles, pkg.OtherFiles)
460
461 depsByImpPath := make(map[ImportPath]PackageID)
462 depsByPkgPath := make(map[PackagePath]PackageID)
463 for importPath, imported := range pkg.Imports {
464 importPath := ImportPath(importPath)
465
466 // It is not an invariant that importPath == imported.PkgPath.
467 // For example, package "net" imports "golang.org/x/net/dns/dnsmessage"
468 // which refers to the package whose ID and PkgPath are both
469 // "vendor/golang.org/x/net/dns/dnsmessage". Notice the ImportMap,
470 // which maps ImportPaths to PackagePaths:
471 //
472 // $ go list -json net vendor/golang.org/x/net/dns/dnsmessage
473 // {
474 // "ImportPath": "net",
475 // "Name": "net",
476 // "Imports": [
477 // "C",
478 // "vendor/golang.org/x/net/dns/dnsmessage",
479 // "vendor/golang.org/x/net/route",
480 // ...
481 // ],
482 // "ImportMap": {
483 // "golang.org/x/net/dns/dnsmessage": "vendor/golang.org/x/net/dns/dnsmessage",
484 // "golang.org/x/net/route": "vendor/golang.org/x/net/route"
485 // },
486 // ...
487 // }
488 // {
489 // "ImportPath": "vendor/golang.org/x/net/dns/dnsmessage",
490 // "Name": "dnsmessage",
491 // ...
492 // }
493 //
494 // (Beware that, for historical reasons, go list uses
495 // the JSON field "ImportPath" for the package's
496 // path--effectively the linker symbol prefix.)
497 //
498 // The example above is slightly special to go list
499 // because it's in the std module. Otherwise,
500 // vendored modules are simply modules whose directory
501 // is vendor/ instead of GOMODCACHE, and the
502 // import path equals the package path.
503 //
504 // But in GOPATH (non-module) mode, it's possible for
505 // package vendoring to cause a non-identity ImportMap,
506 // as in this example:
507 //
508 // $ cd $HOME/src
509 // $ find . -type f
510 // ./b/b.go
511 // ./vendor/example.com/a/a.go
512 // $ cat ./b/b.go
513 // package b
514 // import _ "example.com/a"
515 // $ cat ./vendor/example.com/a/a.go
516 // package a
517 // $ GOPATH=$HOME GO111MODULE=off go list -json ./b | grep -A2 ImportMap
518 // "ImportMap": {
519 // "example.com/a": "vendor/example.com/a"
520 // },
521
522 // Don't remember any imports with significant errors.
523 //
524 // The len=0 condition is a heuristic check for imports of
525 // non-existent packages (for which go/packages will create
526 // an edge to a synthesized node). The heuristic is unsound
527 // because some valid packages have zero files, for example,
528 // a directory containing only the file p_test.go defines an
529 // empty package p.
530 // TODO(adonovan): clarify this. Perhaps go/packages should
531 // report which nodes were synthesized.
532 if importPath != "unsafe" && len(imported.CompiledGoFiles) == 0 {
533 depsByImpPath[importPath] = "" // missing
534 continue
535 }
536
537 // Don't record self-import edges.
538 // (This simplifies metadataGraph's cycle check.)
539 if PackageID(imported.ID) == id {
540 if len(pkg.Errors) == 0 {
541 bug.Reportf("self-import without error in package %s", id)
542 }
543 continue
544 }
545
546 dep := buildMetadata(updates, loadDir, false, imported) // only top level packages can be standalone
547
548 // Don't record edges to packages with no name, as they cause trouble for
549 // the importer (golang/go#60952).
550 //
551 // Also don't record edges to packages whose ID was modified (i.e.
552 // command-line-arguments packages), as encountered in golang/go#66109. In
553 // this case, we could theoretically keep the edge through dep.ID, but
554 // since this import doesn't make any sense in the first place, we instead
555 // choose to consider it invalid.
556 //
557 // However, we do want to insert these packages into the update map
558 // (buildMetadata above), so that we get type-checking diagnostics for the
559 // invalid packages.
560 if dep == nil || dep.ID != PackageID(imported.ID) || imported.Name == "" {
561 depsByImpPath[importPath] = "" // missing
562 continue
563 }
564
565 depsByImpPath[importPath] = PackageID(imported.ID)
566 depsByPkgPath[PackagePath(imported.PkgPath)] = PackageID(imported.ID)
567 }
568 mp.DepsByImpPath = depsByImpPath
569 mp.DepsByPkgPath = depsByPkgPath
570 return mp
571
572 // m.Diagnostics is set later in the loading pass, using
573 // computeLoadDiagnostics.
574 }
575
576 // computeLoadDiagnostics computes and sets m.Diagnostics for the given metadata m.
577 //
578 // It should only be called during package handle construction in buildPackageHandle.
579 func computeLoadDiagnostics(ctx context.Context, snapshot *Snapshot, mp *metadata.Package) []*Diagnostic {
580 var diags []*Diagnostic
581 for _, packagesErr := range mp.Errors {
582 // Filter out parse errors from go list. We'll get them when we
583 // actually parse, and buggy overlay support may generate spurious
584 // errors. (See TestNewModule_Issue38207.)
585 if strings.Contains(packagesErr.Msg, "expected '") {
586 continue
587 }
588 pkgDiags, err := goPackagesErrorDiagnostics(ctx, packagesErr, mp, snapshot)
589 if err != nil {
590 // There are certain cases where the go command returns invalid
591 // positions, so we cannot panic or even bug.Reportf here.
592 event.Error(ctx, "unable to compute positions for list errors", err, label.Package.Of(string(mp.ID)))
593 continue
594 }
595 diags = append(diags, pkgDiags...)
596 }
597
598 // TODO(rfindley): this is buggy: an insignificant change to a modfile
599 // (or an unsaved modfile) could affect the position of deps errors,
600 // without invalidating the package.
601 depsDiags, err := depsErrors(ctx, snapshot, mp)
602 if err != nil {
603 if ctx.Err() == nil {
604 // TODO(rfindley): consider making this a bug.Reportf. depsErrors should
605 // not normally fail.
606 event.Error(ctx, "unable to compute deps errors", err, label.Package.Of(string(mp.ID)))
607 }
608 } else {
609 diags = append(diags, depsDiags...)
610 }
611 return diags
612 }
613
614 // isWorkspacePackageLocked reports whether p is a workspace package for the
615 // snapshot s.
616 //
617 // Workspace packages are packages that we consider the user to be actively
618 // working on. As such, they are re-diagnosed on every keystroke, and searched
619 // for various workspace-wide queries such as references or workspace symbols.
620 //
621 // See the commentary inline for a description of the workspace package
622 // heuristics.
623 //
624 // s.mu must be held while calling this function.
625 //
626 // TODO(rfindley): remove 'meta' from this function signature. Whether or not a
627 // package is a workspace package should depend only on the package, view
628 // definition, and snapshot file source. While useful, the heuristic
629 // "allFilesHaveRealPackages" does not add that much value and is path
630 // dependent as it depends on the timing of loads.
631 func isWorkspacePackageLocked(ctx context.Context, s *Snapshot, meta *metadata.Graph, pkg *metadata.Package) bool {
632 if metadata.IsCommandLineArguments(pkg.ID) {
633 // Ad-hoc command-line-arguments packages aren't workspace packages.
634 // With zero-config gopls (golang/go#57979) they should be very rare, as
635 // they should only arise when the user opens a file outside the workspace
636 // which isn't present in the import graph of a workspace package.
637 //
638 // Considering them as workspace packages tends to be racy, as they don't
639 // deterministically belong to any view.
640 if !pkg.Standalone {
641 return false
642 }
643
644 // If all the files contained in pkg have a real package, we don't need to
645 // keep pkg as a workspace package.
646 if allFilesHaveRealPackages(meta, pkg) {
647 return false
648 }
649
650 // For now, allow open standalone packages (i.e. go:build ignore) to be
651 // workspace packages, but this means they could belong to multiple views.
652 return containsOpenFileLocked(s, pkg)
653 }
654
655 // If a real package is open, consider it to be part of the workspace.
656 //
657 // TODO(rfindley): reconsider this. In golang/go#66145, we saw that even if a
658 // View sees a real package for a file, it doesn't mean that View is able to
659 // cleanly diagnose the package. Yet, we do want to show diagnostics for open
660 // packages outside the workspace. Is there a better way to ensure that only
661 // the 'best' View gets a workspace package for the open file?
662 if containsOpenFileLocked(s, pkg) {
663 return true
664 }
665
666 // Apply filtering logic.
667 //
668 // Workspace packages must contain at least one non-filtered file.
669 filterFunc := s.view.filterFunc()
670 uris := make(map[protocol.DocumentURI]unit) // filtered package URIs
671 for _, uri := range slices.Concat(pkg.CompiledGoFiles, pkg.GoFiles) {
672 if !strings.Contains(string(uri), "/vendor/") && !filterFunc(uri) {
673 uris[uri] = struct{}{}
674 }
675 }
676 if len(uris) == 0 {
677 return false // no non-filtered files
678 }
679
680 // For non-module views (of type GOPATH or AdHoc), or if
681 // expandWorkspaceToModule is unset, workspace packages must be contained in
682 // the workspace folder.
683 //
684 // For module views (of type GoMod or GoWork), packages must in any case be
685 // in a workspace module (enforced below).
686 if !s.view.typ.usesModules() || !s.Options().ExpandWorkspaceToModule {
687 folder := s.view.folder.Dir.Path()
688 inFolder := false
689 for uri := range uris {
690 if pathutil.InDir(folder, uri.Path()) {
691 inFolder = true
692 break
693 }
694 }
695 if !inFolder {
696 return false
697 }
698 }
699
700 // In module mode, a workspace package must be contained in a workspace
701 // module.
702 if s.view.typ.usesModules() {
703 var modURI protocol.DocumentURI
704 if pkg.Module != nil {
705 modURI = protocol.URIFromPath(pkg.Module.GoMod)
706 } else {
707 // golang/go#65816: for std and cmd, Module is nil.
708 // Fall back to an inferior heuristic.
709 if len(pkg.CompiledGoFiles) == 0 {
710 return false // need at least one file to guess the go.mod file
711 }
712 dir := pkg.CompiledGoFiles[0].Dir()
713 var err error
714 modURI, err = findRootPattern(ctx, dir, "go.mod", lockedSnapshot{s})
715 if err != nil || modURI == "" {
716 // err != nil implies context cancellation, in which case the result of
717 // this query does not matter.
718 return false
719 }
720 }
721 _, ok := s.view.workspaceModFiles[modURI]
722 return ok
723 }
724
725 return true // an ad-hoc package or GOPATH package
726 }
727
728 // containsOpenFileLocked reports whether any file referenced by m is open in
729 // the snapshot s.
730 //
731 // s.mu must be held while calling this function.
732 func containsOpenFileLocked(s *Snapshot, mp *metadata.Package) bool {
733 uris := map[protocol.DocumentURI]struct{}{}
734 for _, uri := range mp.CompiledGoFiles {
735 uris[uri] = struct{}{}
736 }
737 for _, uri := range mp.GoFiles {
738 uris[uri] = struct{}{}
739 }
740
741 for uri := range uris {
742 fh, _ := s.files.get(uri)
743 if _, open := fh.(*overlay); open {
744 return true
745 }
746 }
747 return false
748 }
749
750 // computeWorkspacePackagesLocked computes workspace packages in the
751 // snapshot s for the given metadata graph. The result does not
752 // contain intermediate test variants.
753 //
754 // s.mu must be held while calling this function.
755 func computeWorkspacePackagesLocked(ctx context.Context, s *Snapshot, meta *metadata.Graph) immutable.Map[PackageID, PackagePath] {
756 // The provided context is used for reading snapshot files, which can only
757 // fail due to context cancellation. Don't let this happen as it could lead
758 // to inconsistent results.
759 ctx = context.WithoutCancel(ctx)
760 workspacePackages := make(map[PackageID]PackagePath)
761 for _, mp := range meta.Packages {
762 if !isWorkspacePackageLocked(ctx, s, meta, mp) {
763 continue
764 }
765
766 switch {
767 case mp.ForTest == "":
768 // A normal package.
769 workspacePackages[mp.ID] = mp.PkgPath
770 case mp.ForTest == mp.PkgPath, mp.ForTest+"_test" == mp.PkgPath:
771 // The test variant of some workspace package or its x_test.
772 // To load it, we need to load the non-test variant with -test.
773 //
774 // Notably, this excludes intermediate test variants from workspace
775 // packages.
776 assert(!mp.IsIntermediateTestVariant(), "unexpected ITV")
777 workspacePackages[mp.ID] = mp.ForTest
778 }
779 }
780 return immutable.MapOf(workspacePackages)
781 }
782
783 // allFilesHaveRealPackages reports whether all files referenced by m are
784 // contained in a "real" package (not command-line-arguments).
785 //
786 // If m is valid but all "real" packages containing any file are invalid, this
787 // function returns false.
788 //
789 // If m is not a command-line-arguments package, this is trivially true.
790 func allFilesHaveRealPackages(g *metadata.Graph, mp *metadata.Package) bool {
791 n := len(mp.CompiledGoFiles)
792 checkURIs:
793 for _, uri := range slices.Concat(mp.CompiledGoFiles[0:n:n], mp.GoFiles) {
794 for _, pkg := range g.ForFile[uri] {
795 if !metadata.IsCommandLineArguments(pkg.ID) {
796 continue checkURIs
797 }
798 }
799 return false
800 }
801 return true
802 }
803
804 func isTestMain(pkg *packages.Package, gocache string) bool {
805 // Test mains must have an import path that ends with ".test".
806 if !strings.HasSuffix(pkg.PkgPath, ".test") {
807 return false
808 }
809 // Test main packages are always named "main".
810 if pkg.Name != "main" {
811 return false
812 }
813 // Test mains always have exactly one GoFile that is in the build cache.
814 if len(pkg.GoFiles) > 1 {
815 return false
816 }
817 if !pathutil.InDir(gocache, pkg.GoFiles[0]) {
818 return false
819 }
820 return true
821 }