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.
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"
37 type snapshot struct {
38 memoize.Arg // allow as a memoize.Function arg
43 // the cache generation that contains the data for this snapshot.
44 generation *memoize.Generation
46 // builtin pins the AST and package for builtin.go in memory.
47 builtin *builtinPackageHandle
49 // mu guards all of the maps in the snapshot.
52 // ids maps file URIs to package IDs.
53 // It may be invalidated on calls to go/packages.
54 ids map[span.URI][]packageID
56 // metadata maps file IDs to their associated metadata.
57 // It may invalidated on calls to go/packages.
58 metadata map[packageID]*metadata
60 // importedBy maps package IDs to the list of packages that import them.
61 importedBy map[packageID][]packageID
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
67 // goFiles maps a parseKey to its parseGoHandle.
68 goFiles map[parseKey]*parseGoHandle
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
74 // actions maps an actionkey to its actionHandle.
75 actions map[actionKey]*actionHandle
77 // workspacePackages contains the workspace's packages, which are loaded
78 // when the view is created.
79 workspacePackages map[packageID]packagePath
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{}
85 // unloadableFiles keeps track of files that we've failed to load.
86 unloadableFiles map[span.URI]struct{}
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
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
99 // modules is the set of modules currently in this workspace.
100 modules map[span.URI]*moduleRoot
102 // workspaceModuleHandle keeps track of the in-memory representation of the
103 // go.mod file for the workspace module.
104 workspaceModuleHandle *workspaceModuleHandle
107 type packageKey struct {
108 mode source.ParseMode
112 type actionKey struct {
114 analyzer *analysis.Analyzer
117 func (s *snapshot) ID() uint64 {
121 func (s *snapshot) View() source.View {
125 func (s *snapshot) FileSet() *token.FileSet {
126 return s.view.session.cache.fset
129 func (s *snapshot) ModFiles() []span.URI {
131 for _, m := range s.modules {
132 uris = append(uris, m.modURI)
137 func (s *snapshot) ValidBuildConfiguration() bool {
138 return validBuildConfiguration(s.view.rootURI, &s.view.workspaceInformation, s.modules)
141 // workspaceMode describes the way in which the snapshot's workspace should
143 func (s *snapshot) workspaceMode() workspaceMode {
144 var mode workspaceMode
146 // If the view has an invalid configuration, don't build the workspace
148 validBuildConfiguration := s.ValidBuildConfiguration()
149 if !validBuildConfiguration {
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 {
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 {
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,
168 if !options.ExpandWorkspaceToModule {
171 // The workspace module has been disabled by the user.
172 if !options.ExperimentalWorkspaceModule {
175 mode |= usesWorkspaceModule
179 // config returns the configuration used for the snapshot's interaction with
180 // the go/packages API. It uses the given working directory.
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
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()
191 cfg := &packages.Config{
194 Env: append(append([]string{}, env...), "GO111MODULE="+s.view.go111module),
195 BuildFlags: append([]string{}, buildFlags...),
196 Mode: packages.NeedName |
198 packages.NeedCompiledGoFiles |
199 packages.NeedImports |
201 packages.NeedTypesSizes |
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")
208 Logf: func(format string, args ...interface{}) {
210 event.Log(ctx, fmt.Sprintf(format, args...))
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)
219 packagesinternal.SetGoCmdRunner(cfg, s.view.session.gocmdRunner)
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)
231 _, err = runner.Run(ctx, *inv)
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)
242 return runner.Run(ctx, *inv)
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)
252 return runner.RunPiped(ctx, *inv, stdout, stderr)
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))
259 inv = &gocommand.Invocation{
266 if allowTempModfile && s.workspaceMode()&tempModfile != 0 {
268 return "", nil, nil, cleanup, fmt.Errorf("no go.mod file found in %s", cfg.Dir)
270 modFH, err := s.GetFile(ctx, modURI)
272 return "", nil, nil, cleanup, err
274 // Use the go.sum if it happens to be available.
275 sumFH, _ := s.sumFH(ctx, modFH)
277 tmpURI, cleanup, err = tempModFile(modFH, sumFH)
279 return "", nil, nil, cleanup, err
281 inv.ModFile = tmpURI.Filename()
284 var modContent []byte
286 modFH, err := s.GetFile(ctx, modURI)
288 return "", nil, nil, cleanup, err
290 modContent, err = modFH.Read()
292 return "", nil, nil, nil, err
295 modMod, err := s.needsModEqualsMod(ctx, modURI, modContent)
297 return "", nil, nil, cleanup, err
303 runner = packagesinternal.GetGoCmdRunner(cfg)
304 return tmpURI, runner, inv, cleanup, nil
307 func (s *snapshot) buildOverlay() map[string][]byte {
311 overlays := make(map[string][]byte)
312 for uri, fh := range s.files {
313 overlay, ok := fh.(*overlay)
320 // TODO(rstambler): Make sure not to send overlays outside of the current view.
321 overlays[uri.Filename()] = overlay.text
326 func hashUnsavedOverlays(files map[span.URI]source.VersionedFileHandle) string {
328 for uri, fh := range files {
329 if overlay, ok := fh.(*overlay); ok && !overlay.saved {
330 unsaved = append(unsaved, uri.Filename())
333 sort.Strings(unsaved)
334 return hashContents([]byte(strings.Join(unsaved, "")))
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))
340 phs, err := s.packageHandlesForFile(ctx, uri, mode)
344 var pkgs []source.Package
345 for _, ph := range phs {
346 pkg, err := ph.check(ctx, s)
350 pkgs = append(pkgs, pkg)
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))
358 phs, err := s.packageHandlesForFile(ctx, uri, mode)
364 return nil, errors.Errorf("no packages")
368 for _, handle := range phs[1:] {
370 case source.WidestPackage:
371 if ph == nil || len(handle.CompiledGoFiles()) > len(ph.CompiledGoFiles()) {
374 case source.NarrowestPackage:
375 if ph == nil || len(handle.CompiledGoFiles()) < len(ph.CompiledGoFiles()) {
381 return nil, errors.Errorf("no packages in input")
384 return ph.check(ctx, s)
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)
395 if fh.Kind() != source.Go {
396 return nil, fmt.Errorf("no packages for non-Go file %s", uri)
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
404 if m := s.getMetadata(id); m == nil {
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.
413 if err := s.load(ctx, fileURI(uri)); err != nil {
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
422 case source.TypecheckAll:
423 if s.workspaceParseMode(id) == source.ParseFull {
424 parseModes = []source.ParseMode{source.ParseFull}
426 parseModes = []source.ParseMode{source.ParseExported, source.ParseFull}
428 case source.TypecheckFull:
429 parseModes = []source.ParseMode{source.ParseFull}
430 case source.TypecheckWorkspace:
431 parseModes = []source.ParseMode{s.workspaceParseMode(id)}
434 for _, parseMode := range parseModes {
435 ph, err := s.buildPackageHandle(ctx, id, parseMode)
439 phs = append(phs, ph)
446 func (s *snapshot) GetReverseDependencies(ctx context.Context, id string) ([]source.Package, error) {
447 if err := s.awaitLoaded(ctx); err != nil {
450 ids := make(map[packageID]struct{})
451 s.transitiveReverseDependencies(packageID(id), ids)
453 // Make sure to delete the original package ID from the map.
454 delete(ids, packageID(id))
456 var pkgs []source.Package
457 for id := range ids {
458 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
462 pkgs = append(pkgs, pkg)
467 func (s *snapshot) checkedPackage(ctx context.Context, id packageID, mode source.ParseMode) (*pkg, error) {
468 ph, err := s.buildPackageHandle(ctx, id, mode)
472 return ph.check(ctx, s)
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 {
481 if s.getMetadata(id) == nil {
485 importedBy := s.getImportedBy(id)
486 for _, parentID := range importedBy {
487 s.transitiveReverseDependencies(parentID, ids)
491 func (s *snapshot) getGoFile(key parseKey) *parseGoHandle {
494 return s.goFiles[key]
497 func (s *snapshot) addGoFile(key parseKey, pgh *parseGoHandle) *parseGoHandle {
500 if existing, ok := s.goFiles[key]; ok {
507 func (s *snapshot) getParseModHandle(uri span.URI) *parseModHandle {
510 return s.parseModHandles[uri]
513 func (s *snapshot) getModWhyHandle(uri span.URI) *modWhyHandle {
516 return s.modWhyHandles[uri]
519 func (s *snapshot) getModUpgradeHandle(uri span.URI) *modUpgradeHandle {
522 return s.modUpgradeHandles[uri]
525 func (s *snapshot) getModTidyHandle(uri span.URI) *modTidyHandle {
528 return s.modTidyHandles[uri]
531 func (s *snapshot) getImportedBy(id packageID) []packageID {
534 return s.getImportedByLocked(id)
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()
542 return s.importedBy[id]
545 func (s *snapshot) clearAndRebuildImportGraph() {
549 // Completely invalidate the original map.
550 s.importedBy = make(map[packageID][]packageID)
551 s.rebuildImportGraph()
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)
562 func (s *snapshot) addPackageHandle(ph *packageHandle) *packageHandle {
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 {
571 s.packages[ph.packageKey()] = ph
575 func (s *snapshot) workspacePackageIDs() (ids []packageID) {
579 for id := range s.workspacePackages {
580 ids = append(ids, id)
585 func (s *snapshot) WorkspaceDirectories(ctx context.Context) []span.URI {
590 for d := range s.workspaceDirectories {
591 dirs = append(dirs, d)
596 func (s *snapshot) WorkspacePackages(ctx context.Context) ([]source.Package, error) {
597 if err := s.awaitLoaded(ctx); err != nil {
600 var pkgs []source.Package
601 for _, pkgID := range s.workspacePackageIDs() {
602 pkg, err := s.checkedPackage(ctx, pkgID, s.workspaceParseMode(pkgID))
606 pkgs = append(pkgs, pkg)
611 func (s *snapshot) KnownPackages(ctx context.Context) ([]source.Package, error) {
612 if err := s.awaitLoaded(ctx); err != nil {
616 // The WorkspaceSymbols implementation relies on this function returning
617 // workspace packages first.
618 ids := s.workspacePackageIDs()
620 for id := range s.metadata {
621 if _, ok := s.workspacePackages[id]; ok {
624 ids = append(ids, id)
628 var pkgs []source.Package
629 for _, id := range ids {
630 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
634 pkgs = append(pkgs, pkg)
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)
647 results := map[string]source.Package{}
648 for _, ph := range s.packages {
649 cachedPkg, err := ph.cached(s.generation)
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
660 results[string(importPath)] = newPkg
667 func (s *snapshot) GoModForFile(ctx context.Context, uri span.URI) span.URI {
669 for _, m := range s.modules {
670 if !isSubdirectory(m.rootURI.Filename(), uri.Filename()) {
673 if len(m.modURI) > len(match) {
680 func (s *snapshot) getPackage(id packageID, mode source.ParseMode) *packageHandle {
688 return s.packages[key]
691 func (s *snapshot) getActionHandle(id packageID, m source.ParseMode, a *analysis.Analyzer) *actionHandle {
702 return s.actions[key]
705 func (s *snapshot) addActionHandle(ah *actionHandle) *actionHandle {
710 analyzer: ah.analyzer,
716 if ah, ok := s.actions[key]; ok {
723 func (s *snapshot) getIDsForURI(uri span.URI) []packageID {
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?
734 for _, id := range s.ids[uri] {
735 if m, ok := s.metadata[id]; ok {
736 metadata = append(metadata, m)
742 func (s *snapshot) getMetadata(id packageID) *metadata {
746 return s.metadata[id]
749 func (s *snapshot) addID(uri span.URI, id packageID) {
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 {
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" {
764 // Delete command-line-arguments if it was a workspace package.
765 delete(s.workspacePackages, existingID)
769 s.ids[uri] = append(s.ids[uri], id)
772 func (s *snapshot) isWorkspacePackage(id packageID) (packagePath, bool) {
776 scope, ok := s.workspacePackages[id]
780 func (s *snapshot) FindFile(uri span.URI) source.VersionedFileHandle {
781 f, err := s.view.getFile(uri)
789 return s.files[f.URI()]
792 // GetVersionedFile returns a File for the given URI. If the file is unknown it
793 // is added to the managed set.
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)
805 return s.getFileLocked(ctx, f)
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)
813 func (s *snapshot) getFileLocked(ctx context.Context, f *fileBase) (source.VersionedFileHandle, error) {
814 if fh, ok := s.files[f.URI()]; ok {
818 fh, err := s.view.session.cache.getFile(ctx, f.URI())
822 closed := &closedFile{fh}
823 s.files[f.URI()] = closed
827 func (s *snapshot) IsOpen(uri span.URI) bool {
831 _, open := s.files[uri].(*overlay)
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)
839 if err := s.reloadWorkspace(ctx); err != nil {
842 if err := s.reloadOrphanedFiles(ctx); err != nil {
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?
850 if len(s.metadata) == 0 {
851 return s.view.initializedErr
856 func (s *snapshot) AwaitInitialized(ctx context.Context) {
860 case <-s.view.initialized:
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)
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"))
875 // See which of the workspace packages are missing metadata.
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" {
883 if s.metadata[id] == nil {
884 pkgPathSet[pkgPath] = struct{}{}
889 if len(pkgPathSet) == 0 {
892 var pkgPaths []interface{}
893 for pkgPath := range pkgPathSet {
894 pkgPaths = append(pkgPaths, pkgPath)
896 return s.load(ctx, pkgPaths...)
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 {
909 err := s.load(ctx, scopes...)
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
915 // TODO(rstambler): This may be an overestimate if the load stopped
916 // early for an unrelated errors. Add a fallback?
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))
923 for _, scope := range scopes {
924 uri := span.URI(scope.(fileURI))
925 if s.getMetadataForURILocked(uri) == nil {
926 s.unloadableFiles[uri] = struct{}{}
934 func (s *snapshot) orphanedFileScopes() []interface{} {
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 {
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) {
949 // Don't reload metadata for files we've already deemed unloadable.
950 if _, ok := s.unloadableFiles[uri]; ok {
953 if s.getMetadataForURILocked(uri) == nil {
954 scopeSet[uri] = struct{}{}
957 var scopes []interface{}
958 for uri := range scopeSet {
959 scopes = append(scopes, fileURI(uri))
964 func contains(views []*View, view *View) bool {
965 for _, v := range views {
973 func generationName(v *View, snapshotID uint64) string {
974 return fmt.Sprintf("v%v/%v", v.id, snapshotID)
977 func (s *snapshot) clone(ctx context.Context, withoutURIs map[span.URI]source.VersionedFileHandle, forceReloadMetadata bool) (*snapshot, reinitializeView) {
981 newGen := s.view.session.cache.store.Generation(generationName(s.view, s.id+1))
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,
1005 if s.builtin != nil {
1006 newGen.Inherit(s.builtin.handle)
1009 // Copy all of the FileHandles.
1010 for k, v := range s.files {
1013 // Copy the set of unloadable files.
1014 for k, v := range s.unloadableFiles {
1015 result.unloadableFiles[k] = v
1017 // Copy all of the modHandles.
1018 for k, v := range s.parseModHandles {
1019 result.parseModHandles[k] = v
1021 // Copy all of the workspace directories. They may be reset later.
1022 for k, v := range s.workspaceDirectories {
1023 result.workspaceDirectories[k] = v
1026 for k, v := range s.goFiles {
1027 if _, ok := withoutURIs[k.file.URI]; ok {
1030 newGen.Inherit(v.handle)
1031 newGen.Inherit(v.astCacheHandle)
1032 result.goFiles[k] = v
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 {
1041 result.modTidyHandles[k] = v
1043 for k, v := range s.modUpgradeHandles {
1044 if _, ok := withoutURIs[k]; ok {
1047 result.modUpgradeHandles[k] = v
1049 for k, v := range s.modWhyHandles {
1050 if _, ok := withoutURIs[k]; ok {
1053 result.modWhyHandles[k] = v
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
1061 var modulesChanged, shouldReinitializeView bool
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 {
1068 // The original FileHandle for this URI is cached on the snapshot.
1069 originalFH := s.files[withoutURI]
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)
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
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)
1090 for k := range s.modUpgradeHandles {
1091 delete(result.modUpgradeHandles, k)
1093 for k := range s.modWhyHandles {
1094 delete(result.modWhyHandles, k)
1097 currentExists := true
1098 if _, err := currentFH.Read(); os.IsNotExist(err) {
1099 currentExists = false
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
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 {
1114 // If a go.mod file in the workspace has changed, we need to
1115 // rebuild the workspace module.
1116 result.workspaceModuleHandle = nil
1118 delete(result.parseModHandles, withoutURI)
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()))
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
1131 } else if originalMod {
1132 // Similarly, we need to retry the IWL if a go.mod in the workspace
1134 if _, ok := result.modules[rootURI]; ok {
1135 delete(result.modules, rootURI)
1136 shouldReinitializeView = true
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
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()))
1148 if mod, ok := result.modules[rootURI]; ok {
1149 mod.sumURI = currentFH.URI()
1151 } else if originalSum {
1152 if mod, ok := result.modules[rootURI]; ok {
1158 // Handle the invalidated file; it may have new contents or not exist.
1160 delete(result.files, withoutURI)
1162 result.files[withoutURI] = currentFH
1164 // Make sure to remove the changed file from the unloadable set.
1165 delete(result.unloadableFiles, withoutURI)
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
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 {
1184 transitiveIDs[id] = newInvalidateMetadata
1185 for _, rid := range s.getImportedByLocked(id) {
1186 addRevDeps(rid, invalidateMetadata)
1189 for id, invalidateMetadata := range directIDs {
1190 addRevDeps(id, invalidateMetadata)
1193 // When modules change, we need to recompute their workspace directories,
1194 // as replace directives may have changed.
1196 result.workspaceDirectories = result.findWorkspaceDirectories(ctx)
1199 // Copy the package type information.
1200 for k, v := range s.packages {
1201 if _, ok := transitiveIDs[k.id]; ok {
1204 newGen.Inherit(v.handle)
1205 result.packages[k] = v
1207 // Copy the package analysis information.
1208 for k, v := range s.actions {
1209 if _, ok := transitiveIDs[k.pkg.id]; ok {
1212 newGen.Inherit(v.handle)
1213 result.actions[k] = v
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 {
1221 result.metadata[k] = v
1223 // Copy the URI to package ID mappings, skipping only those URIs whose
1224 // metadata will be reloaded in future calls to load.
1226 for k, ids := range s.ids {
1227 for _, id := range ids {
1228 if invalidateMetadata, ok := transitiveIDs[id]; invalidateMetadata && ok {
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
1240 if id == "command-line-arguments" {
1241 if invalidateMetadata, ok := transitiveIDs[id]; invalidateMetadata && ok {
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 {
1250 for _, uri := range s.metadata[id].goFiles {
1251 if _, ok := result.files[uri]; ok {
1261 result.workspacePackages[id] = pkgPath
1264 // Inherit all of the go.mod-related handles.
1265 for _, v := range result.modTidyHandles {
1266 newGen.Inherit(v.handle)
1268 for _, v := range result.modUpgradeHandles {
1269 newGen.Inherit(v.handle)
1271 for _, v := range result.modWhyHandles {
1272 newGen.Inherit(v.handle)
1274 for _, v := range result.parseModHandles {
1275 newGen.Inherit(v.handle)
1277 if result.workspaceModuleHandle != nil {
1278 newGen.Inherit(result.workspaceModuleHandle.handle)
1280 // Don't bother copying the importedBy graph,
1281 // as it changes each time we update metadata.
1283 var reinitialize reinitializeView
1285 reinitialize = maybeReinit
1287 if shouldReinitializeView {
1288 reinitialize = definitelyReinit
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{}
1296 return result, reinitialize
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.
1308 // This is a file we don't yet know about. Guess relevant packages by
1309 // considering files in the same directory.
1311 // Cache of FileInfo to avoid unnecessary stats for multiple files in the
1313 stats := make(map[string]struct {
1317 getInfo := func(dir string) (os.FileInfo, error) {
1318 if res, ok := stats[dir]; ok {
1319 return res.FileInfo, res.error
1321 fi, err := os.Stat(dir)
1322 stats[dir] = struct {
1328 dir := filepath.Dir(uri.Filename())
1329 fi, err := getInfo(dir)
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)
1342 if os.SameFile(fi, knownFI) {
1343 found = append(found, ids...)
1349 type reinitializeView int
1352 doNotReinit = reinitializeView(iota)
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 {
1366 o, ok := originalFH.(*overlay)
1367 if !ok || o == nil {
1370 return !o.saved && c.saved
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 {
1379 // If the file hasn't changed, there's no need to reload.
1380 if originalFH.FileIdentity() == currentFH.FileIdentity() {
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()))
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)
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 {
1401 importSet := make(map[string]struct{})
1402 for _, importSpec := range original.File.Imports {
1403 importSet[importSpec.Path.Value] = struct{}{}
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 {
1410 // If the import path is obviously not valid, we can skip reloading
1411 // metadata. For now, valid means properly quoted and without a
1413 path, err := strconv.Unquote(importSpec.Path.Value)
1420 if path[len(path)-1] == '/' {
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.
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{}{
1443 for _, m := range s.modules {
1444 fh, err := s.GetFile(ctx, m.modURI)
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)
1455 for _, r := range mod.File.Replace {
1456 // We may be replacing a module with a different version, not a path
1458 if r.New.Version != "" {
1461 dirs[span.URIFromPath(r.New.Path)] = struct{}{}
1467 func (s *snapshot) BuiltinPackage(ctx context.Context) (*source.BuiltinPackage, error) {
1468 s.AwaitInitialized(ctx)
1470 if s.builtin == nil {
1471 return nil, errors.Errorf("no builtin package for view %s", s.view.name)
1473 d, err := s.builtin.handle.Get(ctx, s.generation, s)
1477 data := d.(*builtinPackageData)
1478 return data.parsed, data.err
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))
1485 uri := span.URIFromPath(goFiles[0])
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)
1493 h := s.generation.Bind(fh.FileIdentity(), func(ctx context.Context, arg memoize.Arg) interface{} {
1494 snapshot := arg.(*snapshot)
1496 pgh := snapshot.parseGoHandle(ctx, fh, source.ParseFull)
1497 pgf, _, err := snapshot.parseGo(ctx, pgh)
1499 return &builtinPackageData{err: err}
1501 pkg, err := ast.NewPackage(snapshot.view.session.cache.fset, map[string]*ast.File{
1502 pgf.URI.Filename(): pgf.File,
1505 return &builtinPackageData{err: err}
1507 return &builtinPackageData{
1508 parsed: &source.BuiltinPackage{
1514 s.builtin = &builtinPackageHandle{handle: h}
1518 type workspaceModuleHandle struct {
1519 handle *memoize.Handle
1522 type workspaceModuleData struct {
1527 type workspaceModuleKey string
1529 func (wmh *workspaceModuleHandle) build(ctx context.Context, snapshot *snapshot) (*modfile.File, error) {
1530 v, err := wmh.handle.Get(ctx, snapshot.generation, snapshot)
1534 data := v.(*workspaceModuleData)
1535 return data.file, data.err
1538 func (s *snapshot) getWorkspaceModuleHandle(ctx context.Context) (*workspaceModuleHandle, error) {
1540 wsModule := s.workspaceModuleHandle
1542 if wsModule != nil {
1543 return wsModule, nil
1545 var fhs []source.FileHandle
1546 for _, mod := range s.modules {
1547 fh, err := s.GetFile(ctx, mod.modURI)
1551 fhs = append(fhs, fh)
1553 goplsModURI := span.URIFromPath(filepath.Join(s.view.Folder().Filename(), "gopls.mod"))
1554 goplsModFH, err := s.GetFile(ctx, goplsModURI)
1558 _, err = goplsModFH.Read()
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.
1569 return nil, errors.Errorf("error getting gopls.mod: %w", err)
1572 sort.Slice(fhs, func(i, j int) bool {
1573 return fhs[i].URI() < fhs[j].URI()
1576 for _, fh := range fhs {
1577 k += fh.FileIdentity().String()
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)
1584 return &workspaceModuleData{err: err}
1586 return &workspaceModuleData{file: parsed.File}
1588 s := arg.(*snapshot)
1589 data := &workspaceModuleData{}
1590 data.file, data.err = s.BuildWorkspaceModFile(ctx)
1593 wsModule = &workspaceModuleHandle{
1598 s.workspaceModuleHandle = wsModule
1599 return s.workspaceModuleHandle, nil
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")
1608 paths := make(map[string]*moduleRoot)
1609 for _, mod := range s.modules {
1610 fh, err := s.GetFile(ctx, mod.modURI)
1614 parsed, err := s.ParseMod(ctx, fh)
1618 if parsed.File == nil || parsed.File.Module == nil {
1619 return nil, fmt.Errorf("no module declaration for %s", mod.modURI)
1621 path := parsed.File.Module.Mod.Path
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"
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 {
1635 // Go back through all of the modules to handle any of their replace
1637 for _, module := range s.modules {
1638 fh, err := s.GetFile(ctx, module.modURI)
1642 pmf, err := s.ParseMod(ctx, fh)
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 {
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()
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)
1665 if err := file.AddReplace(rep.Old.Path, rep.Old.Version, newPath, newVersion); err != nil {
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 {
1682 sumURI := span.URIFromPath(sumFilename(modURI))
1683 if info, _ := os.Stat(sumURI.Filename()); info == nil {