Debian Codegraph @

gopls/internal/cache/view.go

raw symbols SCIP
1 // Copyright 2018 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 is the core of gopls: it is concerned with state
6 // management, dependency analysis, and invalidation; and it holds the
7 // machinery of type checking and modular static analysis. Its
8 // principal types are [Session], [Folder], [View], [Snapshot],
9 // [Cache], and [Package].
10 package cache
11
12 import (
13 "context"
14 "encoding/json"
15 "errors"
16 "fmt"
17 "log"
18 "maps"
19 "os"
20 "os/exec"
21 "path"
22 "path/filepath"
23 "slices"
24 "sort"
25 "strings"
26 "sync"
27 "time"
28
29 "golang.org/x/tools/gopls/internal/cache/typerefs"
30 "golang.org/x/tools/gopls/internal/file"
31 "golang.org/x/tools/gopls/internal/protocol"
32 "golang.org/x/tools/gopls/internal/settings"
33 "golang.org/x/tools/gopls/internal/util/moremaps"
34 "golang.org/x/tools/gopls/internal/util/pathutil"
35 "golang.org/x/tools/gopls/internal/vulncheck"
36 "golang.org/x/tools/internal/event"
37 "golang.org/x/tools/internal/gocommand"
38 "golang.org/x/tools/internal/imports"
39 "golang.org/x/tools/internal/modindex"
40 )
41
42 // A Folder represents an LSP workspace folder, together with its per-folder
43 // options and environment variables that affect build configuration.
44 //
45 // Folders (Name and Dir) are specified by the 'initialize' and subsequent
46 // 'didChangeWorkspaceFolders' requests; their options come from
47 // didChangeConfiguration.
48 //
49 // Folders must not be mutated, as they may be shared across multiple views.
50 type Folder struct {
51 Dir protocol.DocumentURI
52 Name string // decorative name for UI; not necessarily unique
53 Options *settings.Options
54 Env GoEnv
55 }
56
57 // GoEnv holds the environment variables and data from the Go command that is
58 // required for operating on a workspace folder.
59 type GoEnv struct {
60 // Go environment variables. These correspond directly with the Go env var of
61 // the same name.
62 GOOS string
63 GOARCH string
64 GOCACHE string
65 GOMODCACHE string
66 GOPATH string
67 GOPRIVATE string
68 GOFLAGS string
69 GO111MODULE string
70 GOTOOLCHAIN string
71 GOROOT string
72
73 // Go version output.
74 GoVersion int // The X in Go 1.X
75 GoVersionOutput string // complete go version output
76
77 // OS environment variables (notably not go env).
78
79 // ExplicitGOWORK is the GOWORK value set explicitly in the environment. This
80 // may differ from `go env GOWORK` when the GOWORK value is implicit from the
81 // working directory.
82 ExplicitGOWORK string
83
84 // EffectiveGOPACKAGESDRIVER is the effective go/packages driver binary that
85 // will be used. This may be set via GOPACKAGESDRIVER, or may be discovered
86 // via os.LookPath("gopackagesdriver"). The latter functionality is
87 // undocumented and may be removed in the future.
88 //
89 // If GOPACKAGESDRIVER is set to "off", EffectiveGOPACKAGESDRIVER is "".
90 EffectiveGOPACKAGESDRIVER string
91 }
92
93 // View represents a single build for a workspace.
94 //
95 // A View is a logical build (the viewDefinition) along with a state of that
96 // build (the Snapshot).
97 type View struct {
98 id string // a unique string to identify this View in (e.g.) serialized Commands
99
100 *viewDefinition // build configuration
101
102 gocmdRunner *gocommand.Runner // limits go command concurrency
103
104 // baseCtx is the context handed to NewView. This is the parent of all
105 // background contexts created for this view.
106 baseCtx context.Context
107
108 // importsState is for the old imports code
109 importsState *importsState
110
111 // modcacheState is the replacement for importsState, to be used for
112 // goimports operations when the imports source is "gopls".
113 //
114 // It may be nil, if the imports source is not "gopls".
115 modcacheState *modcacheState
116
117 // pkgIndex is an index of package IDs, for efficient storage of typerefs.
118 pkgIndex *typerefs.PackageIndex
119
120 // parseCache holds an LRU cache of recently parsed files.
121 parseCache *parseCache
122
123 // fs is the file source used to populate this view.
124 fs *overlayFS
125
126 // ignoreFilter is used for fast checking of ignored files.
127 ignoreFilter *ignoreFilter
128
129 // cancelInitialWorkspaceLoad can be used to terminate the view's first
130 // attempt at initialization.
131 cancelInitialWorkspaceLoad context.CancelFunc
132
133 snapshotMu sync.Mutex
134 snapshot *Snapshot // latest snapshot; nil after shutdown has been called
135
136 // initialWorkspaceLoad is closed when the first workspace initialization has
137 // completed. If we failed to load, we only retry if the go.mod file changes,
138 // to avoid too many go/packages calls.
139 initialWorkspaceLoad chan struct{}
140
141 // initializationSema is used limit concurrent initialization of snapshots in
142 // the view. We use a channel instead of a mutex to avoid blocking when a
143 // context is canceled.
144 //
145 // This field (along with snapshot.initialized) guards against duplicate
146 // initialization of snapshots. Do not change it without adjusting snapshot
147 // accordingly.
148 initializationSema chan struct{}
149
150 // Document filters are constructed once, in View.filterFunc.
151 filterFuncOnce sync.Once
152 _filterFunc func(protocol.DocumentURI) bool // only accessed by View.filterFunc
153 }
154
155 // definition implements the viewDefiner interface.
156 func (v *View) definition() *viewDefinition { return v.viewDefinition }
157
158 // A viewDefinition is a logical build, i.e. configuration (Folder) along with
159 // a build directory and possibly an environment overlay (e.g. GOWORK=off or
160 // GOOS, GOARCH=...) to affect the build.
161 //
162 // This type is immutable, and compared to see if the View needs to be
163 // reconstructed.
164 //
165 // Note: whenever modifying this type, also modify the equivalence relation
166 // implemented by viewDefinitionsEqual.
167 //
168 // TODO(golang/go#57979): viewDefinition should be sufficient for running
169 // go/packages. Enforce this in the API.
170 type viewDefinition struct {
171 folder *Folder // pointer comparison is OK, as any new Folder creates a new def
172
173 typ ViewType
174 root protocol.DocumentURI // root directory; where to run the Go command
175 gomod protocol.DocumentURI // the nearest go.mod file, or ""
176 gowork protocol.DocumentURI // the nearest go.work file, or ""
177
178 // workspaceModFiles holds the set of mod files active in this snapshot.
179 //
180 // For a go.work workspace, this is the set of workspace modfiles. For a
181 // go.mod workspace, this contains the go.mod file defining the workspace
182 // root, as well as any locally replaced modules (if
183 // "includeReplaceInWorkspace" is set).
184 //
185 // TODO(rfindley): should we just run `go list -m` to compute this set?
186 workspaceModFiles map[protocol.DocumentURI]struct{}
187 workspaceModFilesErr error // error encountered computing workspaceModFiles
188
189 // envOverlay holds additional environment to apply to this viewDefinition.
190 envOverlay map[string]string
191 }
192
193 // definition implements the viewDefiner interface.
194 func (d *viewDefinition) definition() *viewDefinition { return d }
195
196 // Type returns the ViewType type, which determines how go/packages are loaded
197 // for this View.
198 func (d *viewDefinition) Type() ViewType { return d.typ }
199
200 // Root returns the view root, which determines where packages are loaded from.
201 func (d *viewDefinition) Root() protocol.DocumentURI { return d.root }
202
203 // GoMod returns the nearest go.mod file for this view's root, or "".
204 func (d *viewDefinition) GoMod() protocol.DocumentURI { return d.gomod }
205
206 // GoWork returns the nearest go.work file for this view's root, or "".
207 func (d *viewDefinition) GoWork() protocol.DocumentURI { return d.gowork }
208
209 // EnvOverlay returns a new sorted slice of environment variables (in the form
210 // "k=v") for this view definition's env overlay.
211 func (d *viewDefinition) EnvOverlay() []string {
212 var env []string
213 for k, v := range d.envOverlay {
214 env = append(env, fmt.Sprintf("%s=%s", k, v))
215 }
216 sort.Strings(env)
217 return env
218 }
219
220 // GOOS returns the effective GOOS value for this view definition, accounting
221 // for its env overlay.
222 func (d *viewDefinition) GOOS() string {
223 if goos, ok := d.envOverlay["GOOS"]; ok {
224 return goos
225 }
226 return d.folder.Env.GOOS
227 }
228
229 // GOARCH returns the effective GOARCH value for this view definition, accounting
230 // for its env overlay.
231 func (d *viewDefinition) GOARCH() string {
232 if goarch, ok := d.envOverlay["GOARCH"]; ok {
233 return goarch
234 }
235 return d.folder.Env.GOARCH
236 }
237
238 // adjustedGO111MODULE is the value of GO111MODULE to use for loading packages.
239 // It is adjusted to default to "auto" rather than "on", since if we are in
240 // GOPATH and have no module, we may as well allow a GOPATH view to work.
241 func (d viewDefinition) adjustedGO111MODULE() string {
242 if d.folder.Env.GO111MODULE != "" {
243 return d.folder.Env.GO111MODULE
244 }
245 return "auto"
246 }
247
248 // ModFiles returns a new, sorted slice of go.mod files for main modules
249 // enclosed in the snapshot's view and known to the snapshot.
250 func (d viewDefinition) ModFiles() []protocol.DocumentURI {
251 return slices.Sorted(maps.Keys(d.workspaceModFiles))
252 }
253
254 // viewDefinitionsEqual reports whether x and y are equivalent.
255 func viewDefinitionsEqual(x, y *viewDefinition) bool {
256 if (x.workspaceModFilesErr == nil) != (y.workspaceModFilesErr == nil) {
257 return false
258 }
259 if x.workspaceModFilesErr != nil {
260 if x.workspaceModFilesErr.Error() != y.workspaceModFilesErr.Error() {
261 return false
262 }
263 } else if !moremaps.SameKeys(x.workspaceModFiles, y.workspaceModFiles) {
264 return false
265 }
266 if len(x.envOverlay) != len(y.envOverlay) {
267 return false
268 }
269 for i, xv := range x.envOverlay {
270 if xv != y.envOverlay[i] {
271 return false
272 }
273 }
274 return x.folder == y.folder &&
275 x.typ == y.typ &&
276 x.root == y.root &&
277 x.gomod == y.gomod &&
278 x.gowork == y.gowork
279 }
280
281 // A ViewType describes how we load package information for a view.
282 //
283 // This is used for constructing the go/packages.Load query, and for
284 // interpreting missing packages, imports, or errors.
285 //
286 // See the documentation for individual ViewType values for details.
287 type ViewType int
288
289 const (
290 // GoPackagesDriverView is a view with a non-empty GOPACKAGESDRIVER
291 // environment variable.
292 //
293 // Load: ./... from the workspace folder.
294 GoPackagesDriverView ViewType = iota
295
296 // GOPATHView is a view in GOPATH mode.
297 //
298 // I.e. in GOPATH, with GO111MODULE=off, or GO111MODULE=auto with no
299 // go.mod file.
300 //
301 // Load: ./... from the workspace folder.
302 GOPATHView
303
304 // GoModView is a view in module mode with a single Go module.
305 //
306 // Load: <modulePath>/... from the module root.
307 GoModView
308
309 // GoWorkView is a view in module mode with a go.work file.
310 //
311 // Load: <modulePath>/... from the workspace folder, for each module.
312 GoWorkView
313
314 // An AdHocView is a collection of files in a given directory, not in GOPATH
315 // or a module.
316 //
317 // Load: . from the workspace folder.
318 AdHocView
319 )
320
321 func (t ViewType) String() string {
322 switch t {
323 case GoPackagesDriverView:
324 return "GoPackagesDriver"
325 case GOPATHView:
326 return "GOPATH"
327 case GoModView:
328 return "GoMod"
329 case GoWorkView:
330 return "GoWork"
331 case AdHocView:
332 return "AdHoc"
333 default:
334 return "Unknown"
335 }
336 }
337
338 // usesModules reports whether the view uses Go modules.
339 func (typ ViewType) usesModules() bool {
340 switch typ {
341 case GoModView, GoWorkView:
342 return true
343 default:
344 return false
345 }
346 }
347
348 // ID returns the unique ID of this View.
349 func (v *View) ID() string { return v.id }
350
351 // GoCommandRunner returns the shared gocommand.Runner for this view.
352 func (v *View) GoCommandRunner() *gocommand.Runner {
353 return v.gocmdRunner
354 }
355
356 // Folder returns the folder at the base of this view.
357 func (v *View) Folder() *Folder {
358 return v.folder
359 }
360
361 // Env returns the environment to use for running go commands in this view.
362 func (v *View) Env() []string {
363 return slices.Concat(
364 os.Environ(),
365 v.folder.Options.EnvSlice(),
366 []string{"GO111MODULE=" + v.adjustedGO111MODULE()},
367 v.EnvOverlay(),
368 )
369 }
370
371 // ModcacheIndex returns the module cache index
372 func (v *View) ModcacheIndex() (*modindex.Index, error) {
373 if v.modcacheState == nil {
374 return nil, fmt.Errorf("view %q has no module cache", v.id)
375 }
376 return v.modcacheState.getIndex()
377 }
378
379 // UpdateFolders updates the set of views for the new folders.
380 //
381 // Calling this causes each view to be reinitialized.
382 func (s *Session) UpdateFolders(ctx context.Context, newFolders []*Folder) error {
383 s.viewMu.Lock()
384 defer s.viewMu.Unlock()
385
386 overlays := s.Overlays()
387 var openFiles []protocol.DocumentURI
388 for _, o := range overlays {
389 openFiles = append(openFiles, o.URI())
390 }
391
392 defs, err := selectViewDefs(ctx, s, newFolders, openFiles)
393 if err != nil {
394 return err
395 }
396 var newViews []*View
397 for _, def := range defs {
398 v, _, release := s.createView(ctx, def)
399 release()
400 newViews = append(newViews, v)
401 }
402 for _, v := range s.views {
403 v.shutdown()
404 }
405 s.views = newViews
406 return nil
407 }
408
409 // RunProcessEnvFunc runs fn with the process env for this snapshot's view.
410 // Note: the process env contains cached module and filesystem state.
411 func (s *Snapshot) RunProcessEnvFunc(ctx context.Context, fn func(context.Context, *imports.Options) error) error {
412 return s.view.importsState.runProcessEnvFunc(ctx, s, fn)
413 }
414
415 // separated out from its sole use in locateTemplateFiles for testability
416 func fileHasExtension(path string, suffixes []string) bool {
417 ext := filepath.Ext(path)
418 if ext != "" && ext[0] == '.' {
419 ext = ext[1:]
420 }
421 for _, s := range suffixes {
422 if s != "" && ext == s {
423 return true
424 }
425 }
426 return false
427 }
428
429 // locateTemplateFiles ensures that the snapshot has mapped template files
430 // within the workspace folder.
431 func (s *Snapshot) locateTemplateFiles(ctx context.Context) {
432 suffixes := s.Options().TemplateExtensions
433 if len(suffixes) == 0 {
434 return
435 }
436
437 searched := 0
438 filterFunc := s.view.filterFunc()
439 err := filepath.WalkDir(s.view.folder.Dir.Path(), func(path string, entry os.DirEntry, err error) error {
440 if err != nil {
441 return err
442 }
443 if entry.IsDir() {
444 return nil
445 }
446 if fileLimit > 0 && searched > fileLimit {
447 return errExhausted
448 }
449 searched++
450 if !fileHasExtension(path, suffixes) {
451 return nil
452 }
453 uri := protocol.URIFromPath(path)
454 if filterFunc(uri) {
455 return nil
456 }
457 // Get the file in order to include it in the snapshot.
458 // TODO(golang/go#57558): it is fundamentally broken to track files in this
459 // way; we may lose them if configuration or layout changes cause a view to
460 // be recreated.
461 //
462 // Furthermore, this operation must ignore errors, including context
463 // cancellation, or risk leaving the snapshot in an undefined state.
464 s.ReadFile(ctx, uri)
465 return nil
466 })
467 if err != nil {
468 event.Error(ctx, "searching for template files failed", err)
469 }
470 }
471
472 // filterFunc returns a func that reports whether uri is filtered by the currently configured
473 // directoryFilters.
474 func (v *View) filterFunc() func(protocol.DocumentURI) bool {
475 v.filterFuncOnce.Do(func() {
476 folderDir := v.folder.Dir.Path()
477 gomodcache := v.folder.Env.GOMODCACHE
478 var filters []string
479 filters = append(filters, v.folder.Options.DirectoryFilters...)
480 if pref, ok := strings.CutPrefix(gomodcache, folderDir); ok {
481 modcacheFilter := "-" + strings.TrimPrefix(filepath.ToSlash(pref), "/")
482 filters = append(filters, modcacheFilter)
483 }
484 pathIncluded := PathIncludeFunc(filters)
485 v._filterFunc = func(uri protocol.DocumentURI) bool {
486 // Only filter relative to the configured root directory.
487 if pathutil.InDir(folderDir, uri.Path()) {
488 return relPathExcludedByFilter(strings.TrimPrefix(uri.Path(), folderDir), pathIncluded)
489 }
490 return false
491 }
492 })
493 return v._filterFunc
494 }
495
496 // shutdown releases resources associated with the view.
497 func (v *View) shutdown() {
498 // Cancel the initial workspace load if it is still running.
499 v.cancelInitialWorkspaceLoad()
500 v.importsState.stopTimer()
501 if v.modcacheState != nil {
502 v.modcacheState.stopTimer()
503 }
504
505 v.snapshotMu.Lock()
506 if v.snapshot != nil {
507 v.snapshot.cancel()
508 v.snapshot.decref()
509 v.snapshot = nil
510 }
511 v.snapshotMu.Unlock()
512 }
513
514 // ScanImports scans the module cache synchronously.
515 // For use in tests.
516 func (v *View) ScanImports() {
517 gomodcache := v.folder.Env.GOMODCACHE
518 dirCache := v.importsState.modCache.dirCache(gomodcache)
519 imports.ScanModuleCache(gomodcache, dirCache, log.Printf)
520 }
521
522 // IgnoredFile reports if a file would be ignored by a `go list` of the whole
523 // workspace.
524 //
525 // While go list ./... skips directories starting with '.', '_', or 'testdata',
526 // gopls may still load them via file queries. Explicitly filter them out.
527 func (s *Snapshot) IgnoredFile(uri protocol.DocumentURI) bool {
528 // Fast path: if uri doesn't contain '.', '_', or 'testdata', it is not
529 // possible that it is ignored.
530 {
531 uriStr := string(uri)
532 if !strings.Contains(uriStr, ".") && !strings.Contains(uriStr, "_") && !strings.Contains(uriStr, "testdata") {
533 return false
534 }
535 }
536
537 return s.view.ignoreFilter.ignored(uri.Path())
538 }
539
540 // An ignoreFilter implements go list's exclusion rules via its 'ignored' method.
541 type ignoreFilter struct {
542 prefixes []string // root dirs, ending in filepath.Separator
543 }
544
545 // newIgnoreFilter returns a new ignoreFilter implementing exclusion rules
546 // relative to the provided directories.
547 func newIgnoreFilter(dirs []string) *ignoreFilter {
548 f := new(ignoreFilter)
549 for _, d := range dirs {
550 f.prefixes = append(f.prefixes, filepath.Clean(d)+string(filepath.Separator))
551 }
552 return f
553 }
554
555 func (f *ignoreFilter) ignored(filename string) bool {
556 for _, prefix := range f.prefixes {
557 if suffix, ok := strings.CutPrefix(filename, prefix); ok {
558 if checkIgnored(suffix) {
559 return true
560 }
561 }
562 }
563 return false
564 }
565
566 // checkIgnored implements go list's exclusion rules.
567 // Quoting “go help list”:
568 //
569 // Directory and file names that begin with "." or "_" are ignored
570 // by the go tool, as are directories named "testdata".
571 func checkIgnored(suffix string) bool {
572 // Note: this could be further optimized by writing a HasSegment helper, a
573 // segment-boundary respecting variant of strings.Contains.
574 for component := range strings.SplitSeq(suffix, string(filepath.Separator)) {
575 if len(component) == 0 {
576 continue
577 }
578 if component[0] == '.' || component[0] == '_' || component == "testdata" {
579 return true
580 }
581 }
582 return false
583 }
584
585 // Snapshot returns the current snapshot for the view, and a
586 // release function that must be called when the Snapshot is
587 // no longer needed.
588 //
589 // The resulting error is non-nil if and only if the view is shut down, in
590 // which case the resulting release function will also be nil.
591 func (v *View) Snapshot() (*Snapshot, func(), error) {
592 v.snapshotMu.Lock()
593 defer v.snapshotMu.Unlock()
594 if v.snapshot == nil {
595 return nil, nil, errors.New("view is shutdown")
596 }
597 return v.snapshot, v.snapshot.Acquire(), nil
598 }
599
600 // initialize loads the metadata (and currently, file contents, due to
601 // golang/go#57558) for the main package query of the View, which depends on
602 // the view type (see ViewType). If s.initialized is already true, initialize
603 // is a no op.
604 //
605 // The first attempt--which populates the first snapshot for a new view--must
606 // be allowed to run to completion without being cancelled.
607 //
608 // Subsequent attempts are triggered by conditions where gopls can't enumerate
609 // specific packages that require reloading, such as a change to a go.mod file.
610 // These attempts may be cancelled, and then retried by a later call.
611 //
612 // Postcondition: if ctx was not cancelled, s.initialized is true, s.initialErr
613 // holds the error resulting from initialization, if any, and s.metadata holds
614 // the resulting metadata graph.
615 func (s *Snapshot) initialize(ctx context.Context, firstAttempt bool) {
616 // Acquire initializationSema, which is
617 // (in effect) a mutex with a timeout.
618 select {
619 case <-ctx.Done():
620 return
621 case s.view.initializationSema <- struct{}{}:
622 }
623
624 defer func() {
625 <-s.view.initializationSema
626 }()
627
628 s.mu.Lock()
629 initialized := s.initialized
630 s.mu.Unlock()
631
632 if initialized {
633 return
634 }
635
636 defer func() {
637 if firstAttempt {
638 close(s.view.initialWorkspaceLoad)
639 }
640 }()
641
642 // TODO(rFindley): we should only locate template files on the first attempt,
643 // or guard it via a different mechanism.
644 s.locateTemplateFiles(ctx)
645
646 // Collect module paths to load by parsing go.mod files. If a module fails to
647 // parse, capture the parsing failure as a critical diagnostic.
648 var scopes []loadScope // scopes to load
649 var modDiagnostics []*Diagnostic // diagnostics for broken go.mod files
650 addError := func(uri protocol.DocumentURI, err error) {
651 modDiagnostics = append(modDiagnostics, &Diagnostic{
652 URI: uri,
653 Severity: protocol.SeverityError,
654 Source: ListError,
655 Message: err.Error(),
656 })
657 }
658
659 if len(s.view.workspaceModFiles) > 0 {
660 for modURI := range s.view.workspaceModFiles {
661 // Verify that the modfile is valid before trying to load it.
662 //
663 // TODO(rfindley): now that we no longer need to parse the modfile in
664 // order to load scope, we could move these diagnostics to a more general
665 // location where we diagnose problems with modfiles or the workspace.
666 //
667 // Be careful not to add context cancellation errors as critical module
668 // errors.
669 fh, err := s.ReadFile(ctx, modURI)
670 if err != nil {
671 if ctx.Err() != nil {
672 return
673 }
674 addError(modURI, err)
675 continue
676 }
677 parsed, err := s.ParseMod(ctx, fh)
678 if err != nil {
679 if ctx.Err() != nil {
680 return
681 }
682 addError(modURI, err)
683 continue
684 }
685 if parsed.File == nil || parsed.File.Module == nil {
686 addError(modURI, fmt.Errorf("no module path for %s", modURI))
687 continue
688 }
689 // Previously, we loaded <modulepath>/... for each module path, but that
690 // is actually incorrect when the pattern may match packages in more than
691 // one module. See golang/go#59458 for more details.
692 scopes = append(scopes, moduleLoadScope{dir: modURI.DirPath(), modulePath: parsed.File.Module.Mod.Path})
693 }
694 } else {
695 scopes = append(scopes, viewLoadScope{})
696 }
697
698 // If we're loading anything, ensure we also load builtin,
699 // since it provides fake definitions (and documentation)
700 // for types like int that are used everywhere.
701 if len(scopes) > 0 {
702 scopes = append(scopes, packageLoadScope("builtin"))
703 }
704 loadErr := s.load(ctx, NetworkOK, scopes...)
705
706 // A failure is retryable if it may have been due to context cancellation,
707 // and this is not the initial workspace load (firstAttempt==true).
708 //
709 // The IWL runs on a detached context with a long (~10m) timeout, so
710 // if the context was canceled we consider loading to have failed
711 // permanently.
712 if loadErr != nil && ctx.Err() != nil && !firstAttempt {
713 return
714 }
715
716 var initialErr *InitializationError
717 switch {
718 case loadErr != nil && ctx.Err() != nil:
719 event.Error(ctx, fmt.Sprintf("initial workspace load: %v", loadErr), loadErr)
720 initialErr = &InitializationError{
721 MainError: loadErr,
722 }
723 case loadErr != nil:
724 event.Error(ctx, "initial workspace load failed", loadErr)
725 extractedDiags := s.extractGoCommandErrors(ctx, loadErr)
726 initialErr = &InitializationError{
727 MainError: loadErr,
728 Diagnostics: moremaps.Group(extractedDiags, byURI),
729 }
730 case s.view.workspaceModFilesErr != nil:
731 initialErr = &InitializationError{
732 MainError: s.view.workspaceModFilesErr,
733 }
734 case len(modDiagnostics) > 0:
735 initialErr = &InitializationError{
736 MainError: errors.New(modDiagnostics[0].Message),
737 }
738 }
739
740 s.mu.Lock()
741 defer s.mu.Unlock()
742
743 s.initialized = true
744 s.initialErr = initialErr
745 }
746
747 // A StateChange describes external state changes that may affect a snapshot.
748 //
749 // By far the most common of these is a change to file state, but a query of
750 // module upgrade information or vulnerabilities also affects gopls' behavior.
751 type StateChange struct {
752 Modifications []file.Modification // if set, the raw modifications originating this change
753 Files map[protocol.DocumentURI]file.Handle
754 ModuleUpgrades map[protocol.DocumentURI]map[string]string
755 Vulns map[protocol.DocumentURI]*vulncheck.Result
756 CompilerOptDetails map[protocol.DocumentURI]bool // package directory -> whether or not we want details
757 }
758
759 // InvalidateView processes the provided state change, invalidating any derived
760 // results that depend on the changed state.
761 //
762 // The resulting snapshot is non-nil, representing the outcome of the state
763 // change. The second result is a function that must be called to release the
764 // snapshot when the snapshot is no longer needed.
765 //
766 // An error is returned if the given view is no longer active in the session.
767 func (s *Session) InvalidateView(ctx context.Context, view *View, changed StateChange) (*Snapshot, func(), error) {
768 s.viewMu.Lock()
769 defer s.viewMu.Unlock()
770
771 if !slices.Contains(s.views, view) {
772 return nil, nil, fmt.Errorf("view is no longer active")
773 }
774 snapshot, release, _ := s.invalidateViewLocked(ctx, view, changed)
775 return snapshot, release, nil
776 }
777
778 // invalidateViewLocked invalidates the content of the given view.
779 // (See [Session.InvalidateView]).
780 //
781 // The resulting bool reports whether the View needs to be re-diagnosed.
782 // (See [Snapshot.clone]).
783 //
784 // s.viewMu must be held while calling this method.
785 func (s *Session) invalidateViewLocked(ctx context.Context, v *View, changed StateChange) (*Snapshot, func(), bool) {
786 // Detach the context so that content invalidation cannot be canceled.
787 ctx = context.WithoutCancel(ctx)
788
789 // This should be the only time we hold the view's snapshot lock for any period of time.
790 v.snapshotMu.Lock()
791 defer v.snapshotMu.Unlock()
792
793 prevSnapshot := v.snapshot
794
795 if prevSnapshot == nil {
796 panic("invalidateContent called after shutdown")
797 }
798
799 // Cancel all still-running previous requests, since they would be
800 // operating on stale data.
801 prevSnapshot.cancel()
802
803 // Do not clone a snapshot until its view has finished initializing.
804 //
805 // TODO(rfindley): shouldn't we do this before canceling?
806 prevSnapshot.AwaitInitialized(ctx)
807
808 var needsDiagnosis bool
809 s.snapshotWG.Add(1)
810 v.snapshot, needsDiagnosis = prevSnapshot.clone(ctx, v.baseCtx, changed, s.snapshotWG.Done)
811
812 // Remove the initial reference created when prevSnapshot was created.
813 prevSnapshot.decref()
814
815 // Return a second lease to the caller.
816 return v.snapshot, v.snapshot.Acquire(), needsDiagnosis
817 }
818
819 // defineView computes the view definition for the provided workspace folder
820 // and URI.
821 //
822 // If forURI is non-empty, this view should be the best view including forURI.
823 // Otherwise, it is the default view for the folder.
824 //
825 // defineView may return an error if the context is cancelled, or the
826 // workspace folder path is invalid.
827 //
828 // Note: keep this function in sync with [RelevantViews].
829 //
830 // TODO(rfindley): we should be able to remove the error return, as
831 // findModules is going away, and all other I/O is memoized.
832 //
833 // TODO(rfindley): pass in a narrower interface for the file.Source
834 // (e.g. fileExists func(DocumentURI) bool) to make clear that this
835 // process depends only on directory information, not file contents.
836 func defineView(ctx context.Context, fs file.Source, folder *Folder, forFile file.Handle) (*viewDefinition, error) {
837 if err := checkPathValid(folder.Dir.Path()); err != nil {
838 return nil, fmt.Errorf("invalid workspace folder path: %w; check that the spelling of the configured workspace folder path agrees with the spelling reported by the operating system", err)
839 }
840 dir := folder.Dir.Path()
841 if forFile != nil {
842 dir = forFile.URI().DirPath()
843 }
844
845 def := new(viewDefinition)
846 def.folder = folder
847
848 if forFile != nil && fileKind(forFile) == file.Go {
849 // If the file has GOOS/GOARCH build constraints that
850 // don't match the folder's environment (which comes from
851 // 'go env' in the folder, plus user options),
852 // add those constraints to the viewDefinition's environment.
853
854 // Content trimming is nontrivial, so do this outside of the loop below.
855 // Keep this in sync with [RelevantViews].
856 path := forFile.URI().Path()
857 if content, err := forFile.Content(); err == nil {
858 // Note the err == nil condition above: by convention a non-existent file
859 // does not have any constraints. See the related note in [RelevantViews]: this
860 // choice of behavior shouldn't actually matter. In this case, we should
861 // only call defineView with Overlays, which always have content.
862 content = trimContentForPortMatch(content)
863 viewPort := port{def.folder.Env.GOOS, def.folder.Env.GOARCH}
864 if !viewPort.matches(path, content) {
865 for _, p := range preferredPorts {
866 if p.matches(path, content) {
867 if def.envOverlay == nil {
868 def.envOverlay = make(map[string]string)
869 }
870 def.envOverlay["GOOS"] = p.GOOS
871 def.envOverlay["GOARCH"] = p.GOARCH
872 break
873 }
874 }
875 }
876 }
877 }
878
879 var err error
880 dirURI := protocol.URIFromPath(dir)
881 goworkFromEnv := false
882 if folder.Env.ExplicitGOWORK != "off" && folder.Env.ExplicitGOWORK != "" {
883 goworkFromEnv = true
884 def.gowork = protocol.URIFromPath(folder.Env.ExplicitGOWORK)
885 } else {
886 def.gowork, err = findRootPattern(ctx, dirURI, "go.work", fs)
887 if err != nil {
888 return nil, err
889 }
890 }
891
892 // When deriving the best view for a given file, we only want to search
893 // up the directory hierarchy for modfiles.
894 def.gomod, err = findRootPattern(ctx, dirURI, "go.mod", fs)
895 if err != nil {
896 return nil, err
897 }
898
899 // Determine how we load and where to load package information for this view
900 //
901 // Specifically, set
902 // - def.typ
903 // - def.root
904 // - def.workspaceModFiles, and
905 // - def.envOverlay.
906
907 // If GOPACKAGESDRIVER is set it takes precedence.
908 if def.folder.Env.EffectiveGOPACKAGESDRIVER != "" {
909 def.typ = GoPackagesDriverView
910 def.root = dirURI
911 return def, nil
912 }
913
914 // From go.dev/ref/mod, module mode is active if GO111MODULE=on, or
915 // GO111MODULE=auto or "" and we are inside a module or have a GOWORK value.
916 // But gopls is less strict, allowing GOPATH mode if GO111MODULE="", and
917 // AdHoc views if no module is found.
918
919 // gomodWorkspace is a helper to compute the correct set of workspace
920 // modfiles for a go.mod file, based on folder options.
921 gomodWorkspace := func() map[protocol.DocumentURI]unit {
922 modFiles := map[protocol.DocumentURI]struct{}{def.gomod: {}}
923 if folder.Options.IncludeReplaceInWorkspace {
924 includingReplace, err := goModModules(ctx, def.gomod, fs)
925 if err == nil {
926 modFiles = includingReplace
927 } else {
928 // If the go.mod file fails to parse, we don't know anything about
929 // replace directives, so fall back to a view of just the root module.
930 }
931 }
932 return modFiles
933 }
934
935 // Prefer a go.work file if it is available and contains the module relevant
936 // to forURI.
937 if def.adjustedGO111MODULE() != "off" && folder.Env.ExplicitGOWORK != "off" && def.gowork != "" {
938 def.typ = GoWorkView
939 if goworkFromEnv {
940 // The go.work file could be anywhere, which can lead to confusing error
941 // messages.
942 def.root = dirURI
943 } else {
944 // The go.work file could be anywhere, which can lead to confusing error
945 def.root = def.gowork.Dir()
946 }
947 def.workspaceModFiles, def.workspaceModFilesErr = goWorkModules(ctx, def.gowork, fs)
948
949 // If forURI is in a module but that module is not
950 // included in the go.work file, use a go.mod view with GOWORK=off.
951 if forFile != nil && def.workspaceModFilesErr == nil && def.gomod != "" {
952 if _, ok := def.workspaceModFiles[def.gomod]; !ok {
953 def.typ = GoModView
954 def.root = def.gomod.Dir()
955 def.workspaceModFiles = gomodWorkspace()
956 if def.envOverlay == nil {
957 def.envOverlay = make(map[string]string)
958 }
959 def.envOverlay["GOWORK"] = "off"
960 }
961 }
962 return def, nil
963 }
964
965 // Otherwise, use the active module, if in module mode.
966 //
967 // Note, we could override GO111MODULE here via envOverlay if we wanted to
968 // support the case where someone opens a module with GO111MODULE=off. But
969 // that is probably not worth worrying about (at this point, folks probably
970 // shouldn't be setting GO111MODULE).
971 if def.adjustedGO111MODULE() != "off" && def.gomod != "" {
972 def.typ = GoModView
973 def.root = def.gomod.Dir()
974 def.workspaceModFiles = gomodWorkspace()
975 return def, nil
976 }
977
978 // Check if the workspace is within any GOPATH directory.
979 inGOPATH := false
980 for _, gp := range filepath.SplitList(folder.Env.GOPATH) {
981 if pathutil.InDir(filepath.Join(gp, "src"), dir) {
982 inGOPATH = true
983 break
984 }
985 }
986 if def.adjustedGO111MODULE() != "on" && inGOPATH {
987 def.typ = GOPATHView
988 def.root = dirURI
989 return def, nil
990 }
991
992 // We're not in a workspace, module, or GOPATH, so have no better choice than
993 // an ad-hoc view.
994 def.typ = AdHocView
995 def.root = dirURI
996 return def, nil
997 }
998
999 // FetchGoEnv queries the environment and Go command to collect environment
1000 // variables necessary for the workspace folder.
1001 func FetchGoEnv(ctx context.Context, folder protocol.DocumentURI, opts *settings.Options) (*GoEnv, error) {
1002 dir := folder.Path()
1003 // All of the go commands invoked here should be fast. No need to share a
1004 // runner with other operations.
1005 runner := new(gocommand.Runner)
1006 inv := gocommand.Invocation{
1007 WorkingDir: dir,
1008 Env: opts.EnvSlice(),
1009 }
1010
1011 var (
1012 env = new(GoEnv)
1013 err error
1014 )
1015 envvars := map[string]*string{
1016 "GOOS": &env.GOOS,
1017 "GOARCH": &env.GOARCH,
1018 "GOCACHE": &env.GOCACHE,
1019 "GOPATH": &env.GOPATH,
1020 "GOPRIVATE": &env.GOPRIVATE,
1021 "GOMODCACHE": &env.GOMODCACHE,
1022 "GOFLAGS": &env.GOFLAGS,
1023 "GO111MODULE": &env.GO111MODULE,
1024 "GOTOOLCHAIN": &env.GOTOOLCHAIN,
1025 "GOROOT": &env.GOROOT,
1026 }
1027 if err := loadGoEnv(ctx, dir, opts.EnvSlice(), runner, envvars); err != nil {
1028 return nil, err
1029 }
1030
1031 env.GoVersion, err = gocommand.GoVersion(ctx, inv, runner)
1032 if err != nil {
1033 return nil, err
1034 }
1035 env.GoVersionOutput, err = gocommand.GoVersionOutput(ctx, inv, runner)
1036 if err != nil {
1037 return nil, err
1038 }
1039
1040 // The value of GOPACKAGESDRIVER is not returned through the go command.
1041 if driver, ok := opts.Env["GOPACKAGESDRIVER"]; ok {
1042 if driver != "off" {
1043 env.EffectiveGOPACKAGESDRIVER = driver
1044 }
1045 } else if driver := os.Getenv("GOPACKAGESDRIVER"); driver != "off" {
1046 env.EffectiveGOPACKAGESDRIVER = driver
1047 // A user may also have a gopackagesdriver binary on their machine, which
1048 // works the same way as setting GOPACKAGESDRIVER.
1049 //
1050 // TODO(rfindley): remove this call to LookPath. We should not support this
1051 // undocumented method of setting GOPACKAGESDRIVER.
1052 if env.EffectiveGOPACKAGESDRIVER == "" {
1053 tool, err := exec.LookPath("gopackagesdriver")
1054 if err == nil && tool != "" {
1055 env.EffectiveGOPACKAGESDRIVER = tool
1056 }
1057 }
1058 }
1059
1060 // While GOWORK is available through the Go command, we want to differentiate
1061 // between an explicit GOWORK value and one which is implicit from the file
1062 // system. The former doesn't change unless the environment changes.
1063 if gowork, ok := opts.Env["GOWORK"]; ok {
1064 env.ExplicitGOWORK = gowork
1065 } else {
1066 env.ExplicitGOWORK = os.Getenv("GOWORK")
1067 }
1068 return env, nil
1069 }
1070
1071 // loadGoEnv loads `go env` values into the provided map, keyed by Go variable
1072 // name.
1073 func loadGoEnv(ctx context.Context, dir string, configEnv []string, runner *gocommand.Runner, vars map[string]*string) error {
1074 // We can save ~200 ms by requesting only the variables we care about.
1075 args := []string{"-json"}
1076 for k := range vars {
1077 args = append(args, k)
1078 }
1079
1080 inv := gocommand.Invocation{
1081 Verb: "env",
1082 Args: args,
1083 Env: configEnv,
1084 WorkingDir: dir,
1085 }
1086 stdout, err := runner.Run(ctx, inv)
1087 if err != nil {
1088 return err
1089 }
1090 envMap := make(map[string]string)
1091 if err := json.Unmarshal(stdout.Bytes(), &envMap); err != nil {
1092 return fmt.Errorf("internal error unmarshaling JSON from 'go env': %w", err)
1093 }
1094 for key, ptr := range vars {
1095 *ptr = envMap[key]
1096 }
1097
1098 return nil
1099 }
1100
1101 // findRootPattern looks for files with the given basename in dir or any parent
1102 // directory of dir, using the provided FileSource. It returns the first match,
1103 // starting from dir and search parents.
1104 //
1105 // The resulting string is either the file path of a matching file with the
1106 // given basename, or "" if none was found.
1107 //
1108 // findRootPattern only returns an error in the case of context cancellation.
1109 func findRootPattern(ctx context.Context, dirURI protocol.DocumentURI, basename string, fs file.Source) (protocol.DocumentURI, error) {
1110 dir := dirURI.Path()
1111 for dir != "" {
1112 target := filepath.Join(dir, basename)
1113 uri := protocol.URIFromPath(target)
1114 fh, err := fs.ReadFile(ctx, uri)
1115 if err != nil {
1116 return "", err // context cancelled
1117 }
1118 if fileExists(fh) {
1119 return uri, nil
1120 }
1121 // Trailing separators must be trimmed, otherwise filepath.Split is a noop.
1122 next, _ := filepath.Split(strings.TrimRight(dir, string(filepath.Separator)))
1123 if next == dir {
1124 break
1125 }
1126 dir = next
1127 }
1128 return "", nil
1129 }
1130
1131 // checkPathValid performs an OS-specific path validity check. The
1132 // implementation varies for filesystems that are case-insensitive
1133 // (e.g. macOS, Windows), and for those that disallow certain file
1134 // names (e.g. path segments ending with a period on Windows, or
1135 // reserved names such as "com"; see
1136 // https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file).
1137 var checkPathValid = defaultCheckPathValid
1138
1139 // CheckPathValid checks whether a directory is suitable as a workspace folder.
1140 func CheckPathValid(dir string) error { return checkPathValid(dir) }
1141
1142 func defaultCheckPathValid(path string) error {
1143 return nil
1144 }
1145
1146 // IsGoPrivatePath reports whether target is a private import path, as identified
1147 // by the GOPRIVATE environment variable.
1148 func (s *Snapshot) IsGoPrivatePath(target string) bool {
1149 return globsMatchPath(s.view.folder.Env.GOPRIVATE, target)
1150 }
1151
1152 // ModuleUpgrades returns known module upgrades for the dependencies of
1153 // modfile.
1154 func (s *Snapshot) ModuleUpgrades(modfile protocol.DocumentURI) map[string]string {
1155 s.mu.Lock()
1156 defer s.mu.Unlock()
1157 upgrades := map[string]string{}
1158 orig, _ := s.moduleUpgrades.Get(modfile)
1159 maps.Copy(upgrades, orig)
1160 return upgrades
1161 }
1162
1163 // MaxGovulncheckResultsAge defines the maximum vulnerability age considered
1164 // valid by gopls.
1165 //
1166 // Mutable for testing.
1167 var MaxGovulncheckResultAge = 1 * time.Hour
1168
1169 // Vulnerabilities returns known vulnerabilities for the given modfile.
1170 //
1171 // Results more than an hour old are excluded.
1172 //
1173 // TODO(suzmue): replace command.Vuln with a different type, maybe
1174 // https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck/govulnchecklib#Summary?
1175 //
1176 // TODO(rfindley): move to snapshot.go
1177 func (s *Snapshot) Vulnerabilities(modfiles ...protocol.DocumentURI) map[protocol.DocumentURI]*vulncheck.Result {
1178 m := make(map[protocol.DocumentURI]*vulncheck.Result)
1179 now := time.Now()
1180
1181 s.mu.Lock()
1182 defer s.mu.Unlock()
1183
1184 if len(modfiles) == 0 { // empty means all modfiles
1185 modfiles = slices.Collect(s.vulns.Keys())
1186 }
1187 for _, modfile := range modfiles {
1188 vuln, _ := s.vulns.Get(modfile)
1189 if vuln != nil && now.Sub(vuln.AsOf) > MaxGovulncheckResultAge {
1190 vuln = nil
1191 }
1192 m[modfile] = vuln
1193 }
1194 return m
1195 }
1196
1197 // GoVersion returns the effective release Go version (the X in go1.X) for this
1198 // view.
1199 func (v *View) GoVersion() int {
1200 return v.folder.Env.GoVersion
1201 }
1202
1203 // GoVersionString returns the effective Go version string for this view.
1204 //
1205 // Unlike [GoVersion], this encodes the minor version and commit hash information.
1206 func (v *View) GoVersionString() string {
1207 return gocommand.ParseGoVersionOutput(v.folder.Env.GoVersionOutput)
1208 }
1209
1210 // GoVersionString is temporarily available from the snapshot.
1211 //
1212 // TODO(rfindley): refactor so that this method is not necessary.
1213 func (s *Snapshot) GoVersionString() string {
1214 return s.view.GoVersionString()
1215 }
1216
1217 // Copied from
1218 // https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/str/path.go;l=58;drc=2910c5b4a01a573ebc97744890a07c1a3122c67a
1219 func globsMatchPath(globs, target string) bool {
1220 for globs != "" {
1221 // Extract next non-empty glob in comma-separated list.
1222 var glob string
1223 if i := strings.Index(globs, ","); i >= 0 {
1224 glob, globs = globs[:i], globs[i+1:]
1225 } else {
1226 glob, globs = globs, ""
1227 }
1228 if glob == "" {
1229 continue
1230 }
1231
1232 // A glob with N+1 path elements (N slashes) needs to be matched
1233 // against the first N+1 path elements of target,
1234 // which end just before the N+1'th slash.
1235 n := strings.Count(glob, "/")
1236 prefix := target
1237 // Walk target, counting slashes, truncating at the N+1'th slash.
1238 for i := range len(target) {
1239 if target[i] == '/' {
1240 if n == 0 {
1241 prefix = target[:i]
1242 break
1243 }
1244 n--
1245 }
1246 }
1247 if n > 0 {
1248 // Not enough prefix elements.
1249 continue
1250 }
1251 matched, _ := path.Match(glob, prefix)
1252 if matched {
1253 return true
1254 }
1255 }
1256 return false
1257 }
1258
1259 // TODO(rfindley): clean up the redundancy of allFilesExcluded,
1260 // pathExcludedByFilterFunc, pathExcludedByFilter, view.filterFunc...
1261 func allFilesExcluded(files []string, filterFunc func(protocol.DocumentURI) bool) bool {
1262 for _, f := range files {
1263 uri := protocol.URIFromPath(f)
1264 if !filterFunc(uri) {
1265 return false
1266 }
1267 }
1268 return true
1269 }
1270
1271 func relPathExcludedByFilter(path string, pathIncluded func(string) bool) bool {
1272 path = strings.TrimPrefix(filepath.ToSlash(path), "/")
1273 return !pathIncluded(path)
1274 }