Debian Codegraph @

gopls/internal/cache/session.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 "context"
9 "errors"
10 "fmt"
11 "maps"
12 "os"
13 "path/filepath"
14 "slices"
15 "strconv"
16 "strings"
17 "sync"
18 "sync/atomic"
19 "time"
20
21 "golang.org/x/tools/gopls/internal/cache/metadata"
22 "golang.org/x/tools/gopls/internal/cache/typerefs"
23 "golang.org/x/tools/gopls/internal/file"
24 "golang.org/x/tools/gopls/internal/label"
25 "golang.org/x/tools/gopls/internal/protocol"
26 "golang.org/x/tools/gopls/internal/util/bug"
27 "golang.org/x/tools/gopls/internal/util/memoize"
28 "golang.org/x/tools/gopls/internal/util/persistent"
29 "golang.org/x/tools/gopls/internal/vulncheck"
30 "golang.org/x/tools/internal/event"
31 "golang.org/x/tools/internal/event/keys"
32 "golang.org/x/tools/internal/gocommand"
33 "golang.org/x/tools/internal/imports"
34 )
35
36 // NewSession creates a new gopls session with the given cache.
37 func NewSession(ctx context.Context, c *Cache) *Session {
38 index := atomic.AddInt64(&sessionIndex, 1)
39 s := &Session{
40 id: strconv.FormatInt(index, 10),
41 cache: c,
42 gocmdRunner: &gocommand.Runner{},
43 overlayFS: newOverlayFS(c),
44 parseCache: newParseCache(1 * time.Minute), // keep recently parsed files for a minute, to optimize typing CPU
45 viewMap: make(map[protocol.DocumentURI]*View),
46 }
47 event.Log(ctx, "New session", KeyCreateSession.Of(s))
48 return s
49 }
50
51 // A Session holds the state (views, file contents, parse cache,
52 // memoized computations) of a gopls server process.
53 //
54 // It implements the file.Source interface.
55 type Session struct {
56 // Unique identifier for this session.
57 id string
58
59 // Immutable attributes shared across views.
60 cache *Cache // shared cache
61 gocmdRunner *gocommand.Runner // limits go command concurrency
62
63 viewMu sync.Mutex
64 views []*View
65 viewMap map[protocol.DocumentURI]*View // file->best view or nil; nil after shutdown; the key must be a clean uri.
66
67 // snapshots is a counting semaphore that records the number
68 // of unreleased snapshots associated with this session.
69 // Shutdown waits for it to fall to zero.
70 snapshotWG sync.WaitGroup
71
72 parseCache *parseCache
73
74 *overlayFS
75 }
76
77 // ID returns the unique identifier for this session on this server.
78 func (s *Session) ID() string { return s.id }
79 func (s *Session) String() string { return s.id }
80
81 // GoCommandRunner returns the gocommand Runner for this session.
82 func (s *Session) GoCommandRunner() *gocommand.Runner {
83 return s.gocmdRunner
84 }
85
86 // Shutdown the session and all views it has created.
87 func (s *Session) Shutdown(ctx context.Context) {
88 var views []*View
89 s.viewMu.Lock()
90 views = append(views, s.views...)
91 s.views = nil
92 s.viewMap = nil
93 s.viewMu.Unlock()
94 for _, view := range views {
95 view.shutdown()
96 }
97 s.parseCache.stop()
98 s.snapshotWG.Wait() // wait for all work on associated snapshots to finish
99 event.Log(ctx, "Shutdown session", KeyShutdownSession.Of(s))
100 }
101
102 // Cache returns the cache that created this session, for debugging only.
103 func (s *Session) Cache() *Cache {
104 return s.cache
105 }
106
107 // TODO(rfindley): is the logic surrounding this error actually necessary?
108 var ErrViewExists = errors.New("view already exists for session")
109
110 // NewView creates a new View, returning it and its first snapshot. If a
111 // non-empty tempWorkspace directory is provided, the View will record a copy
112 // of its gopls workspace module in that directory, so that client tooling
113 // can execute in the same main module. On success it also returns a release
114 // function that must be called when the Snapshot is no longer needed.
115 func (s *Session) NewView(ctx context.Context, folder *Folder) (*View, *Snapshot, func(), error) {
116 s.viewMu.Lock()
117 defer s.viewMu.Unlock()
118
119 if s.viewMap == nil {
120 return nil, nil, nil, fmt.Errorf("session is shut down")
121 }
122
123 // Querying the file system to check whether
124 // two folders denote the same existing directory.
125 if inode1, err := os.Stat(filepath.FromSlash(folder.Dir.Path())); err == nil {
126 for _, view := range s.views {
127 inode2, err := os.Stat(filepath.FromSlash(view.folder.Dir.Path()))
128 if err == nil && os.SameFile(inode1, inode2) {
129 return nil, nil, nil, ErrViewExists
130 }
131 }
132 }
133
134 def, err := defineView(ctx, s, folder, nil)
135 if err != nil {
136 return nil, nil, nil, err
137 }
138 view, snapshot, release := s.createView(ctx, def)
139 s.views = append(s.views, view)
140 s.viewMap[folder.Dir.Clean()] = view
141 return view, snapshot, release, nil
142 }
143
144 // HasView checks whether the uri's view exists.
145 func (s *Session) HasView(uri protocol.DocumentURI) bool {
146 uri = uri.Clean()
147 s.viewMu.Lock()
148 defer s.viewMu.Unlock()
149 _, ok := s.viewMap[uri]
150 return ok
151 }
152
153 // createView creates a new view, with an initial snapshot that retains the
154 // supplied context, detached from events and cancellation.
155 //
156 // The caller is responsible for calling the release function once.
157 func (s *Session) createView(ctx context.Context, def *viewDefinition) (*View, *Snapshot, func()) {
158 index := atomic.AddInt64(&viewIndex, 1)
159
160 // We want a true background context and not a detached context here
161 // the spans need to be unrelated and no tag values should pollute it.
162 baseCtx := event.Detach(context.WithoutCancel(ctx))
163 backgroundCtx, cancel := context.WithCancel(baseCtx)
164
165 // Compute a skip function to use for module cache scanning.
166 //
167 // Note that unlike other filtering operations, we definitely don't want to
168 // exclude the gomodcache here, even if it is contained in the workspace
169 // folder.
170 //
171 // TODO(rfindley): consolidate with relPathExcludedByFilter(Func), Filterer,
172 // View.filterFunc.
173 var skipPath func(string) bool
174 {
175 // Compute a prefix match, respecting segment boundaries, by ensuring
176 // the pattern (dir) has a trailing slash.
177 dirPrefix := strings.TrimSuffix(string(def.folder.Dir), "/") + "/"
178 pathIncluded := PathIncludeFunc(def.folder.Options.DirectoryFilters)
179 skipPath = func(dir string) bool {
180 uri := strings.TrimSuffix(string(protocol.URIFromPath(dir)), "/")
181 // Note that the logic below doesn't handle the case where uri ==
182 // v.folder.Dir, because there is no point in excluding the entire
183 // workspace folder!
184 if rel, ok := strings.CutPrefix(uri, dirPrefix); ok {
185 return !pathIncluded(rel)
186 }
187 return false
188 }
189 }
190
191 var ignoreFilter *ignoreFilter
192 {
193 var dirs []string
194 if len(def.workspaceModFiles) == 0 {
195 for _, entry := range filepath.SplitList(def.folder.Env.GOPATH) {
196 dirs = append(dirs, filepath.Join(entry, "src"))
197 }
198 } else {
199 dirs = append(dirs, def.folder.Env.GOMODCACHE)
200 for m := range def.workspaceModFiles {
201 dirs = append(dirs, m.DirPath())
202 }
203 }
204 ignoreFilter = newIgnoreFilter(dirs)
205 }
206
207 var pe *imports.ProcessEnv
208 {
209 env := make(map[string]string)
210 envSlice := slices.Concat(os.Environ(), def.folder.Options.EnvSlice(), []string{"GO111MODULE=" + def.adjustedGO111MODULE()})
211 for _, kv := range envSlice {
212 if k, v, ok := strings.Cut(kv, "="); ok {
213 env[k] = v
214 }
215 }
216 pe = &imports.ProcessEnv{
217 GocmdRunner: s.gocmdRunner,
218 BuildFlags: slices.Clone(def.folder.Options.BuildFlags),
219 // TODO(rfindley): an old comment said "processEnv operations should not mutate the modfile"
220 // But shouldn't we honor the default behavior of mod vendoring?
221 ModFlag: "readonly",
222 SkipPathInScan: skipPath,
223 Env: env,
224 WorkingDir: def.root.Path(),
225 ModCache: s.cache.modCache.dirCache(def.folder.Env.GOMODCACHE),
226 }
227 if def.folder.Options.VerboseOutput {
228 pe.Logf = func(format string, args ...any) {
229 event.Log(ctx, fmt.Sprintf(format, args...))
230 }
231 }
232 }
233
234 v := &View{
235 id: strconv.FormatInt(index, 10),
236 gocmdRunner: s.gocmdRunner,
237 initialWorkspaceLoad: make(chan struct{}),
238 initializationSema: make(chan struct{}, 1),
239 baseCtx: baseCtx,
240 pkgIndex: typerefs.NewPackageIndex(),
241 parseCache: s.parseCache,
242 ignoreFilter: ignoreFilter,
243 fs: s.overlayFS,
244 viewDefinition: def,
245 importsState: newImportsState(backgroundCtx, s.cache.modCache, pe),
246 modcacheState: newModcacheState(def.folder.Env.GOMODCACHE),
247 }
248
249 s.snapshotWG.Add(1)
250 v.snapshot = &Snapshot{
251 view: v,
252 backgroundCtx: backgroundCtx,
253 cancel: cancel,
254 store: s.cache.store,
255 refcount: 1, // Snapshots are born referenced.
256 done: s.snapshotWG.Done,
257 packages: new(persistent.Map[PackageID, *packageHandle]),
258 fullAnalysisKeys: new(persistent.Map[PackageID, file.Hash]),
259 factyAnalysisKeys: new(persistent.Map[PackageID, file.Hash]),
260 meta: new(metadata.Graph),
261 files: newFileMap(),
262 shouldLoad: new(persistent.Map[PackageID, []PackagePath]),
263 unloadableFiles: new(persistent.Set[protocol.DocumentURI]),
264 parseModHandles: new(persistent.Map[protocol.DocumentURI, *memoize.Promise]),
265 parseWorkHandles: new(persistent.Map[protocol.DocumentURI, *memoize.Promise]),
266 modTidyHandles: new(persistent.Map[protocol.DocumentURI, *memoize.Promise]),
267 modVulnHandles: new(persistent.Map[protocol.DocumentURI, *memoize.Promise]),
268 modWhyHandles: new(persistent.Map[protocol.DocumentURI, *memoize.Promise]),
269 moduleUpgrades: new(persistent.Map[protocol.DocumentURI, map[string]string]),
270 vulns: new(persistent.Map[protocol.DocumentURI, *vulncheck.Result]),
271 }
272
273 // Snapshots must observe all open files, as there are some caching
274 // heuristics that change behavior depending on open files.
275 for _, o := range s.overlayFS.Overlays() {
276 _, _ = v.snapshot.ReadFile(ctx, o.URI())
277 }
278
279 // Record the environment of the newly created view in the log.
280 event.Log(ctx, fmt.Sprintf("Created View (#%s)", v.id),
281 label.Directory.Of(v.folder.Dir.Path()),
282 viewTypeKey.Of(v.typ.String()),
283 rootDirKey.Of(string(v.root)),
284 goVersionKey.Of(strings.TrimRight(v.folder.Env.GoVersionOutput, "\n")),
285 buildFlagsKey.Of(fmt.Sprint(v.folder.Options.BuildFlags)),
286 envKey.Of(fmt.Sprintf("%+v", v.folder.Env)),
287 envOverlayKey.Of(v.EnvOverlay()),
288 )
289
290 // Initialize the view without blocking.
291 initCtx, initCancel := context.WithCancel(context.WithoutCancel(ctx))
292 v.cancelInitialWorkspaceLoad = initCancel
293 snapshot := v.snapshot
294
295 // Pass a second reference to the background goroutine.
296 bgRelease := snapshot.Acquire()
297 go func() {
298 defer bgRelease()
299 snapshot.initialize(initCtx, true)
300 }()
301
302 // Return a third reference to the caller.
303 return v, snapshot, snapshot.Acquire()
304 }
305
306 // These keys are used to log view metadata in createView.
307 var (
308 viewTypeKey = keys.NewString("view_type", "")
309 rootDirKey = keys.NewString("root_dir", "")
310 goVersionKey = keys.NewString("go_version", "")
311 buildFlagsKey = keys.New("build_flags", "")
312 envKey = keys.New("env", "")
313 envOverlayKey = keys.New("env_overlay", "")
314 )
315
316 // RemoveView removes from the session the view rooted at the specified directory.
317 // It reports whether a view of that directory was removed.
318 func (s *Session) RemoveView(ctx context.Context, dir protocol.DocumentURI) bool {
319 s.viewMu.Lock()
320 defer s.viewMu.Unlock()
321
322 if s.viewMap == nil {
323 return false // Session is shutdown.
324 }
325 s.viewMap = make(map[protocol.DocumentURI]*View) // reset view associations
326
327 var newViews []*View
328 for _, view := range s.views {
329 if view.folder.Dir == dir {
330 view.shutdown()
331 } else {
332 newViews = append(newViews, view)
333 }
334 }
335 removed := len(s.views) - len(newViews)
336 if removed != 1 {
337 // This isn't a bug report, because it could be a client-side bug.
338 event.Error(ctx, "removing view", fmt.Errorf("removed %d views, want exactly 1", removed))
339 }
340 s.views = newViews
341 return removed > 0
342 }
343
344 // View returns the view with a matching id, if present.
345 func (s *Session) View(id string) (*View, error) {
346 s.viewMu.Lock()
347 defer s.viewMu.Unlock()
348 for _, view := range s.views {
349 if view.ID() == id {
350 return view, nil
351 }
352 }
353 return nil, fmt.Errorf("no view with ID %q", id)
354 }
355
356 // SnapshotOf returns a Snapshot corresponding to the given URI.
357 //
358 // In the case where the file can be can be associated with a View by
359 // [RelevantViews] (based on directory information alone, without package
360 // metadata), SnapshotOf returns the current Snapshot for that View. Otherwise,
361 // it awaits loading package metadata and returns a Snapshot for the first View
362 // containing a real (=not command-line-arguments) package for the file.
363 //
364 // If that also fails to find a View, SnapshotOf returns a Snapshot for the
365 // first view in s.views that is not shut down (i.e. s.views[0] unless we lose
366 // a race), for determinism in tests and so that we tend to aggregate the
367 // resulting command-line-arguments packages into a single view.
368 //
369 // SnapshotOf returns an error if a failure occurs along the way (most likely due
370 // to context cancellation), or if there are no Views in the Session.
371 //
372 // On success, the caller must call the returned function to release the snapshot.
373 func (s *Session) SnapshotOf(ctx context.Context, uri protocol.DocumentURI) (*Snapshot, func(), error) {
374 uri = uri.Clean()
375 // Fast path: if the uri has a static association with a view, return it.
376 s.viewMu.Lock()
377 v, err := s.viewOfLocked(ctx, uri)
378 s.viewMu.Unlock()
379
380 if err != nil {
381 return nil, nil, err
382 }
383
384 if v != nil {
385 snapshot, release, err := v.Snapshot()
386 if err == nil {
387 return snapshot, release, nil
388 }
389 // View is shut down. Forget this association.
390 s.viewMu.Lock()
391 if s.viewMap[uri] == v {
392 delete(s.viewMap, uri)
393 }
394 s.viewMu.Unlock()
395 }
396
397 // Fall-back: none of the views could be associated with uri based on
398 // directory information alone.
399 //
400 // Don't memoize the view association in viewMap, as it is not static: Views
401 // may change as metadata changes.
402 //
403 // TODO(rfindley): we could perhaps optimize this case by peeking at existing
404 // metadata before awaiting the load (after all, a load only adds metadata).
405 // But that seems potentially tricky, when in the common case no loading
406 // should be required.
407 views := s.Views()
408 for _, v := range views {
409 snapshot, release, err := v.Snapshot()
410 if err != nil {
411 continue // view was shut down
412 }
413 // We don't check the error from awaitLoaded, because a load failure (that
414 // doesn't result from context cancellation) should not prevent us from
415 // continuing to search for the best view.
416 _ = snapshot.awaitLoaded(ctx)
417 g := snapshot.MetadataGraph()
418 if ctx.Err() != nil {
419 release()
420 return nil, nil, ctx.Err()
421 }
422 // Special handling for the builtin file, since it doesn't have packages.
423 if snapshot.IsBuiltin(uri) {
424 return snapshot, release, nil
425 }
426 // Only match this view if it loaded a real package for the file.
427 //
428 // Any view can load a command-line-arguments package; aggregate those into
429 // views[0] below.
430 for _, pkg := range g.ForFile[uri] {
431 if !metadata.IsCommandLineArguments(pkg.ID) || pkg.Standalone {
432 return snapshot, release, nil
433 }
434 }
435 release()
436 }
437
438 for _, v := range views {
439 snapshot, release, err := v.Snapshot()
440 if err == nil {
441 return snapshot, release, nil // first valid snapshot
442 }
443 }
444 return nil, nil, errNoViews
445 }
446
447 // FileOf returns the file for a given URI and its snapshot.
448 // On success, the returned function must be called to release the snapshot.
449 func (s *Session) FileOf(ctx context.Context, uri protocol.DocumentURI) (file.Handle, *Snapshot, func(), error) {
450 snapshot, release, err := s.SnapshotOf(ctx, uri)
451 if err != nil {
452 return nil, nil, nil, err
453 }
454 fh, err := snapshot.ReadFile(ctx, uri)
455 if err != nil {
456 release()
457 return nil, nil, nil, err
458 }
459 return fh, snapshot, release, nil
460 }
461
462 // errNoViews is sought by orphaned file diagnostics, to detect the case where
463 // we have no view containing a file.
464 var errNoViews = errors.New("no views")
465
466 // viewOfLocked evaluates the best view for uri, memoizing its result in
467 // s.viewMap.
468 //
469 // Precondition: caller holds s.viewMu lock; uri must be clean.
470 //
471 // May return (nil, nil) if no best view can be determined.
472 func (s *Session) viewOfLocked(ctx context.Context, uri protocol.DocumentURI) (*View, error) {
473 if s.viewMap == nil {
474 return nil, errors.New("session is shut down")
475 }
476 v, hit := s.viewMap[uri]
477 if !hit {
478 // Cache miss: compute (and memoize) the best view.
479 fh, err := s.ReadFile(ctx, uri)
480 if err != nil {
481 return nil, err
482 }
483 relevantViews, err := RelevantViews(ctx, s, fh.URI(), s.views)
484 if err != nil {
485 return nil, err
486 }
487 v = matchingView(fh, relevantViews)
488 if v == nil && len(relevantViews) > 0 {
489 // If we have relevant views, but none of them matched the file's build
490 // constraints, then we are still better off using one of them here.
491 // Otherwise, logic may fall back to an inferior view, which lacks
492 // relevant module information, leading to misleading diagnostics.
493 // (as in golang/go#60776).
494 v = relevantViews[0]
495 }
496 s.viewMap[uri] = v // may be nil
497 }
498 return v, nil
499 }
500
501 func (s *Session) Views() []*View {
502 s.viewMu.Lock()
503 defer s.viewMu.Unlock()
504 result := make([]*View, len(s.views))
505 copy(result, s.views)
506 return result
507 }
508
509 // selectViewDefs constructs the best set of views covering the provided workspace
510 // folders and open files.
511 //
512 // This implements the zero-config algorithm of golang/go#57979.
513 func selectViewDefs(ctx context.Context, fs file.Source, folders []*Folder, openFiles []protocol.DocumentURI) ([]*viewDefinition, error) {
514 var defs []*viewDefinition
515
516 // First, compute a default view for each workspace folder.
517 // TODO(golang/go#57979): technically, this is path dependent, since
518 // DidChangeWorkspaceFolders could introduce a path-dependent ordering on
519 // folders. We should keep folders sorted, or sort them here.
520 for _, folder := range folders {
521 def, err := defineView(ctx, fs, folder, nil)
522 if err != nil {
523 return nil, err
524 }
525 defs = append(defs, def)
526 }
527
528 // Next, ensure that the set of views covers all open files contained in a
529 // workspace folder.
530 //
531 // We only do this for files contained in a workspace folder, because other
532 // open files are most likely the result of jumping to a definition from a
533 // workspace file; we don't want to create additional views in those cases:
534 // they should be resolved after initialization.
535
536 folderForFile := func(uri protocol.DocumentURI) *Folder {
537 var longest *Folder
538 for _, folder := range folders {
539 // Check that this is a better match than longest, but not through a
540 // vendor directory. Count occurrences of "/vendor/" as a quick check
541 // that the vendor directory is between the folder and the file. Note the
542 // addition of a trailing "/" to handle the odd case where the folder is named
543 // vendor (which I hope is exceedingly rare in any case).
544 //
545 // Vendored packages are, by definition, part of an existing view.
546 if (longest == nil || len(folder.Dir) > len(longest.Dir)) &&
547 folder.Dir.Encloses(uri) &&
548 strings.Count(string(uri), "/vendor/") == strings.Count(string(folder.Dir)+"/", "/vendor/") {
549
550 longest = folder
551 }
552 }
553 return longest
554 }
555
556 checkFiles:
557 for _, uri := range openFiles {
558 folder := folderForFile(uri)
559 if folder == nil || !folder.Options.ZeroConfig {
560 continue // only guess views for open files
561 }
562 fh, err := fs.ReadFile(ctx, uri)
563 if err != nil {
564 return nil, err
565 }
566 relevantViews, err := RelevantViews(ctx, fs, fh.URI(), defs)
567 if err != nil {
568 // We should never call selectViewDefs with a cancellable context, so
569 // this should never fail.
570 return nil, bug.Errorf("failed to find best view for open file: %v", err)
571 }
572 def := matchingView(fh, relevantViews)
573 if def != nil {
574 continue // file covered by an existing view
575 }
576 def, err = defineView(ctx, fs, folder, fh)
577 if err != nil {
578 // e.g. folder path is invalid?
579 return nil, fmt.Errorf("failed to define view for open file: %v", err)
580 }
581 // It need not strictly be the case that the best view for a file is
582 // distinct from other views, as the logic of getViewDefinition and
583 // [RelevantViews] does not align perfectly. This is not necessarily a bug:
584 // there may be files for which we can't construct a valid view.
585 //
586 // Nevertheless, we should not create redundant views.
587 for _, alt := range defs {
588 if viewDefinitionsEqual(alt, def) {
589 continue checkFiles
590 }
591 }
592 defs = append(defs, def)
593 }
594
595 return defs, nil
596 }
597
598 // The viewDefiner interface allows the [RelevantViews] algorithm to operate on both
599 // Views and viewDefinitions.
600 type viewDefiner interface{ definition() *viewDefinition }
601
602 // RelevantViews returns the views that may contain the given URI, or nil if
603 // none exist. A view is "relevant" if, ignoring build constraints, it may have
604 // a workspace package containing uri. Therefore, the definition of relevance
605 // depends on the view type.
606 func RelevantViews[V viewDefiner](ctx context.Context, fs file.Source, uri protocol.DocumentURI, views []V) ([]V, error) {
607 if len(views) == 0 {
608 return nil, nil // avoid the call to findRootPattern
609 }
610 dir := uri.Dir()
611 modURI, err := findRootPattern(ctx, dir, "go.mod", fs)
612 if err != nil {
613 return nil, err
614 }
615
616 // Prefer GoWork > GoMod > GOPATH > GoPackages > AdHoc.
617 var (
618 goPackagesViews []V // prefer longest
619 workViews []V // prefer longest
620 modViews []V // exact match
621 gopathViews []V // prefer longest
622 adHocViews []V // exact match
623 )
624
625 // pushView updates the views slice with the matching view v, using the
626 // heuristic that views with a longer root are preferable. Accordingly,
627 // pushView may be a no op if v's root is shorter than the roots in the views
628 // slice.
629 //
630 // Invariant: the length of all roots in views is the same.
631 pushView := func(views *[]V, v V) {
632 if len(*views) == 0 {
633 *views = []V{v}
634 return
635 }
636 better := func(l, r V) bool {
637 return len(l.definition().root) > len(r.definition().root)
638 }
639 existing := (*views)[0]
640 switch {
641 case better(existing, v):
642 case better(v, existing):
643 *views = []V{v}
644 default:
645 *views = append(*views, v)
646 }
647 }
648
649 for _, view := range views {
650 switch def := view.definition(); def.Type() {
651 case GoPackagesDriverView:
652 if def.root.Encloses(dir) {
653 pushView(&goPackagesViews, view)
654 }
655 case GoWorkView:
656 if _, ok := def.workspaceModFiles[modURI]; ok || uri == def.gowork {
657 pushView(&workViews, view)
658 }
659 case GoModView:
660 if _, ok := def.workspaceModFiles[modURI]; ok {
661 modViews = append(modViews, view)
662 }
663 case GOPATHView:
664 if def.root.Encloses(dir) {
665 pushView(&gopathViews, view)
666 }
667 case AdHocView:
668 if def.root == dir {
669 adHocViews = append(adHocViews, view)
670 }
671 }
672 }
673
674 // Now that we've collected matching views, choose the best match,
675 // considering ports.
676 //
677 // We only consider one type of view, since the matching view created by
678 // defineView should be of the best type.
679 var relevantViews []V
680 switch {
681 case len(workViews) > 0:
682 relevantViews = workViews
683 case len(modViews) > 0:
684 relevantViews = modViews
685 case len(gopathViews) > 0:
686 relevantViews = gopathViews
687 case len(goPackagesViews) > 0:
688 relevantViews = goPackagesViews
689 case len(adHocViews) > 0:
690 relevantViews = adHocViews
691 }
692
693 return relevantViews, nil
694 }
695
696 // matchingView returns the View or viewDefinition out of relevantViews that
697 // matches the given file's build constraints, or nil if no match is found.
698 //
699 // Making this function generic is convenient so that we can avoid mapping view
700 // definitions back to views inside Session.DidModifyFiles, where performance
701 // matters. It is, however, not the cleanest application of generics.
702 //
703 // Note: keep this function in sync with defineView.
704 func matchingView[V viewDefiner](fh file.Handle, relevantViews []V) V {
705 var zero V
706
707 if len(relevantViews) == 0 {
708 return zero
709 }
710
711 content, err := fh.Content()
712
713 // Port matching doesn't apply to non-go files, or files that no longer exist.
714 // Note that the behavior here on non-existent files shouldn't matter much,
715 // since there will be a subsequent failure.
716 if fileKind(fh) != file.Go || err != nil {
717 return relevantViews[0]
718 }
719
720 // Find the first view that matches constraints.
721 // Content trimming is nontrivial, so do this outside of the loop below.
722 path := fh.URI().Path()
723 content = trimContentForPortMatch(content)
724 for _, v := range relevantViews {
725 def := v.definition()
726 viewPort := port{def.GOOS(), def.GOARCH()}
727 if viewPort.matches(path, content) {
728 return v
729 }
730 }
731
732 return zero // no view found
733 }
734
735 // ResetView resets the best view for the given URI.
736 func (s *Session) ResetView(ctx context.Context, uri protocol.DocumentURI) (*View, error) {
737 s.viewMu.Lock()
738 defer s.viewMu.Unlock()
739
740 if s.viewMap == nil {
741 return nil, fmt.Errorf("session is shut down")
742 }
743
744 view, err := s.viewOfLocked(ctx, uri.Clean())
745 if err != nil {
746 return nil, err
747 }
748 if view == nil {
749 return nil, fmt.Errorf("no view for %s", uri)
750 }
751
752 s.viewMap = make(map[protocol.DocumentURI]*View)
753 for i, v := range s.views {
754 if v == view {
755 v2, _, release := s.createView(ctx, view.viewDefinition)
756 release() // don't need the snapshot
757 v.shutdown()
758 s.views[i] = v2
759 return v2, nil
760 }
761 }
762
763 return nil, bug.Errorf("missing view") // can't happen...
764 }
765
766 // DidModifyFiles reports a file modification to the session. It returns
767 // the new snapshots after the modifications have been applied, paired with
768 // the affected file URIs for those snapshots.
769 // On success, it returns a release function that
770 // must be called when the snapshots are no longer needed.
771 //
772 // TODO(rfindley): what happens if this function fails? It must leave us in a
773 // broken state, which we should surface to the user, probably as a request to
774 // restart gopls.
775 func (s *Session) DidModifyFiles(ctx context.Context, modifications []file.Modification) (map[*View][]protocol.DocumentURI, error) {
776 s.viewMu.Lock()
777 defer s.viewMu.Unlock()
778
779 // Short circuit the logic below if s is shut down.
780 if s.viewMap == nil {
781 return nil, fmt.Errorf("session is shut down")
782 }
783
784 // Update overlays.
785 //
786 // This is done while holding viewMu because the set of open files affects
787 // the set of views, and to prevent views from seeing updated file content
788 // before they have processed invalidations.
789 replaced, err := s.updateOverlays(ctx, modifications)
790 if err != nil {
791 return nil, err
792 }
793
794 // checkViews controls whether the set of views needs to be recomputed, for
795 // example because a go.mod file was created or deleted, or a go.work file
796 // changed on disk.
797 checkViews := false
798
799 // Hack: collect folders from existing views.
800 // TODO(golang/go#57979): we really should track folders independent of
801 // Views, but since we always have a default View for each folder, this
802 // works for now.
803 var folders []*Folder // preserve folder order
804 workspaceFileGlobsSet := make(map[string]bool)
805 seen := make(map[*Folder]unit)
806 for _, v := range s.views {
807 if _, ok := seen[v.folder]; ok {
808 continue
809 }
810 seen[v.folder] = unit{}
811 folders = append(folders, v.folder)
812 for _, glob := range v.folder.Options.WorkspaceFiles {
813 workspaceFileGlobsSet[glob] = true
814 }
815 }
816 workspaceFileGlobs := slices.Collect(maps.Keys(workspaceFileGlobsSet))
817
818 changed := make(map[protocol.DocumentURI]file.Handle)
819 for _, c := range modifications {
820 fh := mustReadFile(ctx, s, c.URI)
821 changed[c.URI] = fh
822
823 // Any change to the set of open files causes views to be recomputed.
824 if c.Action == file.Open || c.Action == file.Close {
825 checkViews = true
826 }
827
828 // Any on-disk change to a go.work or go.mod file causes recomputing views.
829 //
830 // TODO(rfindley): go.work files need not be named "go.work" -- we need to
831 // check each view's source to handle the case of an explicit GOWORK value.
832 // Write a test that fails, and fix this.
833 if (isGoWork(c.URI) || isGoMod(c.URI) || isWorkspaceFile(c.URI, workspaceFileGlobs)) && (c.Action == file.Save || c.OnDisk) {
834 checkViews = true
835 }
836
837 // Any change to the set of supported ports in a file may affect view
838 // selection. This is perhaps more subtle than it first seems: since the
839 // algorithm for selecting views considers open files in a deterministic
840 // order, a change in supported ports may cause a different port to be
841 // chosen, even if all open files still match an existing View!
842 //
843 // We endeavor to avoid that sort of path dependence, so must re-run the
844 // view selection algorithm whenever any input changes.
845 //
846 // However, extracting the build comment is nontrivial, so we don't want to
847 // pay this cost when e.g. processing a bunch of on-disk changes due to a
848 // branch change. Be careful to only do this if both files are open Go
849 // files.
850 if old, ok := replaced[c.URI]; ok && !checkViews && fileKind(fh) == file.Go {
851 if new, ok := fh.(*overlay); ok {
852 if buildComment(old.content) != buildComment(new.content) {
853 checkViews = true
854 }
855 }
856 }
857 }
858
859 if checkViews {
860 var openFiles []protocol.DocumentURI
861 for _, o := range s.Overlays() {
862 openFiles = append(openFiles, o.URI())
863 }
864 // Sort for determinism.
865 slices.Sort(openFiles)
866
867 // TODO(rfindley): can we avoid running the go command (go env)
868 // synchronously to change processing? Can we assume that the env did not
869 // change, and derive go.work using a combination of the configured
870 // GOWORK value and filesystem?
871 defs, err := selectViewDefs(ctx, s, folders, openFiles)
872 if err != nil {
873 // Catastrophic failure, equivalent to a failure of session
874 // initialization and therefore should almost never happen. One
875 // scenario where this failure mode could occur is if some file
876 // permissions have changed preventing us from reading go.mod
877 // files.
878 //
879 // TODO(rfindley): consider surfacing this error more loudly. We
880 // could report a bug, but it's not really a bug.
881 event.Error(ctx, "selecting new views", err)
882 } else {
883 kept := make(map[*View]unit)
884 var newViews []*View
885 for _, def := range defs {
886 var newView *View
887 // Reuse existing view?
888 for _, v := range s.views {
889 if viewDefinitionsEqual(def, v.viewDefinition) {
890 newView = v
891 kept[v] = unit{}
892 break
893 }
894 }
895 if newView == nil {
896 v, _, release := s.createView(ctx, def)
897 release()
898 newView = v
899 }
900 newViews = append(newViews, newView)
901 }
902 for _, v := range s.views {
903 if _, ok := kept[v]; !ok {
904 v.shutdown()
905 }
906 }
907 s.views = newViews
908 s.viewMap = make(map[protocol.DocumentURI]*View)
909 }
910 }
911
912 // We only want to run fast-path diagnostics (i.e. diagnoseChangedFiles) once
913 // for each changed file, in its best view.
914 viewsToDiagnose := map[*View][]protocol.DocumentURI{}
915 for _, mod := range modifications {
916 v, err := s.viewOfLocked(ctx, mod.URI)
917 if err != nil {
918 // viewOfLocked only returns an error in the event of context
919 // cancellation, or if the session is shut down. Since state changes
920 // should occur on an uncancellable context, and s.viewMap was checked at
921 // the top of this function, an error here is a bug.
922 bug.Reportf("finding best view for change: %v", err)
923 continue
924 }
925 if v != nil {
926 viewsToDiagnose[v] = append(viewsToDiagnose[v], mod.URI)
927 }
928 }
929
930 // ...but changes may be relevant to other views, for example if they are
931 // changes to a shared package.
932 for _, v := range s.views {
933 _, release, needsDiagnosis := s.invalidateViewLocked(ctx, v, StateChange{Modifications: modifications, Files: changed})
934 release()
935
936 if needsDiagnosis || checkViews {
937 if _, ok := viewsToDiagnose[v]; !ok {
938 viewsToDiagnose[v] = nil
939 }
940 }
941 }
942
943 return viewsToDiagnose, nil
944 }
945
946 // ExpandModificationsToDirectories returns the set of changes with the
947 // directory changes removed and expanded to include all of the files in
948 // the directory.
949 func (s *Session) ExpandModificationsToDirectories(ctx context.Context, changes []file.Modification) []file.Modification {
950 var snapshots []*Snapshot
951 s.viewMu.Lock()
952 for _, v := range s.views {
953 snapshot, release, err := v.Snapshot()
954 if err != nil {
955 continue // view is shut down; continue with others
956 }
957 defer release()
958 snapshots = append(snapshots, snapshot)
959 }
960 s.viewMu.Unlock()
961
962 // Expand the modification to any file we could care about, which we define
963 // to be any file observed by any of the snapshots.
964 //
965 // There may be other files in the directory, but if we haven't read them yet
966 // we don't need to invalidate them.
967 var result []file.Modification
968 for _, c := range changes {
969 expanded := make(map[protocol.DocumentURI]bool)
970 for _, snapshot := range snapshots {
971 for _, uri := range snapshot.filesInDir(c.URI) {
972 expanded[uri] = true
973 }
974 }
975 if len(expanded) == 0 {
976 result = append(result, c)
977 } else {
978 for uri := range expanded {
979 result = append(result, file.Modification{
980 URI: uri,
981 Action: c.Action,
982 LanguageID: "",
983 OnDisk: c.OnDisk,
984 // changes to directories cannot include text or versions
985 })
986 }
987 }
988 }
989 return result
990 }
991
992 // updateOverlays updates the set of overlays and returns a map of any existing
993 // overlay values that were replaced.
994 //
995 // Precondition: caller holds s.viewMu lock.
996 // TODO(rfindley): move this to fs_overlay.go.
997 func (fs *overlayFS) updateOverlays(ctx context.Context, changes []file.Modification) (map[protocol.DocumentURI]*overlay, error) {
998 fs.mu.Lock()
999 defer fs.mu.Unlock()
1000
1001 replaced := make(map[protocol.DocumentURI]*overlay)
1002 for _, c := range changes {
1003 o, ok := fs.overlays[c.URI]
1004 if ok {
1005 replaced[c.URI] = o
1006 }
1007
1008 // If the file is not opened in an overlay and the change is on disk,
1009 // there's no need to update an overlay. If there is an overlay, we
1010 // may need to update the overlay's saved value.
1011 if !ok && c.OnDisk {
1012 continue
1013 }
1014
1015 // Determine the file kind on open, otherwise, assume it has been cached.
1016 var kind file.Kind
1017 switch c.Action {
1018 case file.Open:
1019 kind = file.KindForLang(c.LanguageID)
1020 default:
1021 if !ok {
1022 return nil, fmt.Errorf("updateOverlays: modifying unopened overlay %v", c.URI)
1023 }
1024 kind = o.kind
1025 }
1026
1027 // Closing a file just deletes its overlay.
1028 if c.Action == file.Close {
1029 delete(fs.overlays, c.URI)
1030 continue
1031 }
1032
1033 // If the file is on disk, check if its content is the same as in the
1034 // overlay. Saves and on-disk file changes don't come with the file's
1035 // content.
1036 text := c.Text
1037 if text == nil && (c.Action == file.Save || c.OnDisk) {
1038 if !ok {
1039 return nil, fmt.Errorf("no known content for overlay for %s", c.Action)
1040 }
1041 text = o.content
1042 }
1043 // On-disk changes don't come with versions.
1044 version := c.Version
1045 if c.OnDisk || c.Action == file.Save {
1046 version = o.version
1047 }
1048 hash := file.HashOf(text)
1049 var sameContentOnDisk bool
1050 switch c.Action {
1051 case file.Delete:
1052 // Do nothing. sameContentOnDisk should be false.
1053 case file.Save:
1054 // Make sure the version and content (if present) is the same.
1055 if false && o.version != version { // Client no longer sends the version
1056 return nil, fmt.Errorf("updateOverlays: saving %s at version %v, currently at %v", c.URI, c.Version, o.version)
1057 }
1058 if c.Text != nil && o.hash != hash {
1059 return nil, fmt.Errorf("updateOverlays: overlay %s changed on save", c.URI)
1060 }
1061 sameContentOnDisk = true
1062 default:
1063 fh := mustReadFile(ctx, fs.delegate, c.URI)
1064 _, readErr := fh.Content()
1065 sameContentOnDisk = (readErr == nil && fh.Identity().Hash == hash)
1066 }
1067 o = &overlay{
1068 uri: c.URI,
1069 version: version,
1070 content: text,
1071 modTime: time.Now(),
1072 kind: kind,
1073 hash: hash,
1074 saved: sameContentOnDisk,
1075 }
1076
1077 // NOTE: previous versions of this code checked here that the overlay had a
1078 // view and file kind (but we don't know why).
1079
1080 fs.overlays[c.URI] = o
1081 }
1082
1083 return replaced, nil
1084 }
1085
1086 func mustReadFile(ctx context.Context, fs file.Source, uri protocol.DocumentURI) file.Handle {
1087 ctx = context.WithoutCancel(ctx)
1088 fh, err := fs.ReadFile(ctx, uri)
1089 if err != nil {
1090 // ReadFile cannot fail with an uncancellable context.
1091 bug.Reportf("reading file failed unexpectedly: %v", err)
1092 return brokenFile{uri, err}
1093 }
1094 return fh
1095 }
1096
1097 // A brokenFile represents an unexpected failure to read a file.
1098 type brokenFile struct {
1099 uri protocol.DocumentURI
1100 err error
1101 }
1102
1103 func (b brokenFile) String() string { return b.uri.Path() }
1104 func (b brokenFile) URI() protocol.DocumentURI { return b.uri }
1105 func (b brokenFile) Identity() file.Identity { return file.Identity{URI: b.uri} }
1106 func (b brokenFile) SameContentsOnDisk() bool { return false }
1107 func (b brokenFile) Version() int32 { return 0 }
1108 func (b brokenFile) Content() ([]byte, error) { return nil, b.err }
1109 func (b brokenFile) ModTime() (time.Time, error) { return time.Time{}, b.err }
1110
1111 // FileWatchingGlobPatterns returns a set of glob patterns that the client is
1112 // required to watch for changes, and notify the server of them, in order to
1113 // keep the server's state up to date.
1114 //
1115 // This set includes
1116 // 1. all go.mod and go.work files in the workspace; and
1117 // 2. all files defined by the WorkspaceFiles option in BuildOptions (to support custom GOPACKAGESDRIVERS); and
1118 // 3. for each Snapshot, its modules (or directory for ad-hoc views). In
1119 // module mode, this is the set of active modules (and for VS Code, all
1120 // workspace directories within them, due to golang/go#42348).
1121 //
1122 // The watch for workspace files in (1) is sufficient to
1123 // capture changes to the repo structure that may affect the set of views.
1124 // Whenever this set changes, we reload the workspace and invalidate memoized
1125 // files.
1126 //
1127 // The watch for workspace directories in (2) should keep each View up to date,
1128 // as it should capture any newly added/modified/deleted Go files.
1129 //
1130 // Patterns are returned as a set of protocol.RelativePatterns, since they can
1131 // always be later translated to glob patterns (i.e. strings) if the client
1132 // lacks relative pattern support. By convention, any pattern returned with
1133 // empty baseURI should be served as a glob pattern.
1134 //
1135 // In general, we prefer to serve relative patterns, as they work better on
1136 // most clients that support both, and do not have issues with Windows driver
1137 // letter casing:
1138 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#relativePattern
1139 //
1140 // TODO(golang/go#57979): we need to reset the memoizedFS when a view changes.
1141 // Consider the case where we incidentally read a file, then it moved outside
1142 // of an active module, and subsequently changed: we would still observe the
1143 // original file state.
1144 func (s *Session) FileWatchingGlobPatterns(ctx context.Context) map[protocol.RelativePattern]unit {
1145 s.viewMu.Lock()
1146 defer s.viewMu.Unlock()
1147
1148 // Always watch files that may change the set of views.
1149 patterns := map[protocol.RelativePattern]unit{
1150 {Pattern: "**/*.{mod,work}"}: {},
1151 }
1152
1153 for _, view := range s.views {
1154 snapshot, release, err := view.Snapshot()
1155 if err != nil {
1156 continue // view is shut down; continue with others
1157 }
1158 maps.Copy(patterns, snapshot.fileWatchingGlobPatterns())
1159 release()
1160 }
1161 return patterns
1162 }
1163
1164 // OrphanedFileDiagnostics reports diagnostics describing why open files have
1165 // no packages or have only command-line-arguments packages.
1166 //
1167 // If the resulting diagnostic is nil, the file is either not orphaned or we
1168 // can't produce a good diagnostic.
1169 //
1170 // The caller must not mutate the result.
1171 func (s *Session) OrphanedFileDiagnostics(ctx context.Context) (map[protocol.DocumentURI][]*Diagnostic, error) {
1172 if err := ctx.Err(); err != nil {
1173 // Avoid collecting diagnostics if the context is cancelled.
1174 // (Previously, it was possible to get all the way to packages.Load on a cancelled context)
1175 return nil, err
1176 }
1177 // Note: diagnostics holds a slice for consistency with other diagnostic
1178 // funcs.
1179 diagnostics := make(map[protocol.DocumentURI][]*Diagnostic)
1180
1181 byView := make(map[*View][]*overlay)
1182 for _, o := range s.Overlays() {
1183 uri := o.URI()
1184 snapshot, release, err := s.SnapshotOf(ctx, uri)
1185 if err != nil {
1186 // TODO(golang/go#57979): we have to use the .go suffix as an approximation for
1187 // file kind here, because we don't have access to Options if no View was
1188 // matched.
1189 //
1190 // But Options are really a property of Folder, not View, and we could
1191 // match a folder here.
1192 //
1193 // Refactor so that Folders are tracked independently of Views, and use
1194 // the correct options here to get the most accurate file kind.
1195 //
1196 // TODO(golang/go#57979): once we switch entirely to the zeroconfig
1197 // logic, we should use this diagnostic for the fallback case of
1198 // s.views[0] in the ViewOf logic.
1199 if errors.Is(err, errNoViews) {
1200 if strings.HasSuffix(string(uri), ".go") {
1201 if _, rng, ok := orphanedFileDiagnosticRange(ctx, s.parseCache, o); ok {
1202 diagnostics[uri] = []*Diagnostic{{
1203 URI: uri,
1204 Range: rng,
1205 Severity: protocol.SeverityWarning,
1206 Source: ListError,
1207 Message: fmt.Sprintf("No active builds contain %s: consider opening a new workspace folder containing it", uri.Path()),
1208 }}
1209 }
1210 }
1211 continue
1212 }
1213 return nil, err
1214 }
1215 v := snapshot.View()
1216 release()
1217 byView[v] = append(byView[v], o)
1218 }
1219
1220 for view, overlays := range byView {
1221 snapshot, release, err := view.Snapshot()
1222 if err != nil {
1223 continue // view is shutting down
1224 }
1225 defer release()
1226 diags, err := snapshot.orphanedFileDiagnostics(ctx, overlays)
1227 if err != nil {
1228 return nil, err
1229 }
1230 for _, d := range diags {
1231 diagnostics[d.URI] = append(diagnostics[d.URI], d)
1232 }
1233 }
1234 return diagnostics, nil
1235 }