Debian Codegraph @

gopls/internal/cache/snapshot.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 "cmp"
10 "context"
11 "errors"
12 "fmt"
13 "go/ast"
14 "go/build/constraint"
15 "go/parser"
16 "go/token"
17 "os"
18 "path"
19 "path/filepath"
20 "regexp"
21 "slices"
22 "strconv"
23 "strings"
24 "sync"
25
26 "golang.org/x/tools/go/types/objectpath"
27 "golang.org/x/tools/gopls/internal/cache/metadata"
28 "golang.org/x/tools/gopls/internal/cache/methodsets"
29 "golang.org/x/tools/gopls/internal/cache/parsego"
30 "golang.org/x/tools/gopls/internal/cache/testfuncs"
31 "golang.org/x/tools/gopls/internal/cache/xrefs"
32 "golang.org/x/tools/gopls/internal/file"
33 "golang.org/x/tools/gopls/internal/filecache"
34 label1 "golang.org/x/tools/gopls/internal/label"
35 "golang.org/x/tools/gopls/internal/protocol"
36 "golang.org/x/tools/gopls/internal/protocol/command"
37 "golang.org/x/tools/gopls/internal/settings"
38 "golang.org/x/tools/gopls/internal/util/bug"
39 "golang.org/x/tools/gopls/internal/util/constraints"
40 "golang.org/x/tools/gopls/internal/util/immutable"
41 "golang.org/x/tools/gopls/internal/util/memoize"
42 "golang.org/x/tools/gopls/internal/util/moremaps"
43 "golang.org/x/tools/gopls/internal/util/pathutil"
44 "golang.org/x/tools/gopls/internal/util/persistent"
45 "golang.org/x/tools/gopls/internal/vulncheck"
46 "golang.org/x/tools/internal/event"
47 "golang.org/x/tools/internal/event/label"
48 "golang.org/x/tools/internal/gocommand"
49 )
50
51 // A Snapshot represents the current state for a given view.
52 //
53 // It is first and foremost an idempotent implementation of file.Source whose
54 // ReadFile method returns consistent information about the existence and
55 // content of each file throughout its lifetime.
56 //
57 // However, the snapshot also manages additional state (such as parsed files
58 // and packages) that are derived from file content.
59 //
60 // Snapshots are responsible for bookkeeping and invalidation of this state,
61 // implemented in Snapshot.clone.
62 type Snapshot struct {
63 // sequenceID is the monotonically increasing ID of this snapshot within its View.
64 //
65 // Sequence IDs for Snapshots from different Views cannot be compared.
66 sequenceID uint64
67
68 // TODO(rfindley): the snapshot holding a reference to the view poses
69 // lifecycle problems: a view may be shut down and waiting for work
70 // associated with this snapshot to complete. While most accesses of the view
71 // are benign (options or workspace information), this is not formalized and
72 // it is wrong for the snapshot to use a shutdown view.
73 //
74 // Fix this by passing options and workspace information to the snapshot,
75 // both of which should be immutable for the snapshot.
76 view *View
77
78 cancel func()
79 backgroundCtx context.Context
80
81 store *memoize.Store // cache of handles shared by all snapshots
82
83 refMu sync.Mutex
84
85 // refcount holds the number of outstanding references to the current
86 // Snapshot. When refcount is decremented to 0, the Snapshot maps are
87 // destroyed and the done function is called.
88 //
89 // TODO(rfindley): use atomic.Int32 on Go 1.19+.
90 refcount int
91 done func() // for implementing Session.Shutdown
92
93 // mu guards all of the maps in the snapshot, as well as the builtin URI and
94 // initialized.
95 mu sync.Mutex
96
97 // initialized reports whether the snapshot has been initialized. Concurrent
98 // initialization is guarded by the view.initializationSema. Each snapshot is
99 // initialized at most once: concurrent initialization is guarded by
100 // view.initializationSema.
101 initialized bool
102
103 // initialErr holds the last error resulting from initialization. If
104 // initialization fails, we only retry when the workspace modules change,
105 // to avoid too many go/packages calls.
106 // If initialized is false, initialErr still holds the error resulting from
107 // the previous initialization.
108 // TODO(rfindley): can we unify the lifecycle of initialized and initialErr.
109 initialErr *InitializationError
110
111 // builtin is the location of builtin.go in GOROOT.
112 //
113 // TODO(rfindley): would it make more sense to eagerly parse builtin, and
114 // instead store a *parsego.File here?
115 builtin protocol.DocumentURI
116
117 // meta holds loaded metadata.
118 //
119 // meta is guarded by mu, but the Graph itself is immutable.
120 //
121 // TODO(rfindley): in many places we hold mu while operating on meta, even
122 // though we only need to hold mu while reading the pointer.
123 meta *metadata.Graph
124
125 // files maps file URIs to their corresponding FileHandles.
126 // It may invalidated when a file's content changes.
127 files *fileMap
128
129 // packages maps a packageKey to a *packageHandle.
130 // It may be invalidated when a file's content changes.
131 //
132 // Invariants to preserve:
133 // - packages.Get(id).meta == meta.metadata[id] for all ids
134 // - if a package is in packages, then all of its dependencies should also
135 // be in packages, unless there is a missing import
136 packages *persistent.Map[PackageID, *packageHandle]
137
138 // fullAnalysisKeys and factyAnalysisKeys hold memoized cache keys for
139 // analysis packages. "full" refers to the cache key including all enabled
140 // analyzers, whereas "facty" is the key including only the subset of enabled
141 // analyzers that produce facts, such as is required for transitively
142 // imported packages.
143 //
144 // These keys are memoized because they can be quite expensive to compute.
145 fullAnalysisKeys *persistent.Map[PackageID, file.Hash]
146 factyAnalysisKeys *persistent.Map[PackageID, file.Hash]
147
148 // workspacePackages contains the workspace's packages, which are loaded
149 // when the view is created. It does not contain intermediate test variants.
150 workspacePackages immutable.Map[PackageID, PackagePath]
151
152 // shouldLoad tracks packages that need to be reloaded, mapping a PackageID
153 // to the package paths that should be used to reload it
154 //
155 // When we try to load a package, we clear it from the shouldLoad map
156 // regardless of whether the load succeeded, to prevent endless loads.
157 shouldLoad *persistent.Map[PackageID, []PackagePath]
158
159 // unloadableFiles keeps track of files that we've failed to load.
160 unloadableFiles *persistent.Set[protocol.DocumentURI]
161
162 // TODO(rfindley): rename the handles below to "promises". A promise is
163 // different from a handle (we mutate the package handle.)
164
165 // parseModHandles keeps track of any parseModHandles for the snapshot.
166 // The handles need not refer to only the view's go.mod file.
167 parseModHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] // *memoize.Promise[parseModResult]
168
169 // parseWorkHandles keeps track of any parseWorkHandles for the snapshot.
170 // The handles need not refer to only the view's go.work file.
171 parseWorkHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] // *memoize.Promise[parseWorkResult]
172
173 // Preserve go.mod-related handles to avoid garbage-collecting the results
174 // of various calls to the go command. The handles need not refer to only
175 // the view's go.mod file.
176 modTidyHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] // *memoize.Promise[modTidyResult]
177 modWhyHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] // *memoize.Promise[modWhyResult]
178 modVulnHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] // *memoize.Promise[modVulnResult]
179
180 // moduleUpgrades tracks known upgrades for module paths in each modfile.
181 // Each modfile has a map of module name to upgrade version.
182 moduleUpgrades *persistent.Map[protocol.DocumentURI, map[string]string]
183
184 // vulns maps each go.mod file's URI to its known vulnerabilities.
185 vulns *persistent.Map[protocol.DocumentURI, *vulncheck.Result]
186
187 // compilerOptDetails is the set of directories whose packages
188 // and tests need compiler optimization details in the diagnostics.
189 compilerOptDetails map[protocol.DocumentURI]unit
190
191 // Concurrent type checking:
192 // typeCheckMu guards the ongoing type checking batch, and reference count of
193 // ongoing type checking operations.
194 // When the batch is no longer needed (batchRef=0), it is discarded.
195 typeCheckMu sync.Mutex
196 batchRef int
197 batch *typeCheckBatch
198 }
199
200 var _ memoize.RefCounted = (*Snapshot)(nil) // snapshots are reference-counted
201
202 func (s *Snapshot) awaitPromise(ctx context.Context, p *memoize.Promise) (any, error) {
203 return p.Get(ctx, s)
204 }
205
206 // Acquire prevents the snapshot from being destroyed until the returned
207 // function is called.
208 //
209 // (s.Acquire().release() could instead be expressed as a pair of
210 // method calls s.IncRef(); s.DecRef(). The latter has the advantage
211 // that the DecRefs are fungible and don't require holding anything in
212 // addition to the refcounted object s, but paradoxically that is also
213 // an advantage of the current approach, which forces the caller to
214 // consider the release function at every stage, making a reference
215 // leak more obvious.)
216 func (s *Snapshot) Acquire() func() {
217 s.refMu.Lock()
218 defer s.refMu.Unlock()
219 assert(s.refcount > 0, "non-positive refs")
220 s.refcount++
221
222 return s.decref
223 }
224
225 // decref should only be referenced by Acquire, and by View when it frees its
226 // reference to View.snapshot.
227 func (s *Snapshot) decref() {
228 s.refMu.Lock()
229 defer s.refMu.Unlock()
230
231 assert(s.refcount > 0, "non-positive refs")
232 s.refcount--
233 if s.refcount == 0 {
234 s.packages.Destroy()
235 s.files.destroy()
236 s.parseModHandles.Destroy()
237 s.parseWorkHandles.Destroy()
238 s.modTidyHandles.Destroy()
239 s.modVulnHandles.Destroy()
240 s.modWhyHandles.Destroy()
241 s.unloadableFiles.Destroy()
242 s.moduleUpgrades.Destroy()
243 s.vulns.Destroy()
244 s.done()
245 }
246 }
247
248 // SequenceID is the sequence id of this snapshot within its containing
249 // view.
250 //
251 // Relative to their view sequence ids are monotonically increasing, but this
252 // does not hold globally: when new views are created their initial snapshot
253 // has sequence ID 0.
254 func (s *Snapshot) SequenceID() uint64 {
255 return s.sequenceID
256 }
257
258 // Labels returns a new slice of labels that should be used for events
259 // related to a snapshot.
260 func (s *Snapshot) Labels() []label.Label {
261 return []label.Label{
262 label1.ViewID.Of(s.view.id),
263 label1.Snapshot.Of(s.SequenceID()),
264 label1.Directory.Of(s.Folder().Path()),
265 }
266 }
267
268 // Folder returns the folder at the base of this snapshot.
269 func (s *Snapshot) Folder() protocol.DocumentURI {
270 return s.view.folder.Dir
271 }
272
273 // View returns the View associated with this snapshot.
274 func (s *Snapshot) View() *View {
275 return s.view
276 }
277
278 // FileKind returns the kind of a file.
279 //
280 // We can't reliably deduce the kind from the file name alone,
281 // as some editors can be told to interpret a buffer as
282 // language different from the file name heuristic, e.g. that
283 // an .html file actually contains Go "html/template" syntax,
284 // or even that a .go file contains Python.
285 func (s *Snapshot) FileKind(fh file.Handle) file.Kind {
286 if k := fileKind(fh); k != file.UnknownKind {
287 return k
288 }
289 fext := filepath.Ext(fh.URI().Path())
290 exts := s.Options().TemplateExtensions
291 for _, ext := range exts {
292 if fext == ext || fext == "."+ext {
293 return file.Tmpl
294 }
295 }
296
297 // and now what? This should never happen, but it does for cgo before go1.15
298 //
299 // TODO(rfindley): this doesn't look right. We should default to UnknownKind.
300 // Also, I don't understand the comment above, though I'd guess before go1.15
301 // we encountered cgo files without the .go extension.
302 return file.Go
303 }
304
305 // fileKind returns the default file kind for a file, before considering
306 // template file extensions. See [Snapshot.FileKind].
307 func fileKind(fh file.Handle) file.Kind {
308 // The kind of an unsaved buffer comes from the
309 // TextDocumentItem.LanguageID field in the didChange event,
310 // not from the file name. They may differ.
311 if o, ok := fh.(*overlay); ok {
312 if o.kind != file.UnknownKind {
313 return o.kind
314 }
315 }
316
317 fext := filepath.Ext(fh.URI().Path())
318 switch fext {
319 case ".go":
320 return file.Go
321 case ".mod":
322 return file.Mod
323 case ".sum":
324 return file.Sum
325 case ".work":
326 return file.Work
327 case ".s":
328 return file.Asm
329 }
330 return file.UnknownKind
331 }
332
333 // Options returns the options associated with this snapshot.
334 func (s *Snapshot) Options() *settings.Options {
335 return s.view.folder.Options
336 }
337
338 // BackgroundContext returns a context used for all background processing
339 // on behalf of this snapshot.
340 func (s *Snapshot) BackgroundContext() context.Context {
341 return s.backgroundCtx
342 }
343
344 // Templates returns the .tmpl files.
345 func (s *Snapshot) Templates() map[protocol.DocumentURI]file.Handle {
346 s.mu.Lock()
347 defer s.mu.Unlock()
348
349 tmpls := map[protocol.DocumentURI]file.Handle{}
350 for k, fh := range s.files.all() {
351 if s.FileKind(fh) == file.Tmpl {
352 tmpls[k] = fh
353 }
354 }
355 return tmpls
356 }
357
358 // RunGoModUpdateCommands runs a series of `go` commands that updates the go.mod
359 // and go.sum file for wd, and returns their updated contents.
360 //
361 // TODO(rfindley): the signature of RunGoModUpdateCommands is very confusing,
362 // and is the only thing forcing the ModFlag and ModFile indirection.
363 // Simplify it.
364 func (s *Snapshot) RunGoModUpdateCommands(ctx context.Context, modURI protocol.DocumentURI, run func(invoke func(...string) (*bytes.Buffer, error)) error) ([]byte, []byte, error) {
365 tempDir, cleanupModDir, err := TempModDir(ctx, s, modURI)
366 if err != nil {
367 return nil, nil, err
368 }
369 defer cleanupModDir()
370
371 // TODO(rfindley): we must use ModFlag and ModFile here (rather than simply
372 // setting Args), because without knowing the verb, we can't know whether
373 // ModFlag is appropriate. Refactor so that args can be set by the caller.
374 inv, cleanupInvocation, err := s.GoCommandInvocation(NetworkOK, modURI.DirPath(), "", nil, "GOWORK=off")
375 if err != nil {
376 return nil, nil, err
377 }
378 defer cleanupInvocation()
379
380 inv.ModFlag = "mod"
381 inv.ModFile = filepath.Join(tempDir, "go.mod")
382 invoke := func(args ...string) (*bytes.Buffer, error) {
383 inv.Verb = args[0]
384 inv.Args = args[1:]
385 return s.view.gocmdRunner.Run(ctx, *inv)
386 }
387 if err := run(invoke); err != nil {
388 return nil, nil, err
389 }
390 var modBytes, sumBytes []byte
391 modBytes, err = os.ReadFile(filepath.Join(tempDir, "go.mod"))
392 if err != nil && !os.IsNotExist(err) {
393 return nil, nil, err
394 }
395 sumBytes, err = os.ReadFile(filepath.Join(tempDir, "go.sum"))
396 if err != nil && !os.IsNotExist(err) {
397 return nil, nil, err
398 }
399 return modBytes, sumBytes, nil
400 }
401
402 // TempModDir creates a temporary directory with the contents of the provided
403 // modURI, as well as its corresponding go.sum file, if it exists. On success,
404 // it is the caller's responsibility to call the cleanup function to remove the
405 // directory when it is no longer needed.
406 func TempModDir(ctx context.Context, fs file.Source, modURI protocol.DocumentURI) (dir string, _ func(), rerr error) {
407 dir, err := os.MkdirTemp("", "gopls-tempmod")
408 if err != nil {
409 return "", nil, err
410 }
411 cleanup := func() {
412 if err := os.RemoveAll(dir); err != nil {
413 event.Error(ctx, "cleaning temp dir", err)
414 }
415 }
416 defer func() {
417 if rerr != nil {
418 cleanup()
419 }
420 }()
421
422 // If go.mod exists, write it.
423 modFH, err := fs.ReadFile(ctx, modURI)
424 if err != nil {
425 return "", nil, err // context cancelled
426 }
427 if data, err := modFH.Content(); err == nil {
428 if err := os.WriteFile(filepath.Join(dir, "go.mod"), data, 0666); err != nil {
429 return "", nil, err
430 }
431 }
432
433 // If go.sum exists, write it.
434 sumURI := protocol.DocumentURI(strings.TrimSuffix(string(modURI), ".mod") + ".sum")
435 sumFH, err := fs.ReadFile(ctx, sumURI)
436 if err != nil {
437 return "", nil, err // context cancelled
438 }
439 if data, err := sumFH.Content(); err == nil {
440 if err := os.WriteFile(filepath.Join(dir, "go.sum"), data, 0666); err != nil {
441 return "", nil, err
442 }
443 }
444
445 return dir, cleanup, nil
446 }
447
448 // AllowNetwork determines whether Go commands are permitted to use the
449 // network. (Controlled via GOPROXY=off.)
450 type AllowNetwork bool
451
452 const (
453 NoNetwork AllowNetwork = false
454 NetworkOK AllowNetwork = true
455 )
456
457 // GoCommandInvocation populates inv with configuration for running go commands
458 // on the snapshot.
459 //
460 // On success, the caller must call the cleanup function exactly once
461 // when the invocation is no longer needed.
462 //
463 // TODO(rfindley): although this function has been simplified significantly,
464 // additional refactoring is still required: the responsibility for Env and
465 // BuildFlags should be more clearly expressed in the API.
466 //
467 // If allowNetwork is NoNetwork, set GOPROXY=off.
468 func (s *Snapshot) GoCommandInvocation(allowNetwork AllowNetwork, dir, verb string, args []string, env ...string) (_ *gocommand.Invocation, cleanup func(), _ error) {
469 inv := &gocommand.Invocation{
470 Verb: verb,
471 Args: args,
472 WorkingDir: dir,
473 Env: append(s.view.Env(), env...),
474 BuildFlags: slices.Clone(s.Options().BuildFlags),
475 }
476 if !allowNetwork {
477 inv.Env = append(inv.Env, "GOPROXY=off")
478 }
479
480 // Write overlay files for unsaved editor buffers.
481 overlay, cleanup, err := gocommand.WriteOverlays(s.buildOverlays())
482 if err != nil {
483 return nil, nil, err
484 }
485 inv.Overlay = overlay
486 return inv, cleanup, nil
487 }
488
489 // buildOverlays returns a new mapping from logical file name to
490 // effective content, for each unsaved editor buffer, in the same form
491 // as [packages.Cfg]'s Overlay field.
492 func (s *Snapshot) buildOverlays() map[string][]byte {
493 overlays := make(map[string][]byte)
494 for _, overlay := range s.Overlays() {
495 if overlay.saved {
496 continue
497 }
498 // TODO(rfindley): previously, there was a todo here to make sure we don't
499 // send overlays outside of the current view. IMO we should instead make
500 // sure this doesn't matter.
501 overlays[overlay.URI().Path()] = overlay.content
502 }
503 return overlays
504 }
505
506 // Overlays returns the set of overlays at this snapshot.
507 //
508 // Note that this may differ from the set of overlays on the server, if the
509 // snapshot observed a historical state.
510 func (s *Snapshot) Overlays() []*overlay {
511 s.mu.Lock()
512 defer s.mu.Unlock()
513
514 return s.files.getOverlays()
515 }
516
517 // Package data kinds, identifying various package data that may be stored in
518 // the file cache.
519 const (
520 xrefsKind = "xrefs"
521 methodSetsKind = "methodsets"
522 testsKind = "tests"
523 exportDataKind = "export"
524 diagnosticsKind = "diagnostics"
525 typerefsKind = "typerefs"
526 symbolsKind = "symbols"
527 )
528
529 // PackageDiagnostics returns diagnostics for files contained in specified
530 // packages.
531 //
532 // If these diagnostics cannot be loaded from cache, the requested packages
533 // may be type-checked.
534 func (s *Snapshot) PackageDiagnostics(ctx context.Context, ids ...PackageID) (map[protocol.DocumentURI][]*Diagnostic, error) {
535 ctx, done := event.Start(ctx, "cache.snapshot.PackageDiagnostics")
536 defer done()
537
538 var mu sync.Mutex
539 perFile := make(map[protocol.DocumentURI][]*Diagnostic)
540 collect := func(diags []*Diagnostic) {
541 mu.Lock()
542 defer mu.Unlock()
543 for _, diag := range diags {
544 perFile[diag.URI] = append(perFile[diag.URI], diag)
545 }
546 }
547 pre := func(_ int, ph *packageHandle) bool {
548 if diags, ok := filecache.GetOrFatal(diagnosticsKind, ph.key, decodeDiagnostics); ok {
549 collect(ph.loadDiagnostics)
550 collect(diags)
551 return false
552 }
553 return true
554 }
555 post := func(_ int, pkg *Package) {
556 collect(pkg.loadDiagnostics)
557 collect(pkg.pkg.diagnostics)
558 }
559 return perFile, s.forEachPackage(ctx, ids, pre, post)
560 }
561
562 // References returns cross-reference indexes for the specified packages.
563 //
564 // If these indexes cannot be loaded from cache, the requested packages may
565 // be type-checked.
566 func (s *Snapshot) References(ctx context.Context, ids ...PackageID) ([]xrefIndex, error) {
567 ctx, done := event.Start(ctx, "cache.snapshot.References")
568 defer done()
569
570 indexes := make([]xrefIndex, len(ids))
571 pre := func(i int, ph *packageHandle) bool {
572 if idx, ok := filecache.GetOrFatal(xrefsKind, ph.key, xrefs.Decode); ok {
573 indexes[i] = xrefIndex{mp: ph.mp, idx: idx}
574 return false
575 }
576 return true
577 }
578 post := func(i int, pkg *Package) {
579 indexes[i] = xrefIndex{mp: pkg.metadata, idx: pkg.pkg.xrefs()}
580 }
581 return indexes, s.forEachPackage(ctx, ids, pre, post)
582 }
583
584 // An xrefIndex is a helper for looking up references in a given package.
585 type xrefIndex struct {
586 mp *metadata.Package
587 idx *xrefs.Index
588 }
589
590 func (index xrefIndex) Lookup(targets map[PackagePath]map[objectpath.Path]struct{}) []protocol.Location {
591 return index.idx.Lookup(index.mp, targets)
592 }
593
594 // MethodSets returns method-set indexes for the specified packages.
595 //
596 // If these indexes cannot be loaded from cache, the requested packages may
597 // be type-checked.
598 func (s *Snapshot) MethodSets(ctx context.Context, ids ...PackageID) ([]*methodsets.Index, error) {
599 ctx, done := event.Start(ctx, "cache.snapshot.MethodSets")
600 defer done()
601
602 indexes := make([]*methodsets.Index, len(ids))
603 pre := func(i int, ph *packageHandle) bool {
604 pkgPath := ph.mp.PkgPath // capture for decode closure
605 if idx, ok := filecache.GetOrFatal(methodSetsKind, ph.key, func(data []byte) *methodsets.Index {
606 return methodsets.Decode(pkgPath, data)
607 }); ok {
608 indexes[i] = idx
609 return false
610 }
611 return true
612 }
613 post := func(i int, pkg *Package) {
614 indexes[i] = pkg.pkg.methodsets()
615 }
616 return indexes, s.forEachPackage(ctx, ids, pre, post)
617 }
618
619 // Tests returns test-set indexes for the specified packages. There is a
620 // one-to-one correspondence between ID and Index.
621 //
622 // If these indexes cannot be loaded from cache, the requested packages may be
623 // type-checked.
624 func (s *Snapshot) Tests(ctx context.Context, ids ...PackageID) ([]*testfuncs.Index, error) {
625 ctx, done := event.Start(ctx, "cache.snapshot.Tests")
626 defer done()
627
628 indexes := make([]*testfuncs.Index, len(ids))
629 pre := func(i int, ph *packageHandle) bool {
630 if idx, ok := filecache.GetOrFatal(testsKind, ph.key, testfuncs.Decode); ok {
631 indexes[i] = idx
632 return false
633 }
634 return true
635 }
636 post := func(i int, pkg *Package) {
637 indexes[i] = pkg.pkg.tests()
638 }
639 return indexes, s.forEachPackage(ctx, ids, pre, post)
640 }
641
642 // NarrowestMetadataForFile returns metadata for the narrowest package
643 // (the one with the fewest files) that encloses the specified file.
644 // The result may be a test variant, but never an intermediate test variant.
645 func (snapshot *Snapshot) NarrowestMetadataForFile(ctx context.Context, uri protocol.DocumentURI) (*metadata.Package, error) {
646 mps, err := snapshot.MetadataForFile(ctx, uri, true)
647 if err != nil {
648 return nil, err
649 }
650 if len(mps) == 0 {
651 return nil, fmt.Errorf("no package metadata for file %s", uri)
652 }
653 return mps[0], nil
654 }
655
656 // MetadataForFile returns a new slice containing metadata for each
657 // package containing the Go file identified by uri, ordered by the
658 // number of CompiledGoFiles (i.e. "narrowest" to "widest" package),
659 // and secondarily by IsIntermediateTestVariant (false < true).
660 // The result may include tests and intermediate test variants of
661 // importable packages. If removeIntermediateTestVariants is provided,
662 // intermediate test variants will be excluded.
663 // It returns an error if the context was cancelled.
664 func (s *Snapshot) MetadataForFile(ctx context.Context, uri protocol.DocumentURI, removeIntermediateTestVariants bool) ([]*metadata.Package, error) {
665 if s.view.typ == AdHocView {
666 // As described in golang/go#57209, in ad-hoc workspaces (where we load ./
667 // rather than ./...), preempting the directory load with file loads can
668 // lead to an inconsistent outcome, where certain files are loaded with
669 // command-line-arguments packages and others are loaded only in the ad-hoc
670 // package. Therefore, ensure that the workspace is loaded before doing any
671 // file loads.
672 if err := s.awaitLoaded(ctx); err != nil {
673 return nil, err
674 }
675 }
676
677 s.mu.Lock()
678
679 // Start with the set of package associations derived from the last load.
680 pkgs := s.meta.ForFile[uri]
681
682 shouldLoad := false // whether any packages containing uri are marked 'shouldLoad'
683 for _, pkg := range pkgs {
684 if p, _ := s.shouldLoad.Get(pkg.ID); len(p) > 0 {
685 shouldLoad = true
686 }
687 }
688
689 // Check if uri is known to be unloadable.
690 unloadable := s.unloadableFiles.Contains(uri)
691
692 s.mu.Unlock()
693
694 // Reload if loading is likely to improve the package associations for uri:
695 // - uri is not contained in any valid packages
696 // - ...or one of the packages containing uri is marked 'shouldLoad'
697 // - ...but uri is not unloadable
698 if (shouldLoad || len(pkgs) == 0) && !unloadable {
699 scope := fileLoadScope(uri)
700 err := s.load(ctx, NoNetwork, scope)
701
702 // Return the context error here as the current operation is no longer
703 // valid.
704 if err != nil {
705 // Guard against failed loads due to context cancellation. We don't want
706 // to mark loads as completed if they failed due to context cancellation.
707 if ctx.Err() != nil {
708 return nil, ctx.Err()
709 }
710
711 // Don't return an error here, as we may still return stale IDs.
712 // Furthermore, the result of MetadataForFile should be consistent upon
713 // subsequent calls, even if the file is marked as unloadable.
714 if !errors.Is(err, errNoPackages) {
715 event.Error(ctx, "MetadataForFile", err)
716 }
717 }
718
719 // We must clear scopes after loading.
720 //
721 // TODO(rfindley): unlike reloadWorkspace, this is simply marking loaded
722 // packages as loaded. We could do this from snapshot.load and avoid
723 // raciness.
724 s.clearShouldLoad(scope)
725 }
726
727 // Retrieve the metadata.
728 s.mu.Lock()
729 defer s.mu.Unlock()
730 // TODO(rfindley): is there any reason not to make the sorting below the
731 // canonical sorting, so that we don't need to mutate this slice?
732 metas := slices.Clone(s.meta.ForFile[uri])
733
734 // Metadata is only ever added by loading,
735 // so if we get here and still have
736 // no packages, uri is unloadable.
737 if !unloadable && len(metas) == 0 {
738 s.unloadableFiles.Add(uri)
739 }
740
741 if removeIntermediateTestVariants {
742 metadata.RemoveIntermediateTestVariants(&metas)
743 }
744
745 // Sort packages "narrowest" to "widest" (in practice:
746 // non-tests before tests), and regular packages before
747 // their intermediate test variants (which have the same
748 // files but different imports).
749 slices.SortFunc(metas, func(x, y *metadata.Package) int {
750 if sign := cmp.Compare(len(x.CompiledGoFiles), len(y.CompiledGoFiles)); sign != 0 {
751 return sign
752 }
753 // Skip ITV-specific ordering if they were removed.
754 if removeIntermediateTestVariants {
755 return 0
756 }
757 return boolCompare(x.IsIntermediateTestVariant(), y.IsIntermediateTestVariant())
758 })
759
760 return metas, nil
761 }
762
763 // btoi returns int(b) as proposed in #64825.
764 func btoi(b bool) int {
765 if b {
766 return 1
767 } else {
768 return 0
769 }
770 }
771
772 // boolCompare is a comparison function for booleans, returning -1 if x < y, 0
773 // if x == y, and 1 if x > y, where false < true.
774 func boolCompare(x, y bool) int {
775 return btoi(x) - btoi(y)
776 }
777
778 // ReverseDependencies returns a new mapping whose entries are
779 // the ID and Metadata of each package in the workspace that
780 // directly or transitively depend on the package denoted by id,
781 // excluding id itself.
782 func (s *Snapshot) ReverseDependencies(ctx context.Context, id PackageID, transitive bool) (map[PackageID]*metadata.Package, error) {
783 if err := s.awaitLoaded(ctx); err != nil {
784 return nil, err
785 }
786
787 meta := s.MetadataGraph()
788 var rdeps map[PackageID]*metadata.Package
789 if transitive {
790 rdeps = meta.ReverseReflexiveTransitiveClosure(id)
791
792 // Remove the original package ID from the map.
793 // (Callers all want irreflexivity but it's easier
794 // to compute reflexively then subtract.)
795 delete(rdeps, id)
796
797 } else {
798 // direct reverse dependencies
799 rdeps = make(map[PackageID]*metadata.Package)
800 for _, rdep := range meta.ImportedBy[id] {
801 rdeps[rdep.ID] = rdep
802 }
803 }
804
805 return rdeps, nil
806 }
807
808 // See Session.FileWatchingGlobPatterns for a description of gopls' file
809 // watching heuristic.
810 func (s *Snapshot) fileWatchingGlobPatterns() map[protocol.RelativePattern]unit {
811 // Always watch files that may change the view definition.
812 patterns := make(map[protocol.RelativePattern]unit)
813
814 // If GOWORK is outside the folder, ensure we are watching it.
815 if s.view.gowork != "" && !s.view.folder.Dir.Encloses(s.view.gowork) {
816 workPattern := protocol.RelativePattern{
817 BaseURI: s.view.gowork.Dir(),
818 Pattern: path.Base(string(s.view.gowork)),
819 }
820 patterns[workPattern] = unit{}
821 }
822
823 for _, glob := range s.Options().WorkspaceFiles {
824 patterns[protocol.RelativePattern{Pattern: glob}] = unit{}
825 }
826
827 var extensions strings.Builder
828 extensions.WriteString("go,mod,sum,work")
829 for _, ext := range s.Options().TemplateExtensions {
830 extensions.WriteString(",")
831 extensions.WriteString(ext)
832 }
833 watchGoFiles := fmt.Sprintf("**/*.{%s}", extensions.String())
834
835 var dirs []string
836 if s.view.typ.usesModules() {
837 if s.view.typ == GoWorkView {
838 workVendorDir := filepath.Join(s.view.gowork.DirPath(), "vendor")
839 workVendorURI := protocol.URIFromPath(workVendorDir)
840 patterns[protocol.RelativePattern{BaseURI: workVendorURI, Pattern: watchGoFiles}] = unit{}
841 }
842
843 // In module mode, watch directories containing active modules, and collect
844 // these dirs for later filtering the set of known directories.
845 //
846 // The assumption is that the user is not actively editing non-workspace
847 // modules, so don't pay the price of file watching.
848 for modFile := range s.view.workspaceModFiles {
849 dirs = append(dirs, modFile.DirPath())
850
851 // TODO(golang/go#64724): thoroughly test these patterns, particularly on
852 // on Windows.
853 //
854 // Note that glob patterns should use '/' on Windows:
855 // https://code.visualstudio.com/docs/editor/glob-patterns
856 patterns[protocol.RelativePattern{BaseURI: modFile.Dir(), Pattern: watchGoFiles}] = unit{}
857 }
858 } else {
859 // In non-module modes (GOPATH or AdHoc), we just watch the workspace root.
860 dirs = []string{s.view.root.Path()}
861 patterns[protocol.RelativePattern{Pattern: watchGoFiles}] = unit{}
862 }
863
864 if s.watchSubdirs() {
865 // Some clients (e.g. VS Code) do not send notifications for changes to
866 // directories that contain Go code (golang/go#42348). To handle this,
867 // explicitly watch all of the directories in the workspace. We find them
868 // by adding the directories of every file in the snapshot's workspace
869 // directories. There may be thousands of patterns, each a single
870 // directory.
871 //
872 // We compute this set by looking at files that we've previously observed.
873 // This may miss changed to directories that we haven't observed, but that
874 // shouldn't matter as there is nothing to invalidate (if a directory falls
875 // in forest, etc).
876 //
877 // (A previous iteration created a single glob pattern holding a union of
878 // all the directories, but this was found to cause VS Code to get stuck
879 // for several minutes after a buffer was saved twice in a workspace that
880 // had >8000 watched directories.)
881 //
882 // Some clients (notably coc.nvim, which uses watchman for globs) perform
883 // poorly with a large list of individual directories.
884 s.addKnownSubdirs(patterns, dirs)
885 }
886
887 return patterns
888 }
889
890 func (s *Snapshot) addKnownSubdirs(patterns map[protocol.RelativePattern]unit, wsDirs []string) {
891 s.mu.Lock()
892 defer s.mu.Unlock()
893
894 for dir := range s.files.getDirs().All() {
895 for _, wsDir := range wsDirs {
896 if pathutil.InDir(wsDir, dir) {
897 patterns[protocol.RelativePattern{Pattern: filepath.ToSlash(dir)}] = unit{}
898 }
899 }
900 }
901 }
902
903 // watchSubdirs reports whether gopls should request separate file watchers for
904 // each relevant subdirectory. This is necessary only for clients (namely VS
905 // Code) that do not send notifications for individual files in a directory
906 // when the entire directory is deleted.
907 func (s *Snapshot) watchSubdirs() bool {
908 switch p := s.Options().SubdirWatchPatterns; p {
909 case settings.SubdirWatchPatternsOn:
910 return true
911 case settings.SubdirWatchPatternsOff:
912 return false
913 case settings.SubdirWatchPatternsAuto:
914 // See the documentation of InternalOptions.SubdirWatchPatterns for an
915 // explanation of why VS Code gets a different default value here.
916 //
917 // Unfortunately, there is no authoritative list of client names, nor any
918 // requirements that client names do not change. We should update the VS
919 // Code extension to set a default value of "subdirWatchPatterns" to "on",
920 // so that this workaround is only temporary.
921 switch s.Options().ClientInfo.Name {
922 case "Visual Studio Code", "Visual Studio Code - Insiders":
923 return true
924 default:
925 return false
926 }
927 default:
928 bug.Reportf("invalid subdirWatchPatterns: %q", p)
929 return false
930 }
931 }
932
933 // filesInDir returns all files observed by the snapshot that are contained in
934 // a directory with the provided URI.
935 func (s *Snapshot) filesInDir(uri protocol.DocumentURI) []protocol.DocumentURI {
936 s.mu.Lock()
937 defer s.mu.Unlock()
938
939 dir := uri.Path()
940 if !s.files.getDirs().Contains(dir) {
941 return nil
942 }
943 var files []protocol.DocumentURI
944 for uri := range s.files.all() {
945 if pathutil.InDir(dir, uri.Path()) {
946 files = append(files, uri)
947 }
948 }
949 return files
950 }
951
952 // WorkspaceMetadata returns a new, unordered slice containing
953 // metadata for all ordinary and test packages (but not
954 // intermediate test variants) in the workspace.
955 //
956 // The workspace is the set of modules typically defined by a
957 // go.work file. It is not transitively closed: for example,
958 // the standard library is not usually part of the workspace
959 // even though every module in the workspace depends on it.
960 //
961 // Operations that must inspect all the dependencies of the
962 // workspace packages should instead use AllMetadata.
963 func (s *Snapshot) WorkspaceMetadata(ctx context.Context) ([]*metadata.Package, error) {
964 if err := s.awaitLoaded(ctx); err != nil {
965 return nil, err
966 }
967
968 s.mu.Lock()
969 defer s.mu.Unlock()
970
971 meta := make([]*metadata.Package, 0, s.workspacePackages.Len())
972 for id := range s.workspacePackages.All() {
973 meta = append(meta, s.meta.Packages[id])
974 }
975 return meta, nil
976 }
977
978 // WorkspacePackages returns the map of workspace package to package path.
979 //
980 // The set of workspace packages is updated after every load. A package is a
981 // workspace package if and only if it is present in this map.
982 func (s *Snapshot) WorkspacePackages() immutable.Map[PackageID, PackagePath] {
983 s.mu.Lock()
984 defer s.mu.Unlock()
985 return s.workspacePackages
986 }
987
988 // IsWorkspacePackage reports whether the given package ID refers to a
989 // workspace package for the Snapshot. It is equivalent to looking up the
990 // package in [Snapshot.WorkspacePackages].
991 func (s *Snapshot) IsWorkspacePackage(id PackageID) bool {
992 s.mu.Lock()
993 defer s.mu.Unlock()
994 _, ok := s.workspacePackages.Value(id)
995 return ok
996 }
997
998 // AllMetadata returns a new unordered array of metadata for
999 // all packages known to this snapshot, which includes the
1000 // packages of all workspace modules plus their transitive
1001 // import dependencies.
1002 //
1003 // It may also contain ad-hoc packages for standalone files.
1004 // It includes all test variants.
1005 //
1006 // TODO(rfindley): Replace usage of function this with s.LoadMetadataGraph().
1007 func (s *Snapshot) AllMetadata(ctx context.Context) ([]*metadata.Package, error) {
1008 g, err := s.LoadMetadataGraph(ctx)
1009 if err != nil {
1010 return nil, err
1011 }
1012 return moremaps.ValueSlice(g.Packages), nil
1013 }
1014
1015 // GoModForFile returns the URI of the go.mod file for the given URI.
1016 //
1017 // TODO(rfindley): clarify that this is only active modules. Or update to just
1018 // use findRootPattern.
1019 func (s *Snapshot) GoModForFile(uri protocol.DocumentURI) protocol.DocumentURI {
1020 return moduleForURI(s.view.workspaceModFiles, uri)
1021 }
1022
1023 func moduleForURI(modFiles map[protocol.DocumentURI]struct{}, uri protocol.DocumentURI) protocol.DocumentURI {
1024 var match protocol.DocumentURI
1025 for modURI := range modFiles {
1026 if !modURI.Dir().Encloses(uri) {
1027 continue
1028 }
1029 if len(modURI) > len(match) {
1030 match = modURI
1031 }
1032 }
1033 return match
1034 }
1035
1036 // Metadata returns the metadata for the specified package,
1037 // or nil if it was not found.
1038 func (s *Snapshot) Metadata(id PackageID) *metadata.Package {
1039 s.mu.Lock()
1040 defer s.mu.Unlock()
1041 return s.meta.Packages[id]
1042 }
1043
1044 // clearShouldLoad clears package IDs that no longer need to be reloaded after
1045 // scopes has been loaded.
1046 func (s *Snapshot) clearShouldLoad(scopes ...loadScope) {
1047 s.mu.Lock()
1048 defer s.mu.Unlock()
1049
1050 for _, scope := range scopes {
1051 switch scope := scope.(type) {
1052 case packageLoadScope:
1053 scopePath := PackagePath(scope)
1054 var toDelete []PackageID
1055 for id, pkgPaths := range s.shouldLoad.All() {
1056 if slices.Contains(pkgPaths, scopePath) {
1057 toDelete = append(toDelete, id)
1058 }
1059 }
1060 for _, id := range toDelete {
1061 s.shouldLoad.Delete(id)
1062 }
1063 case fileLoadScope:
1064 uri := protocol.DocumentURI(scope)
1065 for _, pkg := range s.meta.ForFile[uri] {
1066 s.shouldLoad.Delete(pkg.ID)
1067 }
1068 }
1069 }
1070 }
1071
1072 // ReadFile returns a File for the given URI. If the file is unknown it is added
1073 // to the managed set.
1074 //
1075 // ReadFile succeeds even if the file does not exist. A non-nil error return
1076 // indicates some type of internal error, for example if ctx is cancelled.
1077 func (s *Snapshot) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error) {
1078 s.mu.Lock()
1079 defer s.mu.Unlock()
1080
1081 return lockedSnapshot{s}.ReadFile(ctx, uri)
1082 }
1083
1084 // lockedSnapshot implements the file.Source interface, while holding s.mu.
1085 //
1086 // TODO(rfindley): This unfortunate type had been eliminated, but it had to be
1087 // restored to fix golang/go#65801. We should endeavor to remove it again.
1088 type lockedSnapshot struct {
1089 s *Snapshot
1090 }
1091
1092 func (s lockedSnapshot) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error) {
1093 fh, ok := s.s.files.get(uri)
1094 if !ok {
1095 var err error
1096 fh, err = s.s.view.fs.ReadFile(ctx, uri)
1097 if err != nil {
1098 return nil, err
1099 }
1100 s.s.files.set(uri, fh)
1101 }
1102 return fh, nil
1103 }
1104
1105 // preloadFiles delegates to the view FileSource to read the requested uris in
1106 // parallel, without holding the snapshot lock.
1107 func (s *Snapshot) preloadFiles(ctx context.Context, uris []protocol.DocumentURI) {
1108 files := make([]file.Handle, len(uris))
1109 var wg sync.WaitGroup
1110 iolimit := make(chan struct{}, 20) // I/O concurrency limiting semaphore
1111 for i, uri := range uris {
1112 wg.Add(1)
1113 iolimit <- struct{}{}
1114 go func(i int, uri protocol.DocumentURI) {
1115 defer wg.Done()
1116 fh, err := s.view.fs.ReadFile(ctx, uri)
1117 <-iolimit
1118 if err != nil && ctx.Err() == nil {
1119 event.Error(ctx, fmt.Sprintf("reading %s", uri), err)
1120 return
1121 }
1122 files[i] = fh
1123 }(i, uri)
1124 }
1125 wg.Wait()
1126
1127 s.mu.Lock()
1128 defer s.mu.Unlock()
1129
1130 for i, fh := range files {
1131 if fh == nil {
1132 continue // error logged above
1133 }
1134 uri := uris[i]
1135 if _, ok := s.files.get(uri); !ok {
1136 s.files.set(uri, fh)
1137 }
1138 }
1139 }
1140
1141 // IsOpen returns whether the editor currently has a file open.
1142 func (s *Snapshot) IsOpen(uri protocol.DocumentURI) bool {
1143 s.mu.Lock()
1144 defer s.mu.Unlock()
1145
1146 fh, _ := s.files.get(uri)
1147 _, open := fh.(*overlay)
1148 return open
1149 }
1150
1151 // MetadataGraph returns the current metadata graph for the Snapshot.
1152 func (s *Snapshot) MetadataGraph() *metadata.Graph {
1153 s.mu.Lock()
1154 defer s.mu.Unlock()
1155 return s.meta
1156 }
1157
1158 // LoadMetadataGraph is like [Snapshot.MetadataGraph], but awaits snapshot reloading.
1159 func (s *Snapshot) LoadMetadataGraph(ctx context.Context) (*metadata.Graph, error) {
1160 if err := s.awaitLoaded(ctx); err != nil {
1161 return nil, err
1162 }
1163 return s.MetadataGraph(), nil
1164 }
1165
1166 // InitializationError returns the last error from initialization.
1167 func (s *Snapshot) InitializationError() *InitializationError {
1168 s.mu.Lock()
1169 defer s.mu.Unlock()
1170 return s.initialErr
1171 }
1172
1173 // awaitLoaded awaits initialization and package reloading, and returns
1174 // ctx.Err().
1175 func (s *Snapshot) awaitLoaded(ctx context.Context) error {
1176 // Do not return results until the snapshot's view has been initialized.
1177 s.AwaitInitialized(ctx)
1178 s.reloadWorkspace(ctx)
1179 return ctx.Err()
1180 }
1181
1182 // AwaitInitialized waits until the snapshot's view is initialized.
1183 func (s *Snapshot) AwaitInitialized(ctx context.Context) {
1184 select {
1185 case <-ctx.Done():
1186 return
1187 case <-s.view.initialWorkspaceLoad:
1188 }
1189 // We typically prefer to run something as intensive as the IWL without
1190 // blocking. I'm not sure if there is a way to do that here.
1191 s.initialize(ctx, false)
1192 }
1193
1194 // reloadWorkspace reloads the metadata for all invalidated workspace packages.
1195 func (s *Snapshot) reloadWorkspace(ctx context.Context) {
1196 if ctx.Err() != nil {
1197 return
1198 }
1199
1200 var scopes []loadScope
1201 var seen map[PackagePath]bool
1202 s.mu.Lock()
1203 for _, pkgPaths := range s.shouldLoad.All() {
1204 for _, pkgPath := range pkgPaths {
1205 if seen == nil {
1206 seen = make(map[PackagePath]bool)
1207 }
1208 if seen[pkgPath] {
1209 continue
1210 }
1211 seen[pkgPath] = true
1212 scopes = append(scopes, packageLoadScope(pkgPath))
1213 }
1214 }
1215 s.mu.Unlock()
1216
1217 if len(scopes) == 0 {
1218 return
1219 }
1220
1221 // For an ad-hoc view, we cannot reload by package path. Just reload the view.
1222 if s.view.typ == AdHocView {
1223 scopes = []loadScope{viewLoadScope{}}
1224 }
1225
1226 err := s.load(ctx, NoNetwork, scopes...)
1227
1228 // Unless the context was canceled, set "shouldLoad" to false for all
1229 // of the metadata we attempted to load.
1230 if !errors.Is(err, context.Canceled) {
1231 s.clearShouldLoad(scopes...)
1232 if err != nil {
1233 event.Error(ctx, "reloading workspace", err, s.Labels()...)
1234 }
1235 }
1236 }
1237
1238 func (s *Snapshot) orphanedFileDiagnostics(ctx context.Context, overlays []*overlay) ([]*Diagnostic, error) {
1239 if err := s.awaitLoaded(ctx); err != nil {
1240 return nil, err
1241 }
1242
1243 var diagnostics []*Diagnostic
1244 var orphaned []*overlay
1245 searchOverlays:
1246 for _, o := range overlays {
1247 uri := o.URI()
1248 if s.IsBuiltin(uri) || s.FileKind(o) != file.Go {
1249 continue
1250 }
1251 mps, err := s.MetadataForFile(ctx, uri, true)
1252 if err != nil {
1253 return nil, err
1254 }
1255 for _, mp := range mps {
1256 if !metadata.IsCommandLineArguments(mp.ID) || mp.Standalone {
1257 continue searchOverlays
1258 }
1259 }
1260
1261 // With zero-config gopls (golang/go#57979), orphaned file diagnostics
1262 // include diagnostics for orphaned files -- not just diagnostics relating
1263 // to the reason the files are opened.
1264 //
1265 // This is because orphaned files are never considered part of a workspace
1266 // package: if they are loaded by a view, that view is arbitrary, and they
1267 // may be loaded by multiple views. If they were to be diagnosed by
1268 // multiple views, their diagnostics may become inconsistent.
1269 if len(mps) > 0 {
1270 diags, err := s.PackageDiagnostics(ctx, mps[0].ID)
1271 if err != nil {
1272 return nil, err
1273 }
1274 diagnostics = append(diagnostics, diags[uri]...)
1275 }
1276 orphaned = append(orphaned, o)
1277 }
1278
1279 if len(orphaned) == 0 {
1280 return nil, nil
1281 }
1282
1283 loadedModFiles := make(map[protocol.DocumentURI]struct{}) // all mod files, including dependencies
1284 ignoredFiles := make(map[protocol.DocumentURI]bool) // files reported in packages.Package.IgnoredFiles
1285
1286 g := s.MetadataGraph()
1287 for _, meta := range g.Packages {
1288 if meta.Module != nil && meta.Module.GoMod != "" {
1289 gomod := protocol.URIFromPath(meta.Module.GoMod)
1290 loadedModFiles[gomod] = struct{}{}
1291 }
1292 for _, ignored := range meta.IgnoredFiles {
1293 ignoredFiles[ignored] = true
1294 }
1295 }
1296
1297 initialErr := s.InitializationError()
1298
1299 for _, fh := range orphaned {
1300 pgf, rng, ok := orphanedFileDiagnosticRange(ctx, s.view.parseCache, fh)
1301 if !ok {
1302 continue // e.g. cancellation or parse error
1303 }
1304
1305 var (
1306 msg string // if non-empty, report a diagnostic with this message
1307 suggestedFixes []SuggestedFix // associated fixes, if any
1308 )
1309 if initialErr != nil {
1310 msg = fmt.Sprintf("initialization failed: %v", initialErr.MainError)
1311 } else if goMod, err := findRootPattern(ctx, fh.URI().Dir(), "go.mod", file.Source(s)); err == nil && goMod != "" {
1312 // Check if the file's module should be loadable by considering both
1313 // loaded modules and workspace modules. The former covers cases where
1314 // the file is outside of a workspace folder. The latter covers cases
1315 // where the file is inside a workspace module, but perhaps no packages
1316 // were loaded for that module.
1317 _, loadedMod := loadedModFiles[goMod]
1318 _, workspaceMod := s.view.workspaceModFiles[goMod]
1319 // If we have a relevant go.mod file, check whether the file is orphaned
1320 // due to its go.mod file being inactive. We could also offer a
1321 // prescriptive diagnostic in the case that there is no go.mod file, but
1322 // it is harder to be precise in that case, and less important.
1323 if !(loadedMod || workspaceMod) {
1324 modDir := goMod.DirPath()
1325 viewDir := s.view.folder.Dir.Path()
1326
1327 // When the module is underneath the view dir, we offer
1328 // "use all modules" quick-fixes.
1329 inDir := pathutil.InDir(viewDir, modDir)
1330
1331 if rel, err := filepath.Rel(viewDir, modDir); err == nil {
1332 modDir = rel
1333 }
1334
1335 var fix string
1336 if s.view.folder.Env.GoVersion >= 18 {
1337 if s.view.gowork != "" {
1338 fix = fmt.Sprintf("To fix this problem, you can add this module to your go.work file (%s)", s.view.gowork)
1339
1340 cmd := command.NewRunGoWorkCommandCommand("Run `go work use`", command.RunGoWorkArgs{
1341 ViewID: s.view.ID(),
1342 Args: []string{"use", modDir},
1343 })
1344 suggestedFixes = append(suggestedFixes, SuggestedFix{
1345 Title: "Use this module in your go.work file",
1346 Command: cmd,
1347 ActionKind: protocol.QuickFix,
1348 })
1349
1350 if inDir {
1351 cmd := command.NewRunGoWorkCommandCommand("Run `go work use -r`", command.RunGoWorkArgs{
1352 ViewID: s.view.ID(),
1353 Args: []string{"use", "-r", "."},
1354 })
1355 suggestedFixes = append(suggestedFixes, SuggestedFix{
1356 Title: "Use all modules in your workspace",
1357 Command: cmd,
1358 ActionKind: protocol.QuickFix,
1359 })
1360 }
1361 } else {
1362 fix = "To fix this problem, you can add a go.work file that uses this directory."
1363
1364 cmd := command.NewRunGoWorkCommandCommand("Run `go work init && go work use`", command.RunGoWorkArgs{
1365 ViewID: s.view.ID(),
1366 InitFirst: true,
1367 Args: []string{"use", modDir},
1368 })
1369 suggestedFixes = []SuggestedFix{
1370 {
1371 Title: "Add a go.work file using this module",
1372 Command: cmd,
1373 ActionKind: protocol.QuickFix,
1374 },
1375 }
1376
1377 if inDir {
1378 cmd := command.NewRunGoWorkCommandCommand("Run `go work init && go work use -r`", command.RunGoWorkArgs{
1379 ViewID: s.view.ID(),
1380 InitFirst: true,
1381 Args: []string{"use", "-r", "."},
1382 })
1383 suggestedFixes = append(suggestedFixes, SuggestedFix{
1384 Title: "Add a go.work file using all modules in your workspace",
1385 Command: cmd,
1386 ActionKind: protocol.QuickFix,
1387 })
1388 }
1389 }
1390 } else {
1391 fix = `To work with multiple modules simultaneously, please upgrade to Go 1.18 or
1392 later, reinstall gopls, and use a go.work file.`
1393 }
1394
1395 msg = fmt.Sprintf(`This file is within module %q, which is not included in your workspace.
1396 %s
1397 See the documentation for more information on setting up your workspace:
1398 https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.`, modDir, fix)
1399 }
1400 }
1401
1402 if msg == "" {
1403 if ignoredFiles[fh.URI()] {
1404 // TODO(rfindley): use the constraint package to check if the file
1405 // _actually_ satisfies the current build context.
1406 hasConstraint := false
1407 walkConstraints(pgf.File, func(constraint.Expr) bool {
1408 hasConstraint = true
1409 return false
1410 })
1411 var fix string
1412 if hasConstraint {
1413 fix = `This file may be excluded due to its build tags; try adding "-tags=<build tag>" to your gopls "buildFlags" configuration
1414 See the documentation for more information on working with build tags:
1415 https://github.com/golang/tools/blob/master/gopls/doc/settings.md#buildflags.`
1416 } else if strings.Contains(fh.URI().Base(), "_") {
1417 fix = `This file may be excluded due to its GOOS/GOARCH, or other build constraints.`
1418 } else {
1419 fix = `This file is ignored by your gopls build.` // we don't know why
1420 }
1421 msg = fmt.Sprintf("No packages found for open file %s.\n%s", fh.URI().Path(), fix)
1422 } else {
1423 // Fall back: we're not sure why the file is orphaned.
1424 // TODO(rfindley): we could do better here, diagnosing the lack of a
1425 // go.mod file and malformed file names (see the perc%ent marker test).
1426 msg = fmt.Sprintf("No packages found for open file %s.", fh.URI().Path())
1427 }
1428 }
1429
1430 if msg != "" {
1431 d := &Diagnostic{
1432 URI: fh.URI(),
1433 Range: rng,
1434 Severity: protocol.SeverityWarning,
1435 Source: ListError,
1436 Message: msg,
1437 SuggestedFixes: suggestedFixes,
1438 }
1439 if ok := bundleLazyFixes(d); !ok {
1440 bug.Reportf("failed to bundle quick fixes for %v", d)
1441 }
1442 // Only report diagnostics if we detect an actual exclusion.
1443 diagnostics = append(diagnostics, d)
1444 }
1445 }
1446 return diagnostics, nil
1447 }
1448
1449 // orphanedFileDiagnosticRange returns the position to use for orphaned file diagnostics.
1450 // We only warn about an orphaned file if it is well-formed enough to actually
1451 // be part of a package. Otherwise, we need more information.
1452 func orphanedFileDiagnosticRange(ctx context.Context, cache *parseCache, fh file.Handle) (*parsego.File, protocol.Range, bool) {
1453 pgfs, err := cache.parseFiles(ctx, token.NewFileSet(), parsego.Header, false, fh)
1454 if err != nil {
1455 return nil, protocol.Range{}, false
1456 }
1457 pgf := pgfs[0]
1458 name := pgf.File.Name
1459 if !name.Pos().IsValid() {
1460 return nil, protocol.Range{}, false
1461 }
1462 rng, err := pgf.PosRange(name.Pos(), name.End())
1463 if err != nil {
1464 return nil, protocol.Range{}, false
1465 }
1466 return pgf, rng, true
1467 }
1468
1469 // TODO(golang/go#53756): this function needs to consider more than just the
1470 // absolute URI, for example:
1471 // - the position of /vendor/ with respect to the relevant module root
1472 // - whether or not go.work is in use (as vendoring isn't supported in workspace mode)
1473 //
1474 // Most likely, each call site of inVendor needs to be reconsidered to
1475 // understand and correctly implement the desired behavior.
1476 func inVendor(uri protocol.DocumentURI) bool {
1477 _, after, found := strings.Cut(string(uri), "/vendor/")
1478 // Only subdirectories of /vendor/ are considered vendored
1479 // (/vendor/a/foo.go is vendored, /vendor/foo.go is not).
1480 return found && strings.Contains(after, "/")
1481 }
1482
1483 // clone copies state from the receiver into a new Snapshot, applying the given
1484 // state changes.
1485 //
1486 // The caller of clone must call Snapshot.decref on the returned
1487 // snapshot when they are finished using it.
1488 //
1489 // The resulting bool reports whether the change invalidates any derived
1490 // diagnostics for the snapshot, for example because it invalidates Packages or
1491 // parsed go.mod files. This is used to mark a view as needing diagnosis in the
1492 // server.
1493 //
1494 // TODO(rfindley): long term, it may be better to move responsibility for
1495 // diagnostics into the Snapshot (e.g. a Snapshot.Diagnostics method), at which
1496 // point the Snapshot could be responsible for tracking and forwarding a
1497 // 'viewsToDiagnose' field. As is, this field is instead externalized in the
1498 // server.viewsToDiagnose map. Moving it to the snapshot would entirely
1499 // eliminate any 'relevance' heuristics from Session.DidModifyFiles, but would
1500 // also require more strictness about diagnostic dependencies. For example,
1501 // template.Diagnostics currently re-parses every time: there is no Snapshot
1502 // data responsible for providing these diagnostics.
1503 func (s *Snapshot) clone(ctx, bgCtx context.Context, changed StateChange, done func()) (*Snapshot, bool) {
1504 changedFiles := changed.Files
1505 ctx, stop := event.Start(ctx, "cache.snapshot.clone")
1506 defer stop()
1507
1508 s.mu.Lock()
1509 defer s.mu.Unlock()
1510
1511 // TODO(rfindley): reorganize this function to make the derivation of
1512 // needsDiagnosis clearer.
1513 needsDiagnosis := len(changed.CompilerOptDetails) > 0 || len(changed.ModuleUpgrades) > 0 || len(changed.Vulns) > 0
1514
1515 bgCtx, cancel := context.WithCancel(bgCtx)
1516 result := &Snapshot{
1517 sequenceID: s.sequenceID + 1,
1518 store: s.store,
1519 refcount: 1, // Snapshots are born referenced.
1520 done: done,
1521 view: s.view,
1522 backgroundCtx: bgCtx,
1523 cancel: cancel,
1524 builtin: s.builtin,
1525 initialized: s.initialized,
1526 initialErr: s.initialErr,
1527 packages: s.packages.Clone(),
1528 fullAnalysisKeys: s.fullAnalysisKeys.Clone(),
1529 factyAnalysisKeys: s.factyAnalysisKeys.Clone(),
1530 files: s.files.clone(changedFiles),
1531 workspacePackages: s.workspacePackages,
1532 shouldLoad: s.shouldLoad.Clone(), // not cloneWithout: shouldLoad is cleared on loads
1533 unloadableFiles: s.unloadableFiles.Clone(), // not cloneWithout: typing in a file doesn't necessarily make it loadable
1534 parseModHandles: cloneWithout(s.parseModHandles, changedFiles, &needsDiagnosis),
1535 parseWorkHandles: cloneWithout(s.parseWorkHandles, changedFiles, &needsDiagnosis),
1536 modTidyHandles: cloneWithout(s.modTidyHandles, changedFiles, &needsDiagnosis),
1537 modWhyHandles: cloneWithout(s.modWhyHandles, changedFiles, &needsDiagnosis),
1538 modVulnHandles: cloneWithout(s.modVulnHandles, changedFiles, &needsDiagnosis),
1539 moduleUpgrades: cloneWith(s.moduleUpgrades, changed.ModuleUpgrades),
1540 vulns: cloneWith(s.vulns, changed.Vulns),
1541 }
1542
1543 // Compute the new set of packages for which we want compiler
1544 // optimization details, after applying changed.CompilerOptDetails.
1545 if len(s.compilerOptDetails) > 0 || len(changed.CompilerOptDetails) > 0 {
1546 newCompilerOptDetails := make(map[protocol.DocumentURI]unit)
1547 for dir := range s.compilerOptDetails {
1548 if _, ok := changed.CompilerOptDetails[dir]; !ok {
1549 newCompilerOptDetails[dir] = unit{} // no change
1550 }
1551 }
1552 for dir, want := range changed.CompilerOptDetails {
1553 if want {
1554 newCompilerOptDetails[dir] = unit{}
1555 }
1556 }
1557 if len(newCompilerOptDetails) > 0 {
1558 result.compilerOptDetails = newCompilerOptDetails
1559 }
1560 }
1561
1562 reinit := false
1563 for _, mod := range changed.Modifications {
1564 // Changes to vendor tree may require reinitialization,
1565 // either because of an initialization error
1566 // (e.g. "inconsistent vendoring detected"), or because
1567 // one or more modules may have moved into or out of the
1568 // vendor tree after 'go mod vendor' or 'rm -fr vendor/'.
1569 //
1570 // In this case, we consider the actual modification to see if was a creation
1571 // or deletion.
1572 //
1573 // TODO(rfindley): revisit the location of this check.
1574 if inVendor(mod.URI) && (mod.Action == file.Create || mod.Action == file.Delete) ||
1575 strings.HasSuffix(string(mod.URI), "/vendor/modules.txt") {
1576
1577 reinit = true
1578 break
1579 }
1580
1581 // Changes to workspace files, as a rule of thumb, should require reinitialization. Since their behavior
1582 // is generally user-defined, we want to do something sensible by re-triggering a query to the active GOPACKAGESDRIVER,
1583 // and reloading the state of the workspace.
1584 if isWorkspaceFile(mod.URI, s.view.folder.Options.WorkspaceFiles) && (mod.Action == file.Save || mod.OnDisk) {
1585 reinit = true
1586 break
1587 }
1588 }
1589
1590 // Collect observed file handles for changed URIs from the old snapshot, if
1591 // they exist. Importantly, we don't call ReadFile here: consider the case
1592 // where a file is added on disk; we don't want to read the newly added file
1593 // into the old snapshot, as that will break our change detection below.
1594 //
1595 // TODO(rfindley): it may be more accurate to rely on the modification type
1596 // here, similarly to what we do for vendored files above. If we happened not
1597 // to have read a file in the previous snapshot, that's not the same as it
1598 // actually being created.
1599 oldFiles := make(map[protocol.DocumentURI]file.Handle)
1600 for uri := range changedFiles {
1601 if fh, ok := s.files.get(uri); ok {
1602 oldFiles[uri] = fh
1603 }
1604 }
1605 // changedOnDisk determines if the new file handle may have changed on disk.
1606 // It over-approximates, returning true if the new file is saved and either
1607 // the old file wasn't saved, or the on-disk contents changed.
1608 //
1609 // oldFH may be nil.
1610 changedOnDisk := func(oldFH, newFH file.Handle) bool {
1611 if !newFH.SameContentsOnDisk() {
1612 return false
1613 }
1614 if oe, ne := (oldFH != nil && fileExists(oldFH)), fileExists(newFH); !oe || !ne {
1615 return oe != ne
1616 }
1617 return !oldFH.SameContentsOnDisk() || oldFH.Identity() != newFH.Identity()
1618 }
1619
1620 // Reinitialize if any workspace mod file has changed on disk.
1621 for uri, newFH := range changedFiles {
1622 if _, ok := result.view.workspaceModFiles[uri]; ok && changedOnDisk(oldFiles[uri], newFH) {
1623 reinit = true
1624 }
1625 }
1626
1627 // Finally, process sumfile changes that may affect loading.
1628 for uri, newFH := range changedFiles {
1629 if !changedOnDisk(oldFiles[uri], newFH) {
1630 continue // like with go.mod files, we only reinit when things change on disk
1631 }
1632 dir, base := filepath.Split(uri.Path())
1633 if base == "go.work.sum" && s.view.typ == GoWorkView && dir == s.view.gowork.DirPath() {
1634 reinit = true
1635 }
1636 if base == "go.sum" {
1637 modURI := protocol.URIFromPath(filepath.Join(dir, "go.mod"))
1638 if _, active := result.view.workspaceModFiles[modURI]; active {
1639 reinit = true
1640 }
1641 }
1642 }
1643
1644 // The snapshot should be initialized if either s was uninitialized, or we've
1645 // detected a change that triggers reinitialization.
1646 if reinit {
1647 result.initialized = false
1648 needsDiagnosis = true
1649 }
1650
1651 // directIDs keeps track of package IDs that have directly changed.
1652 // Note: this is not a set, it's a map from id to invalidateMetadata.
1653 directIDs := map[PackageID]bool{}
1654
1655 // Invalidate all package metadata if the workspace module has changed.
1656 if reinit {
1657 for k := range s.meta.Packages {
1658 // TODO(rfindley): this seems brittle; can we just start over?
1659 directIDs[k] = true
1660 }
1661 }
1662
1663 // Compute invalidations based on file changes.
1664 anyImportDeleted := false // import deletions can resolve cycles
1665 anyFileOpenedOrClosed := false // opened files affect workspace packages
1666 anyPkgFileChanged := false // adding a file to a package can resolve missing dependencies
1667
1668 for uri, newFH := range changedFiles {
1669 // The original FileHandle for this URI is cached on the snapshot.
1670 oldFH := oldFiles[uri] // may be nil
1671 _, oldOpen := oldFH.(*overlay)
1672 _, newOpen := newFH.(*overlay)
1673
1674 // TODO(rfindley): consolidate with 'metadataChanges' logic below, which
1675 // also considers existential changes.
1676 anyFileOpenedOrClosed = anyFileOpenedOrClosed || (oldOpen != newOpen)
1677 anyPkgFileChanged = anyPkgFileChanged || (oldFH == nil || !fileExists(oldFH)) && fileExists(newFH)
1678
1679 // If uri is a Go file, check if it has changed in a way that would
1680 // invalidate metadata. Note that we can't use s.view.FileKind here,
1681 // because the file type that matters is not what the *client* tells us,
1682 // but what the Go command sees.
1683 var invalidateMetadata, pkgFileChanged, importDeleted bool
1684 if strings.HasSuffix(uri.Path(), ".go") {
1685 invalidateMetadata, pkgFileChanged, importDeleted = metadataChanges(ctx, s, oldFH, newFH)
1686 }
1687 if invalidateMetadata {
1688 // If this is a metadata-affecting change, perhaps a reload will succeed.
1689 result.unloadableFiles.Remove(uri)
1690 needsDiagnosis = true
1691 }
1692
1693 invalidateMetadata = invalidateMetadata || reinit
1694 anyImportDeleted = anyImportDeleted || importDeleted
1695 anyPkgFileChanged = anyPkgFileChanged || pkgFileChanged
1696
1697 // Mark all of the package IDs containing the given file.
1698 filePackageIDs := invalidatedPackageIDs(uri, s.meta.ForFile, pkgFileChanged)
1699 for id := range filePackageIDs {
1700 directIDs[id] = directIDs[id] || invalidateMetadata // may insert 'false'
1701 }
1702
1703 // Invalidate the previous modTidyHandle if any of the files have been
1704 // saved or if any of the metadata has been invalidated.
1705 //
1706 // TODO(rfindley): this seems like too-aggressive invalidation of mod
1707 // results. We should instead thread through overlays to the Go command
1708 // invocation and only run this if invalidateMetadata (and perhaps then
1709 // still do it less frequently).
1710 if invalidateMetadata || fileWasSaved(oldFH, newFH) {
1711 // Only invalidate mod tidy results for the most relevant modfile in the
1712 // workspace. This is a potentially lossy optimization for workspaces
1713 // with many modules (such as google-cloud-go, which has 145 modules as
1714 // of writing).
1715 //
1716 // While it is theoretically possible that a change in workspace module A
1717 // could affect the mod-tidiness of workspace module B (if B transitively
1718 // requires A), such changes are probably unlikely and not worth the
1719 // penalty of re-running go mod tidy for everything. Note that mod tidy
1720 // ignores GOWORK, so the two modules would have to be related by a chain
1721 // of replace directives.
1722 //
1723 // We could improve accuracy by inspecting replace directives, using
1724 // overlays in go mod tidy, and/or checking for metadata changes from the
1725 // on-disk content.
1726 //
1727 // Note that we iterate the modTidyHandles map here, rather than e.g.
1728 // using nearestModFile, because we don't have access to an accurate
1729 // FileSource at this point in the snapshot clone.
1730 const onlyInvalidateMostRelevant = true
1731 if onlyInvalidateMostRelevant {
1732 deleteMostRelevantModFile(result.modTidyHandles, uri)
1733 } else {
1734 result.modTidyHandles.Clear()
1735 }
1736
1737 // TODO(rfindley): should we apply the above heuristic to mod vuln or mod
1738 // why handles as well?
1739 //
1740 // TODO(rfindley): no tests fail if I delete the line below.
1741 result.modWhyHandles.Clear()
1742 result.modVulnHandles.Clear()
1743 }
1744 }
1745
1746 // Deleting an import can cause list errors due to import cycles to be
1747 // resolved. The best we can do without parsing the list error message is to
1748 // hope that list errors may have been resolved by a deleted import.
1749 //
1750 // We could do better by parsing the list error message. We already do this
1751 // to assign a better range to the list error, but for such critical
1752 // functionality as metadata, it's better to be conservative until it proves
1753 // impractical.
1754 //
1755 // We could also do better by looking at which imports were deleted and
1756 // trying to find cycles they are involved in. This fails when the file goes
1757 // from an unparsable state to a parseable state, as we don't have a
1758 // starting point to compare with.
1759 if anyImportDeleted {
1760 for id, mp := range s.meta.Packages {
1761 if len(mp.Errors) > 0 {
1762 directIDs[id] = true
1763 }
1764 }
1765 }
1766
1767 // Adding a file can resolve missing dependencies from existing packages.
1768 //
1769 // We could be smart here and try to guess which packages may have been
1770 // fixed, but until that proves necessary, just invalidate metadata for any
1771 // package with missing dependencies.
1772 if anyPkgFileChanged {
1773 for id, mp := range s.meta.Packages {
1774 for _, impID := range mp.DepsByImpPath {
1775 if impID == "" { // missing import
1776 directIDs[id] = true
1777 break
1778 }
1779 }
1780 }
1781 }
1782
1783 // Invalidate reverse dependencies too.
1784 // idsToInvalidate keeps track of transitive reverse dependencies.
1785 // If an ID is present in the map, invalidate its types.
1786 // If an ID's value is true, invalidate its metadata too.
1787 idsToInvalidate := map[PackageID]bool{}
1788 var addRevDeps func(PackageID, bool)
1789 addRevDeps = func(id PackageID, invalidateMetadata bool) {
1790 current, seen := idsToInvalidate[id]
1791 newInvalidateMetadata := current || invalidateMetadata
1792
1793 // If we've already seen this ID, and the value of invalidate
1794 // metadata has not changed, we can return early.
1795 if seen && current == newInvalidateMetadata {
1796 return
1797 }
1798 idsToInvalidate[id] = newInvalidateMetadata
1799 for _, rdep := range s.meta.ImportedBy[id] {
1800 addRevDeps(rdep.ID, invalidateMetadata)
1801 }
1802 }
1803 for id, invalidateMetadata := range directIDs {
1804 addRevDeps(id, invalidateMetadata)
1805 }
1806
1807 // Invalidated package information.
1808 for id, invalidateMetadata := range idsToInvalidate {
1809 // See the [packageHandle] documentation for more details about this
1810 // invalidation.
1811 if ph, ok := result.packages.Get(id); ok {
1812 needsDiagnosis = true
1813
1814 // Always invalidate analysis keys, as we do not implement fine-grained
1815 // invalidation for analysis.
1816 result.fullAnalysisKeys.Delete(id)
1817 result.factyAnalysisKeys.Delete(id)
1818
1819 if invalidateMetadata {
1820 result.packages.Delete(id)
1821 } else {
1822 // If the package was just invalidated by a dependency, its local
1823 // inputs are still valid.
1824 ph = ph.clone()
1825 if _, ok := directIDs[id]; ok {
1826 ph.state = validMetadata // local inputs changed
1827 } else {
1828 ph.state = min(ph.state, validLocalData) // a dependency changed
1829 }
1830 result.packages.Set(id, ph, nil)
1831 }
1832 }
1833 }
1834
1835 // Compute which metadata updates are required. We only need to invalidate
1836 // packages directly containing the affected file, and only if it changed in
1837 // a relevant way.
1838 metadataUpdates := make(map[PackageID]*metadata.Package)
1839 for id, mp := range s.meta.Packages {
1840 invalidateMetadata := idsToInvalidate[id]
1841
1842 // For metadata that has been newly invalidated, capture package paths
1843 // requiring reloading in the shouldLoad map.
1844 if invalidateMetadata && !metadata.IsCommandLineArguments(mp.ID) {
1845 needsReload := []PackagePath{mp.PkgPath}
1846 if mp.ForTest != "" && mp.ForTest != mp.PkgPath {
1847 // When reloading test variants, always reload their ForTest package as
1848 // well. Otherwise, we may miss test variants in the resulting load.
1849 //
1850 // TODO(rfindley): is this actually sufficient? Is it possible that
1851 // other test variants may be invalidated? Either way, we should
1852 // determine exactly what needs to be reloaded here.
1853 needsReload = append(needsReload, mp.ForTest)
1854 }
1855 result.shouldLoad.Set(id, needsReload, nil)
1856 }
1857
1858 // Check whether the metadata should be deleted.
1859 if invalidateMetadata {
1860 needsDiagnosis = true
1861 metadataUpdates[id] = nil
1862 continue
1863 }
1864 }
1865
1866 // Update metadata, if necessary.
1867 result.meta = s.meta.Update(metadataUpdates)
1868
1869 // Update workspace and active packages, if necessary.
1870 if result.meta != s.meta || anyFileOpenedOrClosed {
1871 needsDiagnosis = true
1872 result.workspacePackages = computeWorkspacePackagesLocked(ctx, result, result.meta)
1873 } else {
1874 result.workspacePackages = s.workspacePackages
1875 }
1876
1877 return result, needsDiagnosis
1878 }
1879
1880 // cloneWithout clones m then deletes from it the keys of changes.
1881 //
1882 // The optional didDelete variable is set to true if there were deletions.
1883 func cloneWithout[K constraints.Ordered, V1, V2 any](m *persistent.Map[K, V1], changes map[K]V2, didDelete *bool) *persistent.Map[K, V1] {
1884 m2 := m.Clone()
1885 for k := range changes {
1886 if m2.Delete(k) && didDelete != nil {
1887 *didDelete = true
1888 }
1889 }
1890 return m2
1891 }
1892
1893 // cloneWith clones m then inserts the changes into it.
1894 func cloneWith[K constraints.Ordered, V any](m *persistent.Map[K, V], changes map[K]V) *persistent.Map[K, V] {
1895 m2 := m.Clone()
1896 for k, v := range changes {
1897 m2.Set(k, v, nil)
1898 }
1899 return m2
1900 }
1901
1902 // deleteMostRelevantModFile deletes the mod file most likely to be the mod
1903 // file for the changed URI, if it exists.
1904 //
1905 // Specifically, this is the longest mod file path in a directory containing
1906 // changed. This might not be accurate if there is another mod file closer to
1907 // changed that happens not to be present in the map, but that's OK: the goal
1908 // of this function is to guarantee that IF the nearest mod file is present in
1909 // the map, it is invalidated.
1910 func deleteMostRelevantModFile(m *persistent.Map[protocol.DocumentURI, *memoize.Promise], changed protocol.DocumentURI) {
1911 var mostRelevant protocol.DocumentURI
1912 changedFile := changed.Path()
1913
1914 for modURI := range m.All() {
1915 if len(modURI) > len(mostRelevant) {
1916 if pathutil.InDir(modURI.DirPath(), changedFile) {
1917 mostRelevant = modURI
1918 }
1919 }
1920 }
1921 if mostRelevant != "" {
1922 m.Delete(mostRelevant)
1923 }
1924 }
1925
1926 // invalidatedPackageIDs returns all packages invalidated by a change to uri.
1927 // If we haven't seen this URI before, we guess based on files in the same
1928 // directory. This is of course incorrect in build systems where packages are
1929 // not organized by directory.
1930 //
1931 // If packageFileChanged is set, the file is either a new file, or has a new
1932 // package name. In this case, all known packages in the directory will be
1933 // invalidated.
1934 func invalidatedPackageIDs(uri protocol.DocumentURI, known map[protocol.DocumentURI][]*metadata.Package, packageFileChanged bool) map[PackageID]struct{} {
1935 invalidated := make(map[PackageID]struct{})
1936
1937 // At a minimum, we invalidate packages known to contain uri.
1938 for _, pkg := range known[uri] {
1939 invalidated[pkg.ID] = struct{}{}
1940 }
1941
1942 // If the file didn't move to a new package, we should only invalidate the
1943 // packages it is currently contained inside.
1944 if !packageFileChanged && len(invalidated) > 0 {
1945 return invalidated
1946 }
1947
1948 // This is a file we don't yet know about, or which has moved packages. Guess
1949 // relevant packages by considering files in the same directory.
1950
1951 // Cache of FileInfo to avoid unnecessary stats for multiple files in the
1952 // same directory.
1953 stats := make(map[string]struct {
1954 os.FileInfo
1955 error
1956 })
1957 getInfo := func(dir string) (os.FileInfo, error) {
1958 if res, ok := stats[dir]; ok {
1959 return res.FileInfo, res.error
1960 }
1961 fi, err := os.Stat(dir)
1962 stats[dir] = struct {
1963 os.FileInfo
1964 error
1965 }{fi, err}
1966 return fi, err
1967 }
1968 dir := uri.DirPath()
1969 fi, err := getInfo(dir)
1970 if err == nil {
1971 // Aggregate all possibly relevant package IDs.
1972 for knownURI, pkgs := range known {
1973 knownDir := knownURI.DirPath()
1974 knownFI, err := getInfo(knownDir)
1975 if err != nil {
1976 continue
1977 }
1978 if os.SameFile(fi, knownFI) {
1979 for _, pkg := range pkgs {
1980 invalidated[pkg.ID] = struct{}{}
1981 }
1982 }
1983 }
1984 }
1985 return invalidated
1986 }
1987
1988 // fileWasSaved reports whether the FileHandle passed in has been saved. It
1989 // accomplishes this by checking to see if the original and current FileHandles
1990 // are both overlays, and if the current FileHandle is saved while the original
1991 // FileHandle was not saved.
1992 func fileWasSaved(originalFH, currentFH file.Handle) bool {
1993 if originalFH == nil || currentFH == nil {
1994 return true // should not happen for valid file handles
1995 }
1996
1997 // If the file identity has not changed, the content has not changed.
1998 // Therefore, the "saved" state (from the perspective of go mod tidy)
1999 // has not changed.
2000 if originalFH.Identity() == currentFH.Identity() {
2001 return false
2002 }
2003 c, ok := currentFH.(*overlay)
2004 if !ok || c == nil {
2005 return true
2006 }
2007 o, ok := originalFH.(*overlay)
2008 if !ok || o == nil {
2009 return c.saved
2010 }
2011 return !o.saved && c.saved
2012 }
2013
2014 // metadataChanges detects features of the change from oldFH->newFH that may
2015 // affect package metadata.
2016 //
2017 // It uses lockedSnapshot to access cached parse information. lockedSnapshot
2018 // must be locked.
2019 //
2020 // The result parameters have the following meaning:
2021 // - invalidate means that package metadata for packages containing the file
2022 // should be invalidated.
2023 // - pkgFileChanged means that the file->package associates for the file have
2024 // changed (possibly because the file is new, or because its package name has
2025 // changed).
2026 // - importDeleted means that an import has been deleted, or we can't
2027 // determine if an import was deleted due to errors.
2028 func metadataChanges(ctx context.Context, lockedSnapshot *Snapshot, oldFH, newFH file.Handle) (invalidate, pkgFileChanged, importDeleted bool) {
2029 if oe, ne := oldFH != nil && fileExists(oldFH), fileExists(newFH); !oe || !ne { // existential changes
2030 changed := oe != ne
2031 return changed, changed, !ne // we don't know if an import was deleted
2032 }
2033
2034 // If the file hasn't changed, there's no need to reload.
2035 if oldFH.Identity() == newFH.Identity() {
2036 return false, false, false
2037 }
2038
2039 fset := token.NewFileSet()
2040 // Parse headers to compare package names and imports.
2041 oldHeads, oldErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Header, false, oldFH)
2042 newHeads, newErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Header, false, newFH)
2043
2044 if oldErr != nil || newErr != nil {
2045 errChanged := (oldErr == nil) != (newErr == nil)
2046 return errChanged, errChanged, (newErr != nil) // we don't know if an import was deleted
2047 }
2048
2049 oldHead := oldHeads[0]
2050 newHead := newHeads[0]
2051
2052 // `go list` fails completely if the file header cannot be parsed. If we go
2053 // from a non-parsing state to a parsing state, we should reload.
2054 if oldHead.ParseErr != nil && newHead.ParseErr == nil {
2055 return true, true, true // We don't know what changed, so fall back on full invalidation.
2056 }
2057
2058 // If a package name has changed, the set of package imports may have changed
2059 // in ways we can't detect here. Assume an import has been deleted.
2060 if oldHead.File.Name.Name != newHead.File.Name.Name {
2061 return true, true, true
2062 }
2063
2064 // Check whether package imports have changed. Only consider potentially
2065 // valid imports paths.
2066 oldImports := validImportPaths(oldHead.File.Imports)
2067 newImports := validImportPaths(newHead.File.Imports)
2068
2069 for path := range newImports {
2070 if _, ok := oldImports[path]; ok {
2071 delete(oldImports, path)
2072 } else {
2073 invalidate = true // a new, potentially valid import was added
2074 }
2075 }
2076
2077 if len(oldImports) > 0 {
2078 invalidate = true
2079 importDeleted = true
2080 }
2081
2082 // If the change does not otherwise invalidate metadata, get the full ASTs in
2083 // order to check magic comments.
2084 //
2085 // Note: if this affects performance we can probably avoid parsing in the
2086 // common case by first scanning the source for potential comments.
2087 if !invalidate {
2088 origFulls, oldErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Full, false, oldFH)
2089 newFulls, newErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Full, false, newFH)
2090 if oldErr == nil && newErr == nil {
2091 invalidate = magicCommentsChanged(origFulls[0].File, newFulls[0].File)
2092 } else {
2093 // At this point, we shouldn't ever fail to produce a parsego.File, as
2094 // we're already past header parsing.
2095 bug.Reportf("metadataChanges: unparsable file %v (old error: %v, new error: %v)", oldFH.URI(), oldErr, newErr)
2096 }
2097 }
2098
2099 return invalidate, pkgFileChanged, importDeleted
2100 }
2101
2102 func magicCommentsChanged(original *ast.File, current *ast.File) bool {
2103 oldComments := extractMagicComments(original)
2104 newComments := extractMagicComments(current)
2105 if len(oldComments) != len(newComments) {
2106 return true
2107 }
2108 for i := range oldComments {
2109 if oldComments[i] != newComments[i] {
2110 return true
2111 }
2112 }
2113 return false
2114 }
2115
2116 // validImportPaths extracts the set of valid import paths from imports.
2117 func validImportPaths(imports []*ast.ImportSpec) map[string]struct{} {
2118 m := make(map[string]struct{})
2119 for _, spec := range imports {
2120 if path := spec.Path.Value; validImportPath(path) {
2121 m[path] = struct{}{}
2122 }
2123 }
2124 return m
2125 }
2126
2127 func validImportPath(path string) bool {
2128 path, err := strconv.Unquote(path)
2129 if err != nil {
2130 return false
2131 }
2132 if path == "" {
2133 return false
2134 }
2135 if path[len(path)-1] == '/' {
2136 return false
2137 }
2138 return true
2139 }
2140
2141 var buildConstraintOrEmbedRe = regexp.MustCompile(`^//(go:embed|go:build|\s*\+build).*`)
2142
2143 // extractMagicComments finds magic comments that affect metadata in f.
2144 func extractMagicComments(f *ast.File) []string {
2145 var results []string
2146 for _, cg := range f.Comments {
2147 for _, c := range cg.List {
2148 if buildConstraintOrEmbedRe.MatchString(c.Text) {
2149 results = append(results, c.Text)
2150 }
2151 }
2152 }
2153 return results
2154 }
2155
2156 // BuiltinFile returns the pseudo-source file builtins.go,
2157 // parsed with legacy ast.Object resolution.
2158 func (s *Snapshot) BuiltinFile(ctx context.Context) (*parsego.File, error) {
2159 s.AwaitInitialized(ctx)
2160
2161 s.mu.Lock()
2162 builtin := s.builtin
2163 s.mu.Unlock()
2164
2165 if builtin == "" {
2166 return nil, fmt.Errorf("no builtin package for view %s", s.view.folder.Name)
2167 }
2168
2169 fh, err := s.ReadFile(ctx, builtin)
2170 if err != nil {
2171 return nil, err
2172 }
2173 // For the builtin file only, we need syntactic object resolution
2174 // (since we can't type check).
2175 mode := parsego.Full &^ parser.SkipObjectResolution
2176 pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), mode, false, fh)
2177 if err != nil {
2178 return nil, err
2179 }
2180 return pgfs[0], nil
2181 }
2182
2183 // IsBuiltin reports whether uri is part of the builtin package.
2184 func (s *Snapshot) IsBuiltin(uri protocol.DocumentURI) bool {
2185 s.mu.Lock()
2186 defer s.mu.Unlock()
2187 // We should always get the builtin URI in a canonical form, so use simple
2188 // string comparison here. span.CompareURI is too expensive.
2189 return uri == s.builtin
2190 }
2191
2192 func (s *Snapshot) setBuiltin(path string) {
2193 s.mu.Lock()
2194 defer s.mu.Unlock()
2195
2196 s.builtin = protocol.URIFromPath(path)
2197 }
2198
2199 // WantCompilerOptDetails reports whether to compute compiler
2200 // optimization details for packages and tests in the given directory.
2201 func (s *Snapshot) WantCompilerOptDetails(dir protocol.DocumentURI) bool {
2202 _, ok := s.compilerOptDetails[dir]
2203 return ok
2204 }
2205
2206 // A CodeLensSourceFunc is a function that reports CodeLenses (range-associated
2207 // commands) for a given file.
2208 type CodeLensSourceFunc func(context.Context, *Snapshot, file.Handle) ([]protocol.CodeLens, error)