Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / internal / lsp / cache / snapshot.go
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package cache
6
7 import (
8         "bytes"
9         "context"
10         "fmt"
11         "go/ast"
12         "go/token"
13         "go/types"
14         "io"
15         "os"
16         "path/filepath"
17         "sort"
18         "strconv"
19         "strings"
20         "sync"
21
22         "golang.org/x/mod/modfile"
23         "golang.org/x/mod/module"
24         "golang.org/x/tools/go/analysis"
25         "golang.org/x/tools/go/packages"
26         "golang.org/x/tools/internal/event"
27         "golang.org/x/tools/internal/gocommand"
28         "golang.org/x/tools/internal/lsp/debug/tag"
29         "golang.org/x/tools/internal/lsp/source"
30         "golang.org/x/tools/internal/memoize"
31         "golang.org/x/tools/internal/packagesinternal"
32         "golang.org/x/tools/internal/span"
33         "golang.org/x/tools/internal/typesinternal"
34         errors "golang.org/x/xerrors"
35 )
36
37 type snapshot struct {
38         memoize.Arg // allow as a memoize.Function arg
39
40         id   uint64
41         view *View
42
43         // the cache generation that contains the data for this snapshot.
44         generation *memoize.Generation
45
46         // builtin pins the AST and package for builtin.go in memory.
47         builtin *builtinPackageHandle
48
49         // mu guards all of the maps in the snapshot.
50         mu sync.Mutex
51
52         // ids maps file URIs to package IDs.
53         // It may be invalidated on calls to go/packages.
54         ids map[span.URI][]packageID
55
56         // metadata maps file IDs to their associated metadata.
57         // It may invalidated on calls to go/packages.
58         metadata map[packageID]*metadata
59
60         // importedBy maps package IDs to the list of packages that import them.
61         importedBy map[packageID][]packageID
62
63         // files maps file URIs to their corresponding FileHandles.
64         // It may invalidated when a file's content changes.
65         files map[span.URI]source.VersionedFileHandle
66
67         // goFiles maps a parseKey to its parseGoHandle.
68         goFiles map[parseKey]*parseGoHandle
69
70         // packages maps a packageKey to a set of packageHandles to which that file belongs.
71         // It may be invalidated when a file's content changes.
72         packages map[packageKey]*packageHandle
73
74         // actions maps an actionkey to its actionHandle.
75         actions map[actionKey]*actionHandle
76
77         // workspacePackages contains the workspace's packages, which are loaded
78         // when the view is created.
79         workspacePackages map[packageID]packagePath
80
81         // workspaceDirectories are the directories containing workspace packages.
82         // They are the view's root, as well as any replace targets.
83         workspaceDirectories map[span.URI]struct{}
84
85         // unloadableFiles keeps track of files that we've failed to load.
86         unloadableFiles map[span.URI]struct{}
87
88         // parseModHandles keeps track of any ParseModHandles for the snapshot.
89         // The handles need not refer to only the view's go.mod file.
90         parseModHandles map[span.URI]*parseModHandle
91
92         // Preserve go.mod-related handles to avoid garbage-collecting the results
93         // of various calls to the go command. The handles need not refer to only
94         // the view's go.mod file.
95         modTidyHandles    map[span.URI]*modTidyHandle
96         modUpgradeHandles map[span.URI]*modUpgradeHandle
97         modWhyHandles     map[span.URI]*modWhyHandle
98
99         // modules is the set of modules currently in this workspace.
100         modules map[span.URI]*moduleRoot
101
102         // workspaceModuleHandle keeps track of the in-memory representation of the
103         // go.mod file for the workspace module.
104         workspaceModuleHandle *workspaceModuleHandle
105 }
106
107 type packageKey struct {
108         mode source.ParseMode
109         id   packageID
110 }
111
112 type actionKey struct {
113         pkg      packageKey
114         analyzer *analysis.Analyzer
115 }
116
117 func (s *snapshot) ID() uint64 {
118         return s.id
119 }
120
121 func (s *snapshot) View() source.View {
122         return s.view
123 }
124
125 func (s *snapshot) FileSet() *token.FileSet {
126         return s.view.session.cache.fset
127 }
128
129 func (s *snapshot) ModFiles() []span.URI {
130         var uris []span.URI
131         for _, m := range s.modules {
132                 uris = append(uris, m.modURI)
133         }
134         return uris
135 }
136
137 func (s *snapshot) ValidBuildConfiguration() bool {
138         return validBuildConfiguration(s.view.rootURI, &s.view.workspaceInformation, s.modules)
139 }
140
141 // workspaceMode describes the way in which the snapshot's workspace should
142 // be loaded.
143 func (s *snapshot) workspaceMode() workspaceMode {
144         var mode workspaceMode
145
146         // If the view has an invalid configuration, don't build the workspace
147         // module.
148         validBuildConfiguration := s.ValidBuildConfiguration()
149         if !validBuildConfiguration {
150                 return mode
151         }
152         // If the view is not in a module and contains no modules, but still has a
153         // valid workspace configuration, do not create the workspace module.
154         // It could be using GOPATH or a different build system entirely.
155         if len(s.modules) == 0 && validBuildConfiguration {
156                 return mode
157         }
158         mode |= moduleMode
159         options := s.view.Options()
160         // The -modfile flag is available for Go versions >= 1.14.
161         if options.TempModfile && s.view.workspaceInformation.goversion >= 14 {
162                 mode |= tempModfile
163         }
164         // If the user is intentionally limiting their workspace scope, don't
165         // enable multi-module workspace mode.
166         // TODO(rstambler): This should only change the calculation of the root,
167         // not the mode.
168         if !options.ExpandWorkspaceToModule {
169                 return mode
170         }
171         // The workspace module has been disabled by the user.
172         if !options.ExperimentalWorkspaceModule {
173                 return mode
174         }
175         mode |= usesWorkspaceModule
176         return mode
177 }
178
179 // config returns the configuration used for the snapshot's interaction with
180 // the go/packages API. It uses the given working directory.
181 //
182 // TODO(rstambler): go/packages requires that we do not provide overlays for
183 // multiple modules in on config, so buildOverlay needs to filter overlays by
184 // module.
185 func (s *snapshot) config(ctx context.Context, dir string) *packages.Config {
186         s.view.optionsMu.Lock()
187         env, buildFlags := s.view.envLocked()
188         verboseOutput := s.view.options.VerboseOutput
189         s.view.optionsMu.Unlock()
190
191         cfg := &packages.Config{
192                 Context:    ctx,
193                 Dir:        dir,
194                 Env:        append(append([]string{}, env...), "GO111MODULE="+s.view.go111module),
195                 BuildFlags: append([]string{}, buildFlags...),
196                 Mode: packages.NeedName |
197                         packages.NeedFiles |
198                         packages.NeedCompiledGoFiles |
199                         packages.NeedImports |
200                         packages.NeedDeps |
201                         packages.NeedTypesSizes |
202                         packages.NeedModule,
203                 Fset:    s.view.session.cache.fset,
204                 Overlay: s.buildOverlay(),
205                 ParseFile: func(*token.FileSet, string, []byte) (*ast.File, error) {
206                         panic("go/packages must not be used to parse files")
207                 },
208                 Logf: func(format string, args ...interface{}) {
209                         if verboseOutput {
210                                 event.Log(ctx, fmt.Sprintf(format, args...))
211                         }
212                 },
213                 Tests: true,
214         }
215         // We want to type check cgo code if go/types supports it.
216         if typesinternal.SetUsesCgo(&types.Config{}) {
217                 cfg.Mode |= packages.LoadMode(packagesinternal.TypecheckCgo)
218         }
219         packagesinternal.SetGoCmdRunner(cfg, s.view.session.gocmdRunner)
220         return cfg
221 }
222
223 func (s *snapshot) RunGoCommandDirect(ctx context.Context, wd, verb string, args []string) error {
224         cfg := s.config(ctx, wd)
225         _, runner, inv, cleanup, err := s.goCommandInvocation(ctx, cfg, false, verb, args)
226         if err != nil {
227                 return err
228         }
229         defer cleanup()
230
231         _, err = runner.Run(ctx, *inv)
232         return err
233 }
234
235 func (s *snapshot) runGoCommandWithConfig(ctx context.Context, cfg *packages.Config, verb string, args []string) (*bytes.Buffer, error) {
236         _, runner, inv, cleanup, err := s.goCommandInvocation(ctx, cfg, true, verb, args)
237         if err != nil {
238                 return nil, err
239         }
240         defer cleanup()
241
242         return runner.Run(ctx, *inv)
243 }
244
245 func (s *snapshot) RunGoCommandPiped(ctx context.Context, wd, verb string, args []string, stdout, stderr io.Writer) error {
246         cfg := s.config(ctx, wd)
247         _, runner, inv, cleanup, err := s.goCommandInvocation(ctx, cfg, true, verb, args)
248         if err != nil {
249                 return err
250         }
251         defer cleanup()
252         return runner.RunPiped(ctx, *inv, stdout, stderr)
253 }
254
255 func (s *snapshot) goCommandInvocation(ctx context.Context, cfg *packages.Config, allowTempModfile bool, verb string, args []string) (tmpURI span.URI, runner *gocommand.Runner, inv *gocommand.Invocation, cleanup func(), err error) {
256         cleanup = func() {} // fallback
257         modURI := s.GoModForFile(ctx, span.URIFromPath(cfg.Dir))
258
259         inv = &gocommand.Invocation{
260                 Verb:       verb,
261                 Args:       args,
262                 Env:        cfg.Env,
263                 WorkingDir: cfg.Dir,
264         }
265
266         if allowTempModfile && s.workspaceMode()&tempModfile != 0 {
267                 if modURI == "" {
268                         return "", nil, nil, cleanup, fmt.Errorf("no go.mod file found in %s", cfg.Dir)
269                 }
270                 modFH, err := s.GetFile(ctx, modURI)
271                 if err != nil {
272                         return "", nil, nil, cleanup, err
273                 }
274                 // Use the go.sum if it happens to be available.
275                 sumFH, _ := s.sumFH(ctx, modFH)
276
277                 tmpURI, cleanup, err = tempModFile(modFH, sumFH)
278                 if err != nil {
279                         return "", nil, nil, cleanup, err
280                 }
281                 inv.ModFile = tmpURI.Filename()
282         }
283
284         var modContent []byte
285         if modURI != "" {
286                 modFH, err := s.GetFile(ctx, modURI)
287                 if err != nil {
288                         return "", nil, nil, cleanup, err
289                 }
290                 modContent, err = modFH.Read()
291                 if err != nil {
292                         return "", nil, nil, nil, err
293                 }
294         }
295         modMod, err := s.needsModEqualsMod(ctx, modURI, modContent)
296         if err != nil {
297                 return "", nil, nil, cleanup, err
298         }
299         if modMod {
300                 inv.ModFlag = "mod"
301         }
302
303         runner = packagesinternal.GetGoCmdRunner(cfg)
304         return tmpURI, runner, inv, cleanup, nil
305 }
306
307 func (s *snapshot) buildOverlay() map[string][]byte {
308         s.mu.Lock()
309         defer s.mu.Unlock()
310
311         overlays := make(map[string][]byte)
312         for uri, fh := range s.files {
313                 overlay, ok := fh.(*overlay)
314                 if !ok {
315                         continue
316                 }
317                 if overlay.saved {
318                         continue
319                 }
320                 // TODO(rstambler): Make sure not to send overlays outside of the current view.
321                 overlays[uri.Filename()] = overlay.text
322         }
323         return overlays
324 }
325
326 func hashUnsavedOverlays(files map[span.URI]source.VersionedFileHandle) string {
327         var unsaved []string
328         for uri, fh := range files {
329                 if overlay, ok := fh.(*overlay); ok && !overlay.saved {
330                         unsaved = append(unsaved, uri.Filename())
331                 }
332         }
333         sort.Strings(unsaved)
334         return hashContents([]byte(strings.Join(unsaved, "")))
335 }
336
337 func (s *snapshot) PackagesForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode) ([]source.Package, error) {
338         ctx = event.Label(ctx, tag.URI.Of(uri))
339
340         phs, err := s.packageHandlesForFile(ctx, uri, mode)
341         if err != nil {
342                 return nil, err
343         }
344         var pkgs []source.Package
345         for _, ph := range phs {
346                 pkg, err := ph.check(ctx, s)
347                 if err != nil {
348                         return nil, err
349                 }
350                 pkgs = append(pkgs, pkg)
351         }
352         return pkgs, nil
353 }
354
355 func (s *snapshot) PackageForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode, pkgPolicy source.PackageFilter) (source.Package, error) {
356         ctx = event.Label(ctx, tag.URI.Of(uri))
357
358         phs, err := s.packageHandlesForFile(ctx, uri, mode)
359         if err != nil {
360                 return nil, err
361         }
362
363         if len(phs) < 1 {
364                 return nil, errors.Errorf("no packages")
365         }
366
367         ph := phs[0]
368         for _, handle := range phs[1:] {
369                 switch pkgPolicy {
370                 case source.WidestPackage:
371                         if ph == nil || len(handle.CompiledGoFiles()) > len(ph.CompiledGoFiles()) {
372                                 ph = handle
373                         }
374                 case source.NarrowestPackage:
375                         if ph == nil || len(handle.CompiledGoFiles()) < len(ph.CompiledGoFiles()) {
376                                 ph = handle
377                         }
378                 }
379         }
380         if ph == nil {
381                 return nil, errors.Errorf("no packages in input")
382         }
383
384         return ph.check(ctx, s)
385 }
386
387 func (s *snapshot) packageHandlesForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode) ([]*packageHandle, error) {
388         // Check if we should reload metadata for the file. We don't invalidate IDs
389         // (though we should), so the IDs will be a better source of truth than the
390         // metadata. If there are no IDs for the file, then we should also reload.
391         fh, err := s.GetFile(ctx, uri)
392         if err != nil {
393                 return nil, err
394         }
395         if fh.Kind() != source.Go {
396                 return nil, fmt.Errorf("no packages for non-Go file %s", uri)
397         }
398         ids := s.getIDsForURI(uri)
399         reload := len(ids) == 0
400         for _, id := range ids {
401                 // Reload package metadata if any of the metadata has missing
402                 // dependencies, in case something has changed since the last time we
403                 // reloaded it.
404                 if m := s.getMetadata(id); m == nil {
405                         reload = true
406                         break
407                 }
408                 // TODO(golang/go#36918): Previously, we would reload any package with
409                 // missing dependencies. This is expensive and results in too many
410                 // calls to packages.Load. Determine what we should do instead.
411         }
412         if reload {
413                 if err := s.load(ctx, fileURI(uri)); err != nil {
414                         return nil, err
415                 }
416         }
417         // Get the list of IDs from the snapshot again, in case it has changed.
418         var phs []*packageHandle
419         for _, id := range s.getIDsForURI(uri) {
420                 var parseModes []source.ParseMode
421                 switch mode {
422                 case source.TypecheckAll:
423                         if s.workspaceParseMode(id) == source.ParseFull {
424                                 parseModes = []source.ParseMode{source.ParseFull}
425                         } else {
426                                 parseModes = []source.ParseMode{source.ParseExported, source.ParseFull}
427                         }
428                 case source.TypecheckFull:
429                         parseModes = []source.ParseMode{source.ParseFull}
430                 case source.TypecheckWorkspace:
431                         parseModes = []source.ParseMode{s.workspaceParseMode(id)}
432                 }
433
434                 for _, parseMode := range parseModes {
435                         ph, err := s.buildPackageHandle(ctx, id, parseMode)
436                         if err != nil {
437                                 return nil, err
438                         }
439                         phs = append(phs, ph)
440                 }
441         }
442
443         return phs, nil
444 }
445
446 func (s *snapshot) GetReverseDependencies(ctx context.Context, id string) ([]source.Package, error) {
447         if err := s.awaitLoaded(ctx); err != nil {
448                 return nil, err
449         }
450         ids := make(map[packageID]struct{})
451         s.transitiveReverseDependencies(packageID(id), ids)
452
453         // Make sure to delete the original package ID from the map.
454         delete(ids, packageID(id))
455
456         var pkgs []source.Package
457         for id := range ids {
458                 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
459                 if err != nil {
460                         return nil, err
461                 }
462                 pkgs = append(pkgs, pkg)
463         }
464         return pkgs, nil
465 }
466
467 func (s *snapshot) checkedPackage(ctx context.Context, id packageID, mode source.ParseMode) (*pkg, error) {
468         ph, err := s.buildPackageHandle(ctx, id, mode)
469         if err != nil {
470                 return nil, err
471         }
472         return ph.check(ctx, s)
473 }
474
475 // transitiveReverseDependencies populates the uris map with file URIs
476 // belonging to the provided package and its transitive reverse dependencies.
477 func (s *snapshot) transitiveReverseDependencies(id packageID, ids map[packageID]struct{}) {
478         if _, ok := ids[id]; ok {
479                 return
480         }
481         if s.getMetadata(id) == nil {
482                 return
483         }
484         ids[id] = struct{}{}
485         importedBy := s.getImportedBy(id)
486         for _, parentID := range importedBy {
487                 s.transitiveReverseDependencies(parentID, ids)
488         }
489 }
490
491 func (s *snapshot) getGoFile(key parseKey) *parseGoHandle {
492         s.mu.Lock()
493         defer s.mu.Unlock()
494         return s.goFiles[key]
495 }
496
497 func (s *snapshot) addGoFile(key parseKey, pgh *parseGoHandle) *parseGoHandle {
498         s.mu.Lock()
499         defer s.mu.Unlock()
500         if existing, ok := s.goFiles[key]; ok {
501                 return existing
502         }
503         s.goFiles[key] = pgh
504         return pgh
505 }
506
507 func (s *snapshot) getParseModHandle(uri span.URI) *parseModHandle {
508         s.mu.Lock()
509         defer s.mu.Unlock()
510         return s.parseModHandles[uri]
511 }
512
513 func (s *snapshot) getModWhyHandle(uri span.URI) *modWhyHandle {
514         s.mu.Lock()
515         defer s.mu.Unlock()
516         return s.modWhyHandles[uri]
517 }
518
519 func (s *snapshot) getModUpgradeHandle(uri span.URI) *modUpgradeHandle {
520         s.mu.Lock()
521         defer s.mu.Unlock()
522         return s.modUpgradeHandles[uri]
523 }
524
525 func (s *snapshot) getModTidyHandle(uri span.URI) *modTidyHandle {
526         s.mu.Lock()
527         defer s.mu.Unlock()
528         return s.modTidyHandles[uri]
529 }
530
531 func (s *snapshot) getImportedBy(id packageID) []packageID {
532         s.mu.Lock()
533         defer s.mu.Unlock()
534         return s.getImportedByLocked(id)
535 }
536
537 func (s *snapshot) getImportedByLocked(id packageID) []packageID {
538         // If we haven't rebuilt the import graph since creating the snapshot.
539         if len(s.importedBy) == 0 {
540                 s.rebuildImportGraph()
541         }
542         return s.importedBy[id]
543 }
544
545 func (s *snapshot) clearAndRebuildImportGraph() {
546         s.mu.Lock()
547         defer s.mu.Unlock()
548
549         // Completely invalidate the original map.
550         s.importedBy = make(map[packageID][]packageID)
551         s.rebuildImportGraph()
552 }
553
554 func (s *snapshot) rebuildImportGraph() {
555         for id, m := range s.metadata {
556                 for _, importID := range m.deps {
557                         s.importedBy[importID] = append(s.importedBy[importID], id)
558                 }
559         }
560 }
561
562 func (s *snapshot) addPackageHandle(ph *packageHandle) *packageHandle {
563         s.mu.Lock()
564         defer s.mu.Unlock()
565
566         // If the package handle has already been cached,
567         // return the cached handle instead of overriding it.
568         if ph, ok := s.packages[ph.packageKey()]; ok {
569                 return ph
570         }
571         s.packages[ph.packageKey()] = ph
572         return ph
573 }
574
575 func (s *snapshot) workspacePackageIDs() (ids []packageID) {
576         s.mu.Lock()
577         defer s.mu.Unlock()
578
579         for id := range s.workspacePackages {
580                 ids = append(ids, id)
581         }
582         return ids
583 }
584
585 func (s *snapshot) WorkspaceDirectories(ctx context.Context) []span.URI {
586         s.mu.Lock()
587         defer s.mu.Unlock()
588
589         var dirs []span.URI
590         for d := range s.workspaceDirectories {
591                 dirs = append(dirs, d)
592         }
593         return dirs
594 }
595
596 func (s *snapshot) WorkspacePackages(ctx context.Context) ([]source.Package, error) {
597         if err := s.awaitLoaded(ctx); err != nil {
598                 return nil, err
599         }
600         var pkgs []source.Package
601         for _, pkgID := range s.workspacePackageIDs() {
602                 pkg, err := s.checkedPackage(ctx, pkgID, s.workspaceParseMode(pkgID))
603                 if err != nil {
604                         return nil, err
605                 }
606                 pkgs = append(pkgs, pkg)
607         }
608         return pkgs, nil
609 }
610
611 func (s *snapshot) KnownPackages(ctx context.Context) ([]source.Package, error) {
612         if err := s.awaitLoaded(ctx); err != nil {
613                 return nil, err
614         }
615
616         // The WorkspaceSymbols implementation relies on this function returning
617         // workspace packages first.
618         ids := s.workspacePackageIDs()
619         s.mu.Lock()
620         for id := range s.metadata {
621                 if _, ok := s.workspacePackages[id]; ok {
622                         continue
623                 }
624                 ids = append(ids, id)
625         }
626         s.mu.Unlock()
627
628         var pkgs []source.Package
629         for _, id := range ids {
630                 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
631                 if err != nil {
632                         return nil, err
633                 }
634                 pkgs = append(pkgs, pkg)
635         }
636         return pkgs, nil
637 }
638
639 func (s *snapshot) CachedImportPaths(ctx context.Context) (map[string]source.Package, error) {
640         // Don't reload workspace package metadata.
641         // This function is meant to only return currently cached information.
642         s.AwaitInitialized(ctx)
643
644         s.mu.Lock()
645         defer s.mu.Unlock()
646
647         results := map[string]source.Package{}
648         for _, ph := range s.packages {
649                 cachedPkg, err := ph.cached(s.generation)
650                 if err != nil {
651                         continue
652                 }
653                 for importPath, newPkg := range cachedPkg.imports {
654                         if oldPkg, ok := results[string(importPath)]; ok {
655                                 // Using the same trick as NarrowestPackage, prefer non-variants.
656                                 if len(newPkg.compiledGoFiles) < len(oldPkg.(*pkg).compiledGoFiles) {
657                                         results[string(importPath)] = newPkg
658                                 }
659                         } else {
660                                 results[string(importPath)] = newPkg
661                         }
662                 }
663         }
664         return results, nil
665 }
666
667 func (s *snapshot) GoModForFile(ctx context.Context, uri span.URI) span.URI {
668         var match span.URI
669         for _, m := range s.modules {
670                 if !isSubdirectory(m.rootURI.Filename(), uri.Filename()) {
671                         continue
672                 }
673                 if len(m.modURI) > len(match) {
674                         match = m.modURI
675                 }
676         }
677         return match
678 }
679
680 func (s *snapshot) getPackage(id packageID, mode source.ParseMode) *packageHandle {
681         s.mu.Lock()
682         defer s.mu.Unlock()
683
684         key := packageKey{
685                 id:   id,
686                 mode: mode,
687         }
688         return s.packages[key]
689 }
690
691 func (s *snapshot) getActionHandle(id packageID, m source.ParseMode, a *analysis.Analyzer) *actionHandle {
692         s.mu.Lock()
693         defer s.mu.Unlock()
694
695         key := actionKey{
696                 pkg: packageKey{
697                         id:   id,
698                         mode: m,
699                 },
700                 analyzer: a,
701         }
702         return s.actions[key]
703 }
704
705 func (s *snapshot) addActionHandle(ah *actionHandle) *actionHandle {
706         s.mu.Lock()
707         defer s.mu.Unlock()
708
709         key := actionKey{
710                 analyzer: ah.analyzer,
711                 pkg: packageKey{
712                         id:   ah.pkg.m.id,
713                         mode: ah.pkg.mode,
714                 },
715         }
716         if ah, ok := s.actions[key]; ok {
717                 return ah
718         }
719         s.actions[key] = ah
720         return ah
721 }
722
723 func (s *snapshot) getIDsForURI(uri span.URI) []packageID {
724         s.mu.Lock()
725         defer s.mu.Unlock()
726
727         return s.ids[uri]
728 }
729
730 func (s *snapshot) getMetadataForURILocked(uri span.URI) (metadata []*metadata) {
731         // TODO(matloob): uri can be a file or directory. Should we update the mappings
732         // to map directories to their contained packages?
733
734         for _, id := range s.ids[uri] {
735                 if m, ok := s.metadata[id]; ok {
736                         metadata = append(metadata, m)
737                 }
738         }
739         return metadata
740 }
741
742 func (s *snapshot) getMetadata(id packageID) *metadata {
743         s.mu.Lock()
744         defer s.mu.Unlock()
745
746         return s.metadata[id]
747 }
748
749 func (s *snapshot) addID(uri span.URI, id packageID) {
750         s.mu.Lock()
751         defer s.mu.Unlock()
752
753         for i, existingID := range s.ids[uri] {
754                 // TODO: We should make sure not to set duplicate IDs,
755                 // and instead panic here. This can be done by making sure not to
756                 // reset metadata information for packages we've already seen.
757                 if existingID == id {
758                         return
759                 }
760                 // If we are setting a real ID, when the package had only previously
761                 // had a command-line-arguments ID, we should just replace it.
762                 if existingID == "command-line-arguments" {
763                         s.ids[uri][i] = id
764                         // Delete command-line-arguments if it was a workspace package.
765                         delete(s.workspacePackages, existingID)
766                         return
767                 }
768         }
769         s.ids[uri] = append(s.ids[uri], id)
770 }
771
772 func (s *snapshot) isWorkspacePackage(id packageID) (packagePath, bool) {
773         s.mu.Lock()
774         defer s.mu.Unlock()
775
776         scope, ok := s.workspacePackages[id]
777         return scope, ok
778 }
779
780 func (s *snapshot) FindFile(uri span.URI) source.VersionedFileHandle {
781         f, err := s.view.getFile(uri)
782         if err != nil {
783                 return nil
784         }
785
786         s.mu.Lock()
787         defer s.mu.Unlock()
788
789         return s.files[f.URI()]
790 }
791
792 // GetVersionedFile returns a File for the given URI. If the file is unknown it
793 // is added to the managed set.
794 //
795 // GetFile succeeds even if the file does not exist. A non-nil error return
796 // indicates some type of internal error, for example if ctx is cancelled.
797 func (s *snapshot) GetVersionedFile(ctx context.Context, uri span.URI) (source.VersionedFileHandle, error) {
798         f, err := s.view.getFile(uri)
799         if err != nil {
800                 return nil, err
801         }
802
803         s.mu.Lock()
804         defer s.mu.Unlock()
805         return s.getFileLocked(ctx, f)
806 }
807
808 // GetFile implements the fileSource interface by wrapping GetVersionedFile.
809 func (s *snapshot) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) {
810         return s.GetVersionedFile(ctx, uri)
811 }
812
813 func (s *snapshot) getFileLocked(ctx context.Context, f *fileBase) (source.VersionedFileHandle, error) {
814         if fh, ok := s.files[f.URI()]; ok {
815                 return fh, nil
816         }
817
818         fh, err := s.view.session.cache.getFile(ctx, f.URI())
819         if err != nil {
820                 return nil, err
821         }
822         closed := &closedFile{fh}
823         s.files[f.URI()] = closed
824         return closed, nil
825 }
826
827 func (s *snapshot) IsOpen(uri span.URI) bool {
828         s.mu.Lock()
829         defer s.mu.Unlock()
830
831         _, open := s.files[uri].(*overlay)
832         return open
833 }
834
835 func (s *snapshot) awaitLoaded(ctx context.Context) error {
836         // Do not return results until the snapshot's view has been initialized.
837         s.AwaitInitialized(ctx)
838
839         if err := s.reloadWorkspace(ctx); err != nil {
840                 return err
841         }
842         if err := s.reloadOrphanedFiles(ctx); err != nil {
843                 return err
844         }
845         // If we still have absolutely no metadata, check if the view failed to
846         // initialize and return any errors.
847         // TODO(rstambler): Should we clear the error after we return it?
848         s.mu.Lock()
849         defer s.mu.Unlock()
850         if len(s.metadata) == 0 {
851                 return s.view.initializedErr
852         }
853         return nil
854 }
855
856 func (s *snapshot) AwaitInitialized(ctx context.Context) {
857         select {
858         case <-ctx.Done():
859                 return
860         case <-s.view.initialized:
861         }
862         // We typically prefer to run something as intensive as the IWL without
863         // blocking. I'm not sure if there is a way to do that here.
864         s.initialize(ctx, false)
865 }
866
867 // reloadWorkspace reloads the metadata for all invalidated workspace packages.
868 func (s *snapshot) reloadWorkspace(ctx context.Context) error {
869         // If the view's build configuration is invalid, we cannot reload by
870         // package path. Just reload the directory instead.
871         if !s.ValidBuildConfiguration() {
872                 return s.load(ctx, viewLoadScope("LOAD_INVALID_VIEW"))
873         }
874
875         // See which of the workspace packages are missing metadata.
876         s.mu.Lock()
877         pkgPathSet := map[packagePath]struct{}{}
878         for id, pkgPath := range s.workspacePackages {
879                 // Don't try to reload "command-line-arguments" directly.
880                 if pkgPath == "command-line-arguments" {
881                         continue
882                 }
883                 if s.metadata[id] == nil {
884                         pkgPathSet[pkgPath] = struct{}{}
885                 }
886         }
887         s.mu.Unlock()
888
889         if len(pkgPathSet) == 0 {
890                 return nil
891         }
892         var pkgPaths []interface{}
893         for pkgPath := range pkgPathSet {
894                 pkgPaths = append(pkgPaths, pkgPath)
895         }
896         return s.load(ctx, pkgPaths...)
897 }
898
899 func (s *snapshot) reloadOrphanedFiles(ctx context.Context) error {
900         // When we load ./... or a package path directly, we may not get packages
901         // that exist only in overlays. As a workaround, we search all of the files
902         // available in the snapshot and reload their metadata individually using a
903         // file= query if the metadata is unavailable.
904         scopes := s.orphanedFileScopes()
905         if len(scopes) == 0 {
906                 return nil
907         }
908
909         err := s.load(ctx, scopes...)
910
911         // If we failed to load some files, i.e. they have no metadata,
912         // mark the failures so we don't bother retrying until the file's
913         // content changes.
914         //
915         // TODO(rstambler): This may be an overestimate if the load stopped
916         // early for an unrelated errors. Add a fallback?
917         //
918         // Check for context cancellation so that we don't incorrectly mark files
919         // as unloadable, but don't return before setting all workspace packages.
920         if ctx.Err() == nil && err != nil {
921                 event.Error(ctx, "reloadOrphanedFiles: failed to load", err, tag.Query.Of(scopes))
922                 s.mu.Lock()
923                 for _, scope := range scopes {
924                         uri := span.URI(scope.(fileURI))
925                         if s.getMetadataForURILocked(uri) == nil {
926                                 s.unloadableFiles[uri] = struct{}{}
927                         }
928                 }
929                 s.mu.Unlock()
930         }
931         return nil
932 }
933
934 func (s *snapshot) orphanedFileScopes() []interface{} {
935         s.mu.Lock()
936         defer s.mu.Unlock()
937
938         scopeSet := make(map[span.URI]struct{})
939         for uri, fh := range s.files {
940                 // Don't try to reload metadata for go.mod files.
941                 if fh.Kind() != source.Go {
942                         continue
943                 }
944                 // If the URI doesn't belong to this view, then it's not in a workspace
945                 // package and should not be reloaded directly.
946                 if !contains(s.view.session.viewsOf(uri), s.view) {
947                         continue
948                 }
949                 // Don't reload metadata for files we've already deemed unloadable.
950                 if _, ok := s.unloadableFiles[uri]; ok {
951                         continue
952                 }
953                 if s.getMetadataForURILocked(uri) == nil {
954                         scopeSet[uri] = struct{}{}
955                 }
956         }
957         var scopes []interface{}
958         for uri := range scopeSet {
959                 scopes = append(scopes, fileURI(uri))
960         }
961         return scopes
962 }
963
964 func contains(views []*View, view *View) bool {
965         for _, v := range views {
966                 if v == view {
967                         return true
968                 }
969         }
970         return false
971 }
972
973 func generationName(v *View, snapshotID uint64) string {
974         return fmt.Sprintf("v%v/%v", v.id, snapshotID)
975 }
976
977 func (s *snapshot) clone(ctx context.Context, withoutURIs map[span.URI]source.VersionedFileHandle, forceReloadMetadata bool) (*snapshot, reinitializeView) {
978         s.mu.Lock()
979         defer s.mu.Unlock()
980
981         newGen := s.view.session.cache.store.Generation(generationName(s.view, s.id+1))
982         result := &snapshot{
983                 id:                    s.id + 1,
984                 generation:            newGen,
985                 view:                  s.view,
986                 builtin:               s.builtin,
987                 ids:                   make(map[span.URI][]packageID),
988                 importedBy:            make(map[packageID][]packageID),
989                 metadata:              make(map[packageID]*metadata),
990                 packages:              make(map[packageKey]*packageHandle),
991                 actions:               make(map[actionKey]*actionHandle),
992                 files:                 make(map[span.URI]source.VersionedFileHandle),
993                 goFiles:               make(map[parseKey]*parseGoHandle),
994                 workspaceDirectories:  make(map[span.URI]struct{}),
995                 workspacePackages:     make(map[packageID]packagePath),
996                 unloadableFiles:       make(map[span.URI]struct{}),
997                 parseModHandles:       make(map[span.URI]*parseModHandle),
998                 modTidyHandles:        make(map[span.URI]*modTidyHandle),
999                 modUpgradeHandles:     make(map[span.URI]*modUpgradeHandle),
1000                 modWhyHandles:         make(map[span.URI]*modWhyHandle),
1001                 modules:               make(map[span.URI]*moduleRoot),
1002                 workspaceModuleHandle: s.workspaceModuleHandle,
1003         }
1004
1005         if s.builtin != nil {
1006                 newGen.Inherit(s.builtin.handle)
1007         }
1008
1009         // Copy all of the FileHandles.
1010         for k, v := range s.files {
1011                 result.files[k] = v
1012         }
1013         // Copy the set of unloadable files.
1014         for k, v := range s.unloadableFiles {
1015                 result.unloadableFiles[k] = v
1016         }
1017         // Copy all of the modHandles.
1018         for k, v := range s.parseModHandles {
1019                 result.parseModHandles[k] = v
1020         }
1021         // Copy all of the workspace directories. They may be reset later.
1022         for k, v := range s.workspaceDirectories {
1023                 result.workspaceDirectories[k] = v
1024         }
1025
1026         for k, v := range s.goFiles {
1027                 if _, ok := withoutURIs[k.file.URI]; ok {
1028                         continue
1029                 }
1030                 newGen.Inherit(v.handle)
1031                 newGen.Inherit(v.astCacheHandle)
1032                 result.goFiles[k] = v
1033         }
1034
1035         // Copy all of the go.mod-related handles. They may be invalidated later,
1036         // so we inherit them at the end of the function.
1037         for k, v := range s.modTidyHandles {
1038                 if _, ok := withoutURIs[k]; ok {
1039                         continue
1040                 }
1041                 result.modTidyHandles[k] = v
1042         }
1043         for k, v := range s.modUpgradeHandles {
1044                 if _, ok := withoutURIs[k]; ok {
1045                         continue
1046                 }
1047                 result.modUpgradeHandles[k] = v
1048         }
1049         for k, v := range s.modWhyHandles {
1050                 if _, ok := withoutURIs[k]; ok {
1051                         continue
1052                 }
1053                 result.modWhyHandles[k] = v
1054         }
1055
1056         // Add all of the modules now. They may be deleted or added to later.
1057         for k, v := range s.modules {
1058                 result.modules[k] = v
1059         }
1060
1061         var modulesChanged, shouldReinitializeView bool
1062
1063         // directIDs keeps track of package IDs that have directly changed.
1064         // It maps id->invalidateMetadata.
1065         directIDs := map[packageID]bool{}
1066         for withoutURI, currentFH := range withoutURIs {
1067
1068                 // The original FileHandle for this URI is cached on the snapshot.
1069                 originalFH := s.files[withoutURI]
1070
1071                 // Check if the file's package name or imports have changed,
1072                 // and if so, invalidate this file's packages' metadata.
1073                 invalidateMetadata := forceReloadMetadata || s.shouldInvalidateMetadata(ctx, result, originalFH, currentFH)
1074
1075                 // Mark all of the package IDs containing the given file.
1076                 // TODO: if the file has moved into a new package, we should invalidate that too.
1077                 filePackages := guessPackagesForURI(withoutURI, s.ids)
1078                 for _, id := range filePackages {
1079                         directIDs[id] = directIDs[id] || invalidateMetadata
1080                 }
1081
1082                 // Invalidate the previous modTidyHandle if any of the files have been
1083                 // saved or if any of the metadata has been invalidated.
1084                 if invalidateMetadata || fileWasSaved(originalFH, currentFH) {
1085                         // TODO(rstambler): Only delete mod handles for which the
1086                         // withoutURI is relevant.
1087                         for k := range s.modTidyHandles {
1088                                 delete(result.modTidyHandles, k)
1089                         }
1090                         for k := range s.modUpgradeHandles {
1091                                 delete(result.modUpgradeHandles, k)
1092                         }
1093                         for k := range s.modWhyHandles {
1094                                 delete(result.modWhyHandles, k)
1095                         }
1096                 }
1097                 currentExists := true
1098                 if _, err := currentFH.Read(); os.IsNotExist(err) {
1099                         currentExists = false
1100                 }
1101                 // If the file invalidation is for a go.mod. originalFH is nil if the
1102                 // file is newly created.
1103                 currentMod := currentExists && currentFH.Kind() == source.Mod
1104                 originalMod := originalFH != nil && originalFH.Kind() == source.Mod
1105                 if currentMod || originalMod {
1106                         modulesChanged = true
1107
1108                         // If the view's go.mod file's contents have changed, invalidate
1109                         // the metadata for every known package in the snapshot.
1110                         if invalidateMetadata {
1111                                 for k := range s.metadata {
1112                                         directIDs[k] = true
1113                                 }
1114                                 // If a go.mod file in the workspace has changed, we need to
1115                                 // rebuild the workspace module.
1116                                 result.workspaceModuleHandle = nil
1117                         }
1118                         delete(result.parseModHandles, withoutURI)
1119
1120                         // Check if this is a newly created go.mod file. When a new module
1121                         // is created, we have to retry the initial workspace load.
1122                         rootURI := span.URIFromPath(filepath.Dir(withoutURI.Filename()))
1123                         if currentMod {
1124                                 if _, ok := result.modules[rootURI]; !ok {
1125                                         if m := getViewModule(ctx, s.view.rootURI, currentFH.URI(), s.view.Options()); m != nil {
1126                                                 result.modules[m.rootURI] = m
1127                                                 shouldReinitializeView = true
1128                                         }
1129
1130                                 }
1131                         } else if originalMod {
1132                                 // Similarly, we need to retry the IWL if a go.mod in the workspace
1133                                 // was deleted.
1134                                 if _, ok := result.modules[rootURI]; ok {
1135                                         delete(result.modules, rootURI)
1136                                         shouldReinitializeView = true
1137                                 }
1138                         }
1139                 }
1140                 // Keep track of the creations and deletions of go.sum files.
1141                 // Creating a go.sum without an associated go.mod has no effect on the
1142                 // set of modules.
1143                 currentSum := currentExists && currentFH.Kind() == source.Sum
1144                 originalSum := originalFH != nil && originalFH.Kind() == source.Sum
1145                 if currentSum || originalSum {
1146                         rootURI := span.URIFromPath(filepath.Dir(withoutURI.Filename()))
1147                         if currentSum {
1148                                 if mod, ok := result.modules[rootURI]; ok {
1149                                         mod.sumURI = currentFH.URI()
1150                                 }
1151                         } else if originalSum {
1152                                 if mod, ok := result.modules[rootURI]; ok {
1153                                         mod.sumURI = ""
1154                                 }
1155                         }
1156                 }
1157
1158                 // Handle the invalidated file; it may have new contents or not exist.
1159                 if !currentExists {
1160                         delete(result.files, withoutURI)
1161                 } else {
1162                         result.files[withoutURI] = currentFH
1163                 }
1164                 // Make sure to remove the changed file from the unloadable set.
1165                 delete(result.unloadableFiles, withoutURI)
1166         }
1167
1168         // Invalidate reverse dependencies too.
1169         // TODO(heschi): figure out the locking model and use transitiveReverseDeps?
1170         // transitiveIDs keeps track of transitive reverse dependencies.
1171         // If an ID is present in the map, invalidate its types.
1172         // If an ID's value is true, invalidate its metadata too.
1173         transitiveIDs := make(map[packageID]bool)
1174         var addRevDeps func(packageID, bool)
1175         addRevDeps = func(id packageID, invalidateMetadata bool) {
1176                 current, seen := transitiveIDs[id]
1177                 newInvalidateMetadata := current || invalidateMetadata
1178
1179                 // If we've already seen this ID, and the value of invalidate
1180                 // metadata has not changed, we can return early.
1181                 if seen && current == newInvalidateMetadata {
1182                         return
1183                 }
1184                 transitiveIDs[id] = newInvalidateMetadata
1185                 for _, rid := range s.getImportedByLocked(id) {
1186                         addRevDeps(rid, invalidateMetadata)
1187                 }
1188         }
1189         for id, invalidateMetadata := range directIDs {
1190                 addRevDeps(id, invalidateMetadata)
1191         }
1192
1193         // When modules change, we need to recompute their workspace directories,
1194         // as replace directives may have changed.
1195         if modulesChanged {
1196                 result.workspaceDirectories = result.findWorkspaceDirectories(ctx)
1197         }
1198
1199         // Copy the package type information.
1200         for k, v := range s.packages {
1201                 if _, ok := transitiveIDs[k.id]; ok {
1202                         continue
1203                 }
1204                 newGen.Inherit(v.handle)
1205                 result.packages[k] = v
1206         }
1207         // Copy the package analysis information.
1208         for k, v := range s.actions {
1209                 if _, ok := transitiveIDs[k.pkg.id]; ok {
1210                         continue
1211                 }
1212                 newGen.Inherit(v.handle)
1213                 result.actions[k] = v
1214         }
1215         // Copy the package metadata. We only need to invalidate packages directly
1216         // containing the affected file, and only if it changed in a relevant way.
1217         for k, v := range s.metadata {
1218                 if invalidateMetadata, ok := transitiveIDs[k]; invalidateMetadata && ok {
1219                         continue
1220                 }
1221                 result.metadata[k] = v
1222         }
1223         // Copy the URI to package ID mappings, skipping only those URIs whose
1224         // metadata will be reloaded in future calls to load.
1225 copyIDs:
1226         for k, ids := range s.ids {
1227                 for _, id := range ids {
1228                         if invalidateMetadata, ok := transitiveIDs[id]; invalidateMetadata && ok {
1229                                 continue copyIDs
1230                         }
1231                 }
1232                 result.ids[k] = ids
1233         }
1234         // Copy the set of initally loaded packages.
1235         for id, pkgPath := range s.workspacePackages {
1236                 // Packages with the id "command-line-arguments" are generated by the
1237                 // go command when the user is outside of GOPATH and outside of a
1238                 // module. Do not cache them as workspace packages for longer than
1239                 // necessary.
1240                 if id == "command-line-arguments" {
1241                         if invalidateMetadata, ok := transitiveIDs[id]; invalidateMetadata && ok {
1242                                 continue
1243                         }
1244                 }
1245
1246                 // If all the files we know about in a package have been deleted,
1247                 // the package is gone and we should no longer try to load it.
1248                 if m := s.metadata[id]; m != nil {
1249                         hasFiles := false
1250                         for _, uri := range s.metadata[id].goFiles {
1251                                 if _, ok := result.files[uri]; ok {
1252                                         hasFiles = true
1253                                         break
1254                                 }
1255                         }
1256                         if !hasFiles {
1257                                 continue
1258                         }
1259                 }
1260
1261                 result.workspacePackages[id] = pkgPath
1262         }
1263
1264         // Inherit all of the go.mod-related handles.
1265         for _, v := range result.modTidyHandles {
1266                 newGen.Inherit(v.handle)
1267         }
1268         for _, v := range result.modUpgradeHandles {
1269                 newGen.Inherit(v.handle)
1270         }
1271         for _, v := range result.modWhyHandles {
1272                 newGen.Inherit(v.handle)
1273         }
1274         for _, v := range result.parseModHandles {
1275                 newGen.Inherit(v.handle)
1276         }
1277         if result.workspaceModuleHandle != nil {
1278                 newGen.Inherit(result.workspaceModuleHandle.handle)
1279         }
1280         // Don't bother copying the importedBy graph,
1281         // as it changes each time we update metadata.
1282
1283         var reinitialize reinitializeView
1284         if modulesChanged {
1285                 reinitialize = maybeReinit
1286         }
1287         if shouldReinitializeView {
1288                 reinitialize = definitelyReinit
1289         }
1290
1291         // If the snapshot's workspace mode has changed, the packages loaded using
1292         // the previous mode are no longer relevant, so clear them out.
1293         if s.workspaceMode() != result.workspaceMode() {
1294                 result.workspacePackages = map[packageID]packagePath{}
1295         }
1296         return result, reinitialize
1297 }
1298
1299 // guessPackagesForURI returns all packages related to uri. If we haven't seen this
1300 // URI before, we guess based on files in the same directory. This is of course
1301 // incorrect in build systems where packages are not organized by directory.
1302 func guessPackagesForURI(uri span.URI, known map[span.URI][]packageID) []packageID {
1303         packages := known[uri]
1304         if len(packages) > 0 {
1305                 // We've seen this file before.
1306                 return packages
1307         }
1308         // This is a file we don't yet know about. Guess relevant packages by
1309         // considering files in the same directory.
1310
1311         // Cache of FileInfo to avoid unnecessary stats for multiple files in the
1312         // same directory.
1313         stats := make(map[string]struct {
1314                 os.FileInfo
1315                 error
1316         })
1317         getInfo := func(dir string) (os.FileInfo, error) {
1318                 if res, ok := stats[dir]; ok {
1319                         return res.FileInfo, res.error
1320                 }
1321                 fi, err := os.Stat(dir)
1322                 stats[dir] = struct {
1323                         os.FileInfo
1324                         error
1325                 }{fi, err}
1326                 return fi, err
1327         }
1328         dir := filepath.Dir(uri.Filename())
1329         fi, err := getInfo(dir)
1330         if err != nil {
1331                 return nil
1332         }
1333
1334         // Aggregate all possibly relevant package IDs.
1335         var found []packageID
1336         for knownURI, ids := range known {
1337                 knownDir := filepath.Dir(knownURI.Filename())
1338                 knownFI, err := getInfo(knownDir)
1339                 if err != nil {
1340                         continue
1341                 }
1342                 if os.SameFile(fi, knownFI) {
1343                         found = append(found, ids...)
1344                 }
1345         }
1346         return found
1347 }
1348
1349 type reinitializeView int
1350
1351 const (
1352         doNotReinit = reinitializeView(iota)
1353         maybeReinit
1354         definitelyReinit
1355 )
1356
1357 // fileWasSaved reports whether the FileHandle passed in has been saved. It
1358 // accomplishes this by checking to see if the original and current FileHandles
1359 // are both overlays, and if the current FileHandle is saved while the original
1360 // FileHandle was not saved.
1361 func fileWasSaved(originalFH, currentFH source.FileHandle) bool {
1362         c, ok := currentFH.(*overlay)
1363         if !ok || c == nil {
1364                 return true
1365         }
1366         o, ok := originalFH.(*overlay)
1367         if !ok || o == nil {
1368                 return c.saved
1369         }
1370         return !o.saved && c.saved
1371 }
1372
1373 // shouldInvalidateMetadata reparses a file's package and import declarations to
1374 // determine if the file requires a metadata reload.
1375 func (s *snapshot) shouldInvalidateMetadata(ctx context.Context, newSnapshot *snapshot, originalFH, currentFH source.FileHandle) bool {
1376         if originalFH == nil {
1377                 return true
1378         }
1379         // If the file hasn't changed, there's no need to reload.
1380         if originalFH.FileIdentity() == currentFH.FileIdentity() {
1381                 return false
1382         }
1383         // If a go.mod in the workspace has been changed, invalidate metadata.
1384         if kind := originalFH.Kind(); kind == source.Mod {
1385                 return isSubdirectory(filepath.Dir(s.view.rootURI.Filename()), filepath.Dir(originalFH.URI().Filename()))
1386         }
1387         // Get the original and current parsed files in order to check package name
1388         // and imports. Use the new snapshot to parse to avoid modifying the
1389         // current snapshot.
1390         original, originalErr := newSnapshot.ParseGo(ctx, originalFH, source.ParseHeader)
1391         current, currentErr := newSnapshot.ParseGo(ctx, currentFH, source.ParseHeader)
1392         if originalErr != nil || currentErr != nil {
1393                 return (originalErr == nil) != (currentErr == nil)
1394         }
1395         // Check if the package's metadata has changed. The cases handled are:
1396         //    1. A package's name has changed
1397         //    2. A file's imports have changed
1398         if original.File.Name.Name != current.File.Name.Name {
1399                 return true
1400         }
1401         importSet := make(map[string]struct{})
1402         for _, importSpec := range original.File.Imports {
1403                 importSet[importSpec.Path.Value] = struct{}{}
1404         }
1405         // If any of the current imports were not in the original imports.
1406         for _, importSpec := range current.File.Imports {
1407                 if _, ok := importSet[importSpec.Path.Value]; ok {
1408                         continue
1409                 }
1410                 // If the import path is obviously not valid, we can skip reloading
1411                 // metadata. For now, valid means properly quoted and without a
1412                 // terminal slash.
1413                 path, err := strconv.Unquote(importSpec.Path.Value)
1414                 if err != nil {
1415                         continue
1416                 }
1417                 if path == "" {
1418                         continue
1419                 }
1420                 if path[len(path)-1] == '/' {
1421                         continue
1422                 }
1423                 return true
1424         }
1425         return false
1426 }
1427
1428 // findWorkspaceDirectoriesLocked returns all of the directories that are
1429 // considered to be part of the view's workspace. For GOPATH workspaces, this
1430 // is just the view's root. For modules-based workspaces, this is the module
1431 // root and any replace targets. It also returns the parseModHandle for the
1432 // view's go.mod file if it has one.
1433 //
1434 // It assumes that the file handle is the view's go.mod file, if it has one.
1435 // The caller need not be holding the snapshot's mutex, but it might be.
1436 func (s *snapshot) findWorkspaceDirectories(ctx context.Context) map[span.URI]struct{} {
1437         // If the view does not have a go.mod file, only the root directory
1438         // is known. In GOPATH mode, we should really watch the entire GOPATH,
1439         // but that's too expensive.
1440         dirs := map[span.URI]struct{}{
1441                 s.view.rootURI: {},
1442         }
1443         for _, m := range s.modules {
1444                 fh, err := s.GetFile(ctx, m.modURI)
1445                 if err != nil {
1446                         continue
1447                 }
1448                 // Ignore parse errors. An invalid go.mod is not fatal.
1449                 // TODO(rstambler): Try to preserve existing watched directories as
1450                 // much as possible, otherwise we will thrash when a go.mod is edited.
1451                 mod, err := s.ParseMod(ctx, fh)
1452                 if err != nil {
1453                         continue
1454                 }
1455                 for _, r := range mod.File.Replace {
1456                         // We may be replacing a module with a different version, not a path
1457                         // on disk.
1458                         if r.New.Version != "" {
1459                                 continue
1460                         }
1461                         dirs[span.URIFromPath(r.New.Path)] = struct{}{}
1462                 }
1463         }
1464         return dirs
1465 }
1466
1467 func (s *snapshot) BuiltinPackage(ctx context.Context) (*source.BuiltinPackage, error) {
1468         s.AwaitInitialized(ctx)
1469
1470         if s.builtin == nil {
1471                 return nil, errors.Errorf("no builtin package for view %s", s.view.name)
1472         }
1473         d, err := s.builtin.handle.Get(ctx, s.generation, s)
1474         if err != nil {
1475                 return nil, err
1476         }
1477         data := d.(*builtinPackageData)
1478         return data.parsed, data.err
1479 }
1480
1481 func (s *snapshot) buildBuiltinPackage(ctx context.Context, goFiles []string) error {
1482         if len(goFiles) != 1 {
1483                 return errors.Errorf("only expected 1 file, got %v", len(goFiles))
1484         }
1485         uri := span.URIFromPath(goFiles[0])
1486
1487         // Get the FileHandle through the cache to avoid adding it to the snapshot
1488         // and to get the file content from disk.
1489         fh, err := s.view.session.cache.getFile(ctx, uri)
1490         if err != nil {
1491                 return err
1492         }
1493         h := s.generation.Bind(fh.FileIdentity(), func(ctx context.Context, arg memoize.Arg) interface{} {
1494                 snapshot := arg.(*snapshot)
1495
1496                 pgh := snapshot.parseGoHandle(ctx, fh, source.ParseFull)
1497                 pgf, _, err := snapshot.parseGo(ctx, pgh)
1498                 if err != nil {
1499                         return &builtinPackageData{err: err}
1500                 }
1501                 pkg, err := ast.NewPackage(snapshot.view.session.cache.fset, map[string]*ast.File{
1502                         pgf.URI.Filename(): pgf.File,
1503                 }, nil, nil)
1504                 if err != nil {
1505                         return &builtinPackageData{err: err}
1506                 }
1507                 return &builtinPackageData{
1508                         parsed: &source.BuiltinPackage{
1509                                 ParsedFile: pgf,
1510                                 Package:    pkg,
1511                         },
1512                 }
1513         })
1514         s.builtin = &builtinPackageHandle{handle: h}
1515         return nil
1516 }
1517
1518 type workspaceModuleHandle struct {
1519         handle *memoize.Handle
1520 }
1521
1522 type workspaceModuleData struct {
1523         file *modfile.File
1524         err  error
1525 }
1526
1527 type workspaceModuleKey string
1528
1529 func (wmh *workspaceModuleHandle) build(ctx context.Context, snapshot *snapshot) (*modfile.File, error) {
1530         v, err := wmh.handle.Get(ctx, snapshot.generation, snapshot)
1531         if err != nil {
1532                 return nil, err
1533         }
1534         data := v.(*workspaceModuleData)
1535         return data.file, data.err
1536 }
1537
1538 func (s *snapshot) getWorkspaceModuleHandle(ctx context.Context) (*workspaceModuleHandle, error) {
1539         s.mu.Lock()
1540         wsModule := s.workspaceModuleHandle
1541         s.mu.Unlock()
1542         if wsModule != nil {
1543                 return wsModule, nil
1544         }
1545         var fhs []source.FileHandle
1546         for _, mod := range s.modules {
1547                 fh, err := s.GetFile(ctx, mod.modURI)
1548                 if err != nil {
1549                         return nil, err
1550                 }
1551                 fhs = append(fhs, fh)
1552         }
1553         goplsModURI := span.URIFromPath(filepath.Join(s.view.Folder().Filename(), "gopls.mod"))
1554         goplsModFH, err := s.GetFile(ctx, goplsModURI)
1555         if err != nil {
1556                 return nil, err
1557         }
1558         _, err = goplsModFH.Read()
1559         switch {
1560         case err == nil:
1561                 // We have a gopls.mod. Our handle only depends on it.
1562                 fhs = []source.FileHandle{goplsModFH}
1563         case os.IsNotExist(err):
1564                 // No gopls.mod, so we must build the workspace mod file automatically.
1565                 // Defensively ensure that the goplsModFH is nil as this controls automatic
1566                 // building of the workspace mod file.
1567                 goplsModFH = nil
1568         default:
1569                 return nil, errors.Errorf("error getting gopls.mod: %w", err)
1570         }
1571
1572         sort.Slice(fhs, func(i, j int) bool {
1573                 return fhs[i].URI() < fhs[j].URI()
1574         })
1575         var k string
1576         for _, fh := range fhs {
1577                 k += fh.FileIdentity().String()
1578         }
1579         key := workspaceModuleKey(hashContents([]byte(k)))
1580         h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
1581                 if goplsModFH != nil {
1582                         parsed, err := s.ParseMod(ctx, goplsModFH)
1583                         if err != nil {
1584                                 return &workspaceModuleData{err: err}
1585                         }
1586                         return &workspaceModuleData{file: parsed.File}
1587                 }
1588                 s := arg.(*snapshot)
1589                 data := &workspaceModuleData{}
1590                 data.file, data.err = s.BuildWorkspaceModFile(ctx)
1591                 return data
1592         })
1593         wsModule = &workspaceModuleHandle{
1594                 handle: h,
1595         }
1596         s.mu.Lock()
1597         defer s.mu.Unlock()
1598         s.workspaceModuleHandle = wsModule
1599         return s.workspaceModuleHandle, nil
1600 }
1601
1602 // BuildWorkspaceModFile generates a workspace module given the modules in the
1603 // the workspace. It does not read gopls.mod.
1604 func (s *snapshot) BuildWorkspaceModFile(ctx context.Context) (*modfile.File, error) {
1605         file := &modfile.File{}
1606         file.AddModuleStmt("gopls-workspace")
1607
1608         paths := make(map[string]*moduleRoot)
1609         for _, mod := range s.modules {
1610                 fh, err := s.GetFile(ctx, mod.modURI)
1611                 if err != nil {
1612                         return nil, err
1613                 }
1614                 parsed, err := s.ParseMod(ctx, fh)
1615                 if err != nil {
1616                         return nil, err
1617                 }
1618                 if parsed.File == nil || parsed.File.Module == nil {
1619                         return nil, fmt.Errorf("no module declaration for %s", mod.modURI)
1620                 }
1621                 path := parsed.File.Module.Mod.Path
1622                 paths[path] = mod
1623                 // If the module's path includes a major version, we expect it to have
1624                 // a matching major version.
1625                 _, majorVersion, _ := module.SplitPathVersion(path)
1626                 if majorVersion == "" {
1627                         majorVersion = "/v0"
1628                 }
1629                 majorVersion = strings.TrimLeft(majorVersion, "/.") // handle gopkg.in versions
1630                 file.AddNewRequire(path, source.WorkspaceModuleVersion(majorVersion), false)
1631                 if err := file.AddReplace(path, "", mod.rootURI.Filename(), ""); err != nil {
1632                         return nil, err
1633                 }
1634         }
1635         // Go back through all of the modules to handle any of their replace
1636         // statements.
1637         for _, module := range s.modules {
1638                 fh, err := s.GetFile(ctx, module.modURI)
1639                 if err != nil {
1640                         return nil, err
1641                 }
1642                 pmf, err := s.ParseMod(ctx, fh)
1643                 if err != nil {
1644                         return nil, err
1645                 }
1646                 // If any of the workspace modules have replace directives, they need
1647                 // to be reflected in the workspace module.
1648                 for _, rep := range pmf.File.Replace {
1649                         // Don't replace any modules that are in our workspace--we should
1650                         // always use the version in the workspace.
1651                         if _, ok := paths[rep.Old.Path]; ok {
1652                                 continue
1653                         }
1654                         newPath := rep.New.Path
1655                         newVersion := rep.New.Version
1656                         // If a replace points to a module in the workspace, make sure we
1657                         // direct it to version of the module in the workspace.
1658                         if mod, ok := paths[rep.New.Path]; ok {
1659                                 newPath = mod.rootURI.Filename()
1660                                 newVersion = ""
1661                         } else if rep.New.Version == "" && !filepath.IsAbs(rep.New.Path) {
1662                                 // Make any relative paths absolute.
1663                                 newPath = filepath.Join(module.rootURI.Filename(), rep.New.Path)
1664                         }
1665                         if err := file.AddReplace(rep.Old.Path, rep.Old.Version, newPath, newVersion); err != nil {
1666                                 return nil, err
1667                         }
1668                 }
1669         }
1670         return file, nil
1671 }
1672
1673 func getViewModule(ctx context.Context, viewRootURI, modURI span.URI, options *source.Options) *moduleRoot {
1674         rootURI := span.URIFromPath(filepath.Dir(modURI.Filename()))
1675         // If we are not in multi-module mode, check that the affected module is
1676         // in the workspace root.
1677         if !options.ExperimentalWorkspaceModule {
1678                 if span.CompareURI(rootURI, viewRootURI) != 0 {
1679                         return nil
1680                 }
1681         }
1682         sumURI := span.URIFromPath(sumFilename(modURI))
1683         if info, _ := os.Stat(sumURI.Filename()); info == nil {
1684                 sumURI = ""
1685         }
1686         return &moduleRoot{
1687                 rootURI: rootURI,
1688                 modURI:  modURI,
1689                 sumURI:  sumURI,
1690         }
1691 }