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 // The snapshot's initialization state is controlled by the fields below.
51 // initializeOnce guards snapshot initialization. Each snapshot is
52 // initialized at most once: reinitialization is triggered on later snapshots
53 // by invalidating this field.
54 initializeOnce *sync.Once
55 // initializedErr holds the last error resulting from initialization. If
56 // initialization fails, we only retry when the the workspace modules change,
57 // to avoid too many go/packages calls.
60 // mu guards all of the maps in the snapshot.
63 // ids maps file URIs to package IDs.
64 // It may be invalidated on calls to go/packages.
65 ids map[span.URI][]packageID
67 // metadata maps file IDs to their associated metadata.
68 // It may invalidated on calls to go/packages.
69 metadata map[packageID]*metadata
71 // importedBy maps package IDs to the list of packages that import them.
72 importedBy map[packageID][]packageID
74 // files maps file URIs to their corresponding FileHandles.
75 // It may invalidated when a file's content changes.
76 files map[span.URI]source.VersionedFileHandle
78 // goFiles maps a parseKey to its parseGoHandle.
79 goFiles map[parseKey]*parseGoHandle
81 // packages maps a packageKey to a set of packageHandles to which that file belongs.
82 // It may be invalidated when a file's content changes.
83 packages map[packageKey]*packageHandle
85 // actions maps an actionkey to its actionHandle.
86 actions map[actionKey]*actionHandle
88 // workspacePackages contains the workspace's packages, which are loaded
89 // when the view is created.
90 workspacePackages map[packageID]packagePath
92 // unloadableFiles keeps track of files that we've failed to load.
93 unloadableFiles map[span.URI]struct{}
95 // parseModHandles keeps track of any ParseModHandles for the snapshot.
96 // The handles need not refer to only the view's go.mod file.
97 parseModHandles map[span.URI]*parseModHandle
99 // Preserve go.mod-related handles to avoid garbage-collecting the results
100 // of various calls to the go command. The handles need not refer to only
101 // the view's go.mod file.
102 modTidyHandles map[span.URI]*modTidyHandle
103 modUpgradeHandles map[span.URI]*modUpgradeHandle
104 modWhyHandles map[span.URI]*modWhyHandle
107 workspaceDirHandle *memoize.Handle
110 type packageKey struct {
111 mode source.ParseMode
115 type actionKey struct {
117 analyzer *analysis.Analyzer
120 func (s *snapshot) ID() uint64 {
124 func (s *snapshot) View() source.View {
128 func (s *snapshot) FileSet() *token.FileSet {
129 return s.view.session.cache.fset
132 func (s *snapshot) ModFiles() []span.URI {
134 for modURI := range s.workspace.activeModFiles() {
135 uris = append(uris, modURI)
140 func (s *snapshot) ValidBuildConfiguration() bool {
141 return validBuildConfiguration(s.view.rootURI, &s.view.workspaceInformation, s.workspace.activeModFiles())
144 // workspaceMode describes the way in which the snapshot's workspace should
146 func (s *snapshot) workspaceMode() workspaceMode {
147 var mode workspaceMode
149 // If the view has an invalid configuration, don't build the workspace
151 validBuildConfiguration := s.ValidBuildConfiguration()
152 if !validBuildConfiguration {
155 // If the view is not in a module and contains no modules, but still has a
156 // valid workspace configuration, do not create the workspace module.
157 // It could be using GOPATH or a different build system entirely.
158 if len(s.workspace.activeModFiles()) == 0 && validBuildConfiguration {
162 options := s.view.Options()
163 // The -modfile flag is available for Go versions >= 1.14.
164 if options.TempModfile && s.view.workspaceInformation.goversion >= 14 {
167 // If the user is intentionally limiting their workspace scope, don't
168 // enable multi-module workspace mode.
169 // TODO(rstambler): This should only change the calculation of the root,
171 if !options.ExpandWorkspaceToModule {
174 // The workspace module has been disabled by the user.
175 if !options.ExperimentalWorkspaceModule {
178 mode |= usesWorkspaceModule
182 // config returns the configuration used for the snapshot's interaction with
183 // the go/packages API. It uses the given working directory.
185 // TODO(rstambler): go/packages requires that we do not provide overlays for
186 // multiple modules in on config, so buildOverlay needs to filter overlays by
188 func (s *snapshot) config(ctx context.Context, inv *gocommand.Invocation) *packages.Config {
189 s.view.optionsMu.Lock()
190 verboseOutput := s.view.options.VerboseOutput
191 s.view.optionsMu.Unlock()
193 cfg := &packages.Config{
197 BuildFlags: inv.BuildFlags,
198 Mode: packages.NeedName |
200 packages.NeedCompiledGoFiles |
201 packages.NeedImports |
203 packages.NeedTypesSizes |
205 Fset: s.view.session.cache.fset,
206 Overlay: s.buildOverlay(),
207 ParseFile: func(*token.FileSet, string, []byte) (*ast.File, error) {
208 panic("go/packages must not be used to parse files")
210 Logf: func(format string, args ...interface{}) {
212 event.Log(ctx, fmt.Sprintf(format, args...))
217 packagesinternal.SetModFile(cfg, inv.ModFile)
218 packagesinternal.SetModFlag(cfg, inv.ModFlag)
219 // We want to type check cgo code if go/types supports it.
220 if typesinternal.SetUsesCgo(&types.Config{}) {
221 cfg.Mode |= packages.LoadMode(packagesinternal.TypecheckCgo)
223 packagesinternal.SetGoCmdRunner(cfg, s.view.session.gocmdRunner)
227 func (s *snapshot) RunGoCommandDirect(ctx context.Context, mode source.InvocationMode, inv *gocommand.Invocation) (*bytes.Buffer, error) {
228 _, inv, cleanup, err := s.goCommandInvocation(ctx, mode, inv)
234 return s.view.session.gocmdRunner.Run(ctx, *inv)
237 func (s *snapshot) RunGoCommandPiped(ctx context.Context, mode source.InvocationMode, inv *gocommand.Invocation, stdout, stderr io.Writer) error {
238 _, inv, cleanup, err := s.goCommandInvocation(ctx, mode, inv)
243 return s.view.session.gocmdRunner.RunPiped(ctx, *inv, stdout, stderr)
246 func (s *snapshot) goCommandInvocation(ctx context.Context, mode source.InvocationMode, inv *gocommand.Invocation) (tmpURI span.URI, updatedInv *gocommand.Invocation, cleanup func(), err error) {
247 s.view.optionsMu.Lock()
248 inv.Env = append(append(append(os.Environ(), s.view.options.EnvSlice()...), inv.Env...), "GO111MODULE="+s.view.go111module)
249 inv.BuildFlags = append([]string{}, s.view.options.BuildFlags...)
250 s.view.optionsMu.Unlock()
251 cleanup = func() {} // fallback
254 if s.workspaceMode()&moduleMode != 0 {
255 // Select the module context to use.
256 // If we're type checking, we need to use the workspace context, meaning
257 // the main (workspace) module. Otherwise, we should use the module for
258 // the passed-in working dir.
259 if mode == source.ForTypeChecking {
260 if s.workspaceMode()&usesWorkspaceModule == 0 {
261 for m := range s.workspace.activeModFiles() { // range to access the only element
267 tmpDir, err = s.getWorkspaceDir(ctx)
269 return "", nil, cleanup, err
271 inv.WorkingDir = tmpDir.Filename()
272 modURI = span.URIFromPath(filepath.Join(tmpDir.Filename(), "go.mod"))
275 modURI = s.GoModForFile(ctx, span.URIFromPath(inv.WorkingDir))
279 wantTempMod := mode != source.UpdateUserModFile
280 needTempMod := mode == source.WriteTemporaryModFile
281 tempMod := wantTempMod && s.workspaceMode()&tempModfile != 0
282 if needTempMod && !tempMod {
283 return "", nil, cleanup, source.ErrTmpModfileUnsupported
288 return "", nil, cleanup, fmt.Errorf("no go.mod file found in %s", inv.WorkingDir)
290 modFH, err := s.GetFile(ctx, modURI)
292 return "", nil, cleanup, err
294 // Use the go.sum if it happens to be available.
295 gosum := s.goSum(ctx, modURI)
296 tmpURI, cleanup, err = tempModFile(modFH, gosum)
298 return "", nil, cleanup, err
300 inv.ModFile = tmpURI.Filename()
303 var modContent []byte
305 modFH, err := s.GetFile(ctx, modURI)
307 return "", nil, cleanup, err
309 modContent, err = modFH.Read()
311 return "", nil, nil, err
314 modMod, err := s.needsModEqualsMod(ctx, modURI, modContent)
316 return "", nil, cleanup, err
322 return tmpURI, inv, cleanup, nil
325 func (s *snapshot) buildOverlay() map[string][]byte {
329 overlays := make(map[string][]byte)
330 for uri, fh := range s.files {
331 overlay, ok := fh.(*overlay)
338 // TODO(rstambler): Make sure not to send overlays outside of the current view.
339 overlays[uri.Filename()] = overlay.text
344 func hashUnsavedOverlays(files map[span.URI]source.VersionedFileHandle) string {
346 for uri, fh := range files {
347 if overlay, ok := fh.(*overlay); ok && !overlay.saved {
348 unsaved = append(unsaved, uri.Filename())
351 sort.Strings(unsaved)
352 return hashContents([]byte(strings.Join(unsaved, "")))
355 func (s *snapshot) PackagesForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode) ([]source.Package, error) {
356 ctx = event.Label(ctx, tag.URI.Of(uri))
358 phs, err := s.packageHandlesForFile(ctx, uri, mode)
362 var pkgs []source.Package
363 for _, ph := range phs {
364 pkg, err := ph.check(ctx, s)
368 pkgs = append(pkgs, pkg)
373 func (s *snapshot) PackageForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode, pkgPolicy source.PackageFilter) (source.Package, error) {
374 ctx = event.Label(ctx, tag.URI.Of(uri))
376 phs, err := s.packageHandlesForFile(ctx, uri, mode)
382 return nil, errors.Errorf("no packages")
386 for _, handle := range phs[1:] {
388 case source.WidestPackage:
389 if ph == nil || len(handle.CompiledGoFiles()) > len(ph.CompiledGoFiles()) {
392 case source.NarrowestPackage:
393 if ph == nil || len(handle.CompiledGoFiles()) < len(ph.CompiledGoFiles()) {
399 return nil, errors.Errorf("no packages in input")
402 return ph.check(ctx, s)
405 func (s *snapshot) packageHandlesForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode) ([]*packageHandle, error) {
406 // Check if we should reload metadata for the file. We don't invalidate IDs
407 // (though we should), so the IDs will be a better source of truth than the
408 // metadata. If there are no IDs for the file, then we should also reload.
409 fh, err := s.GetFile(ctx, uri)
413 if fh.Kind() != source.Go {
414 return nil, fmt.Errorf("no packages for non-Go file %s", uri)
416 ids := s.getIDsForURI(uri)
417 reload := len(ids) == 0
418 for _, id := range ids {
419 // Reload package metadata if any of the metadata has missing
420 // dependencies, in case something has changed since the last time we
422 if m := s.getMetadata(id); m == nil {
426 // TODO(golang/go#36918): Previously, we would reload any package with
427 // missing dependencies. This is expensive and results in too many
428 // calls to packages.Load. Determine what we should do instead.
431 if err := s.load(ctx, fileURI(uri)); err != nil {
435 // Get the list of IDs from the snapshot again, in case it has changed.
436 var phs []*packageHandle
437 for _, id := range s.getIDsForURI(uri) {
438 var parseModes []source.ParseMode
440 case source.TypecheckAll:
441 if s.workspaceParseMode(id) == source.ParseFull {
442 parseModes = []source.ParseMode{source.ParseFull}
444 parseModes = []source.ParseMode{source.ParseExported, source.ParseFull}
446 case source.TypecheckFull:
447 parseModes = []source.ParseMode{source.ParseFull}
448 case source.TypecheckWorkspace:
449 parseModes = []source.ParseMode{s.workspaceParseMode(id)}
452 for _, parseMode := range parseModes {
453 ph, err := s.buildPackageHandle(ctx, id, parseMode)
457 phs = append(phs, ph)
464 func (s *snapshot) GetReverseDependencies(ctx context.Context, id string) ([]source.Package, error) {
465 if err := s.awaitLoaded(ctx); err != nil {
468 ids := make(map[packageID]struct{})
469 s.transitiveReverseDependencies(packageID(id), ids)
471 // Make sure to delete the original package ID from the map.
472 delete(ids, packageID(id))
474 var pkgs []source.Package
475 for id := range ids {
476 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
480 pkgs = append(pkgs, pkg)
485 func (s *snapshot) checkedPackage(ctx context.Context, id packageID, mode source.ParseMode) (*pkg, error) {
486 ph, err := s.buildPackageHandle(ctx, id, mode)
490 return ph.check(ctx, s)
493 // transitiveReverseDependencies populates the uris map with file URIs
494 // belonging to the provided package and its transitive reverse dependencies.
495 func (s *snapshot) transitiveReverseDependencies(id packageID, ids map[packageID]struct{}) {
496 if _, ok := ids[id]; ok {
499 if s.getMetadata(id) == nil {
503 importedBy := s.getImportedBy(id)
504 for _, parentID := range importedBy {
505 s.transitiveReverseDependencies(parentID, ids)
509 func (s *snapshot) getGoFile(key parseKey) *parseGoHandle {
512 return s.goFiles[key]
515 func (s *snapshot) addGoFile(key parseKey, pgh *parseGoHandle) *parseGoHandle {
518 if existing, ok := s.goFiles[key]; ok {
525 func (s *snapshot) getParseModHandle(uri span.URI) *parseModHandle {
528 return s.parseModHandles[uri]
531 func (s *snapshot) getModWhyHandle(uri span.URI) *modWhyHandle {
534 return s.modWhyHandles[uri]
537 func (s *snapshot) getModUpgradeHandle(uri span.URI) *modUpgradeHandle {
540 return s.modUpgradeHandles[uri]
543 func (s *snapshot) getModTidyHandle(uri span.URI) *modTidyHandle {
546 return s.modTidyHandles[uri]
549 func (s *snapshot) getImportedBy(id packageID) []packageID {
552 return s.getImportedByLocked(id)
555 func (s *snapshot) getImportedByLocked(id packageID) []packageID {
556 // If we haven't rebuilt the import graph since creating the snapshot.
557 if len(s.importedBy) == 0 {
558 s.rebuildImportGraph()
560 return s.importedBy[id]
563 func (s *snapshot) clearAndRebuildImportGraph() {
567 // Completely invalidate the original map.
568 s.importedBy = make(map[packageID][]packageID)
569 s.rebuildImportGraph()
572 func (s *snapshot) rebuildImportGraph() {
573 for id, m := range s.metadata {
574 for _, importID := range m.deps {
575 s.importedBy[importID] = append(s.importedBy[importID], id)
580 func (s *snapshot) addPackageHandle(ph *packageHandle) *packageHandle {
584 // If the package handle has already been cached,
585 // return the cached handle instead of overriding it.
586 if ph, ok := s.packages[ph.packageKey()]; ok {
589 s.packages[ph.packageKey()] = ph
593 func (s *snapshot) workspacePackageIDs() (ids []packageID) {
597 for id := range s.workspacePackages {
598 ids = append(ids, id)
603 func (s *snapshot) WorkspaceDirectories(ctx context.Context) []span.URI {
604 return s.workspace.dirs(ctx, s)
607 func (s *snapshot) WorkspacePackages(ctx context.Context) ([]source.Package, error) {
608 if err := s.awaitLoaded(ctx); err != nil {
611 var pkgs []source.Package
612 for _, pkgID := range s.workspacePackageIDs() {
613 pkg, err := s.checkedPackage(ctx, pkgID, s.workspaceParseMode(pkgID))
617 pkgs = append(pkgs, pkg)
622 func (s *snapshot) KnownPackages(ctx context.Context) ([]source.Package, error) {
623 if err := s.awaitLoaded(ctx); err != nil {
627 // The WorkspaceSymbols implementation relies on this function returning
628 // workspace packages first.
629 ids := s.workspacePackageIDs()
631 for id := range s.metadata {
632 if _, ok := s.workspacePackages[id]; ok {
635 ids = append(ids, id)
639 var pkgs []source.Package
640 for _, id := range ids {
641 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
645 pkgs = append(pkgs, pkg)
650 func (s *snapshot) CachedImportPaths(ctx context.Context) (map[string]source.Package, error) {
651 // Don't reload workspace package metadata.
652 // This function is meant to only return currently cached information.
653 s.AwaitInitialized(ctx)
658 results := map[string]source.Package{}
659 for _, ph := range s.packages {
660 cachedPkg, err := ph.cached(s.generation)
664 for importPath, newPkg := range cachedPkg.imports {
665 if oldPkg, ok := results[string(importPath)]; ok {
666 // Using the same trick as NarrowestPackage, prefer non-variants.
667 if len(newPkg.compiledGoFiles) < len(oldPkg.(*pkg).compiledGoFiles) {
668 results[string(importPath)] = newPkg
671 results[string(importPath)] = newPkg
678 func (s *snapshot) GoModForFile(ctx context.Context, uri span.URI) span.URI {
680 for modURI := range s.workspace.activeModFiles() {
681 if !source.InDir(dirURI(modURI).Filename(), uri.Filename()) {
684 if len(modURI) > len(match) {
691 func (s *snapshot) getPackage(id packageID, mode source.ParseMode) *packageHandle {
699 return s.packages[key]
702 func (s *snapshot) getActionHandle(id packageID, m source.ParseMode, a *analysis.Analyzer) *actionHandle {
713 return s.actions[key]
716 func (s *snapshot) addActionHandle(ah *actionHandle) *actionHandle {
721 analyzer: ah.analyzer,
727 if ah, ok := s.actions[key]; ok {
734 func (s *snapshot) getIDsForURI(uri span.URI) []packageID {
741 func (s *snapshot) getMetadataForURILocked(uri span.URI) (metadata []*metadata) {
742 // TODO(matloob): uri can be a file or directory. Should we update the mappings
743 // to map directories to their contained packages?
745 for _, id := range s.ids[uri] {
746 if m, ok := s.metadata[id]; ok {
747 metadata = append(metadata, m)
753 func (s *snapshot) getMetadata(id packageID) *metadata {
757 return s.metadata[id]
760 func (s *snapshot) addID(uri span.URI, id packageID) {
764 for i, existingID := range s.ids[uri] {
765 // TODO: We should make sure not to set duplicate IDs,
766 // and instead panic here. This can be done by making sure not to
767 // reset metadata information for packages we've already seen.
768 if existingID == id {
771 // If we are setting a real ID, when the package had only previously
772 // had a command-line-arguments ID, we should just replace it.
773 if existingID == "command-line-arguments" {
775 // Delete command-line-arguments if it was a workspace package.
776 delete(s.workspacePackages, existingID)
780 s.ids[uri] = append(s.ids[uri], id)
783 func (s *snapshot) isWorkspacePackage(id packageID) (packagePath, bool) {
787 scope, ok := s.workspacePackages[id]
791 func (s *snapshot) FindFile(uri span.URI) source.VersionedFileHandle {
792 f, err := s.view.getFile(uri)
800 return s.files[f.URI()]
803 // GetVersionedFile returns a File for the given URI. If the file is unknown it
804 // is added to the managed set.
806 // GetVersionedFile succeeds even if the file does not exist. A non-nil error return
807 // indicates some type of internal error, for example if ctx is cancelled.
808 func (s *snapshot) GetVersionedFile(ctx context.Context, uri span.URI) (source.VersionedFileHandle, error) {
809 f, err := s.view.getFile(uri)
816 return s.getFileLocked(ctx, f)
819 // GetFile implements the fileSource interface by wrapping GetVersionedFile.
820 func (s *snapshot) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) {
821 return s.GetVersionedFile(ctx, uri)
824 func (s *snapshot) getFileLocked(ctx context.Context, f *fileBase) (source.VersionedFileHandle, error) {
825 if fh, ok := s.files[f.URI()]; ok {
829 fh, err := s.view.session.cache.getFile(ctx, f.URI())
833 closed := &closedFile{fh}
834 s.files[f.URI()] = closed
838 func (s *snapshot) IsOpen(uri span.URI) bool {
842 _, open := s.files[uri].(*overlay)
846 func (s *snapshot) awaitLoaded(ctx context.Context) error {
847 // Do not return results until the snapshot's view has been initialized.
848 s.AwaitInitialized(ctx)
850 if err := s.reloadWorkspace(ctx); err != nil {
853 if err := s.reloadOrphanedFiles(ctx); err != nil {
856 // If we still have absolutely no metadata, check if the view failed to
857 // initialize and return any errors.
858 // TODO(rstambler): Should we clear the error after we return it?
861 if len(s.metadata) == 0 {
862 return s.initializedErr
867 func (s *snapshot) AwaitInitialized(ctx context.Context) {
871 case <-s.view.initialWorkspaceLoad:
873 // We typically prefer to run something as intensive as the IWL without
874 // blocking. I'm not sure if there is a way to do that here.
875 s.initialize(ctx, false)
878 // reloadWorkspace reloads the metadata for all invalidated workspace packages.
879 func (s *snapshot) reloadWorkspace(ctx context.Context) error {
880 // If the view's build configuration is invalid, we cannot reload by
881 // package path. Just reload the directory instead.
882 if !s.ValidBuildConfiguration() {
883 return s.load(ctx, viewLoadScope("LOAD_INVALID_VIEW"))
886 // See which of the workspace packages are missing metadata.
888 pkgPathSet := map[packagePath]struct{}{}
889 for id, pkgPath := range s.workspacePackages {
890 // Don't try to reload "command-line-arguments" directly.
891 if pkgPath == "command-line-arguments" {
894 if s.metadata[id] == nil {
895 pkgPathSet[pkgPath] = struct{}{}
900 if len(pkgPathSet) == 0 {
903 var pkgPaths []interface{}
904 for pkgPath := range pkgPathSet {
905 pkgPaths = append(pkgPaths, pkgPath)
907 return s.load(ctx, pkgPaths...)
910 func (s *snapshot) reloadOrphanedFiles(ctx context.Context) error {
911 // When we load ./... or a package path directly, we may not get packages
912 // that exist only in overlays. As a workaround, we search all of the files
913 // available in the snapshot and reload their metadata individually using a
914 // file= query if the metadata is unavailable.
915 scopes := s.orphanedFileScopes()
916 if len(scopes) == 0 {
920 err := s.load(ctx, scopes...)
922 // If we failed to load some files, i.e. they have no metadata,
923 // mark the failures so we don't bother retrying until the file's
926 // TODO(rstambler): This may be an overestimate if the load stopped
927 // early for an unrelated errors. Add a fallback?
929 // Check for context cancellation so that we don't incorrectly mark files
930 // as unloadable, but don't return before setting all workspace packages.
931 if ctx.Err() == nil && err != nil {
932 event.Error(ctx, "reloadOrphanedFiles: failed to load", err, tag.Query.Of(scopes))
934 for _, scope := range scopes {
935 uri := span.URI(scope.(fileURI))
936 if s.getMetadataForURILocked(uri) == nil {
937 s.unloadableFiles[uri] = struct{}{}
945 func (s *snapshot) orphanedFileScopes() []interface{} {
949 scopeSet := make(map[span.URI]struct{})
950 for uri, fh := range s.files {
951 // Don't try to reload metadata for go.mod files.
952 if fh.Kind() != source.Go {
955 // If the URI doesn't belong to this view, then it's not in a workspace
956 // package and should not be reloaded directly.
957 if !contains(s.view.session.viewsOf(uri), s.view) {
960 // If the file is not open and is in a vendor directory, don't treat it
961 // like a workspace package.
962 if _, ok := fh.(*overlay); !ok && inVendor(uri) {
965 // Don't reload metadata for files we've already deemed unloadable.
966 if _, ok := s.unloadableFiles[uri]; ok {
969 if s.getMetadataForURILocked(uri) == nil {
970 scopeSet[uri] = struct{}{}
973 var scopes []interface{}
974 for uri := range scopeSet {
975 scopes = append(scopes, fileURI(uri))
980 func contains(views []*View, view *View) bool {
981 for _, v := range views {
989 func inVendor(uri span.URI) bool {
990 toSlash := filepath.ToSlash(uri.Filename())
991 if !strings.Contains(toSlash, "/vendor/") {
994 // Only packages in _subdirectories_ of /vendor/ are considered vendored
995 // (/vendor/a/foo.go is vendored, /vendor/foo.go is not).
996 split := strings.Split(toSlash, "/vendor/")
1000 return strings.Contains(split[1], "/")
1003 func generationName(v *View, snapshotID uint64) string {
1004 return fmt.Sprintf("v%v/%v", v.id, snapshotID)
1007 func (s *snapshot) clone(ctx context.Context, changes map[span.URI]*fileChange, forceReloadMetadata bool) (*snapshot, bool) {
1008 // Track some important types of changes.
1013 newWorkspace, workspaceChanged := s.workspace.invalidate(ctx, changes)
1018 newGen := s.view.session.cache.store.Generation(generationName(s.view, s.id+1))
1019 result := &snapshot{
1024 initializeOnce: s.initializeOnce,
1025 initializedErr: s.initializedErr,
1026 ids: make(map[span.URI][]packageID),
1027 importedBy: make(map[packageID][]packageID),
1028 metadata: make(map[packageID]*metadata),
1029 packages: make(map[packageKey]*packageHandle),
1030 actions: make(map[actionKey]*actionHandle),
1031 files: make(map[span.URI]source.VersionedFileHandle),
1032 goFiles: make(map[parseKey]*parseGoHandle),
1033 workspacePackages: make(map[packageID]packagePath),
1034 unloadableFiles: make(map[span.URI]struct{}),
1035 parseModHandles: make(map[span.URI]*parseModHandle),
1036 modTidyHandles: make(map[span.URI]*modTidyHandle),
1037 modUpgradeHandles: make(map[span.URI]*modUpgradeHandle),
1038 modWhyHandles: make(map[span.URI]*modWhyHandle),
1039 workspace: newWorkspace,
1042 if !workspaceChanged && s.workspaceDirHandle != nil {
1043 result.workspaceDirHandle = s.workspaceDirHandle
1044 newGen.Inherit(s.workspaceDirHandle)
1047 if s.builtin != nil {
1048 newGen.Inherit(s.builtin.handle)
1051 // Copy all of the FileHandles.
1052 for k, v := range s.files {
1056 // Copy the set of unloadable files.
1057 for k, v := range s.unloadableFiles {
1058 result.unloadableFiles[k] = v
1060 // Copy all of the modHandles.
1061 for k, v := range s.parseModHandles {
1062 result.parseModHandles[k] = v
1065 for k, v := range s.goFiles {
1066 if _, ok := changes[k.file.URI]; ok {
1069 newGen.Inherit(v.handle)
1070 newGen.Inherit(v.astCacheHandle)
1071 result.goFiles[k] = v
1074 // Copy all of the go.mod-related handles. They may be invalidated later,
1075 // so we inherit them at the end of the function.
1076 for k, v := range s.modTidyHandles {
1077 if _, ok := changes[k]; ok {
1080 result.modTidyHandles[k] = v
1082 for k, v := range s.modUpgradeHandles {
1083 if _, ok := changes[k]; ok {
1086 result.modUpgradeHandles[k] = v
1088 for k, v := range s.modWhyHandles {
1089 if _, ok := changes[k]; ok {
1092 result.modWhyHandles[k] = v
1095 // directIDs keeps track of package IDs that have directly changed.
1096 // It maps id->invalidateMetadata.
1097 directIDs := map[packageID]bool{}
1098 // Invalidate all package metadata if the workspace module has changed.
1099 if workspaceChanged {
1100 for k := range s.metadata {
1105 for uri, change := range changes {
1106 // Maybe reinitialize the view if we see a change in the vendor
1109 vendorChanged = true
1112 // The original FileHandle for this URI is cached on the snapshot.
1113 originalFH := s.files[uri]
1115 // Check if the file's package name or imports have changed,
1116 // and if so, invalidate this file's packages' metadata.
1117 invalidateMetadata := forceReloadMetadata || s.shouldInvalidateMetadata(ctx, result, originalFH, change.fileHandle)
1119 // Mark all of the package IDs containing the given file.
1120 // TODO: if the file has moved into a new package, we should invalidate that too.
1121 filePackages := guessPackagesForURI(uri, s.ids)
1122 for _, id := range filePackages {
1123 directIDs[id] = directIDs[id] || invalidateMetadata
1126 // Invalidate the previous modTidyHandle if any of the files have been
1127 // saved or if any of the metadata has been invalidated.
1128 if invalidateMetadata || fileWasSaved(originalFH, change.fileHandle) {
1129 // TODO(rstambler): Only delete mod handles for which the
1130 // withoutURI is relevant.
1131 for k := range s.modTidyHandles {
1132 delete(result.modTidyHandles, k)
1134 for k := range s.modUpgradeHandles {
1135 delete(result.modUpgradeHandles, k)
1137 for k := range s.modWhyHandles {
1138 delete(result.modWhyHandles, k)
1142 // If the view's go.mod file's contents have changed, invalidate
1143 // the metadata for every known package in the snapshot.
1144 delete(result.parseModHandles, uri)
1145 if _, ok := result.workspace.activeModFiles()[uri]; ok {
1146 modulesChanged = true
1149 // Handle the invalidated file; it may have new contents or not exist.
1151 delete(result.files, uri)
1153 result.files[uri] = change.fileHandle
1155 // Make sure to remove the changed file from the unloadable set.
1156 delete(result.unloadableFiles, uri)
1159 // Invalidate reverse dependencies too.
1160 // TODO(heschi): figure out the locking model and use transitiveReverseDeps?
1161 // transitiveIDs keeps track of transitive reverse dependencies.
1162 // If an ID is present in the map, invalidate its types.
1163 // If an ID's value is true, invalidate its metadata too.
1164 transitiveIDs := make(map[packageID]bool)
1165 var addRevDeps func(packageID, bool)
1166 addRevDeps = func(id packageID, invalidateMetadata bool) {
1167 current, seen := transitiveIDs[id]
1168 newInvalidateMetadata := current || invalidateMetadata
1170 // If we've already seen this ID, and the value of invalidate
1171 // metadata has not changed, we can return early.
1172 if seen && current == newInvalidateMetadata {
1175 transitiveIDs[id] = newInvalidateMetadata
1176 for _, rid := range s.getImportedByLocked(id) {
1177 addRevDeps(rid, invalidateMetadata)
1180 for id, invalidateMetadata := range directIDs {
1181 addRevDeps(id, invalidateMetadata)
1184 // Copy the package type information.
1185 for k, v := range s.packages {
1186 if _, ok := transitiveIDs[k.id]; ok {
1189 newGen.Inherit(v.handle)
1190 result.packages[k] = v
1192 // Copy the package analysis information.
1193 for k, v := range s.actions {
1194 if _, ok := transitiveIDs[k.pkg.id]; ok {
1197 newGen.Inherit(v.handle)
1198 result.actions[k] = v
1200 // Copy the package metadata. We only need to invalidate packages directly
1201 // containing the affected file, and only if it changed in a relevant way.
1202 for k, v := range s.metadata {
1203 if invalidateMetadata, ok := transitiveIDs[k]; invalidateMetadata && ok {
1206 result.metadata[k] = v
1208 // Copy the URI to package ID mappings, skipping only those URIs whose
1209 // metadata will be reloaded in future calls to load.
1211 for k, ids := range s.ids {
1212 for _, id := range ids {
1213 if invalidateMetadata, ok := transitiveIDs[id]; invalidateMetadata && ok {
1219 // Copy the set of initally loaded packages.
1220 for id, pkgPath := range s.workspacePackages {
1221 // Packages with the id "command-line-arguments" are generated by the
1222 // go command when the user is outside of GOPATH and outside of a
1223 // module. Do not cache them as workspace packages for longer than
1225 if id == "command-line-arguments" {
1226 if invalidateMetadata, ok := transitiveIDs[id]; invalidateMetadata && ok {
1231 // If all the files we know about in a package have been deleted,
1232 // the package is gone and we should no longer try to load it.
1233 if m := s.metadata[id]; m != nil {
1235 for _, uri := range s.metadata[id].goFiles {
1236 if _, ok := result.files[uri]; ok {
1246 result.workspacePackages[id] = pkgPath
1249 // Inherit all of the go.mod-related handles.
1250 for _, v := range result.modTidyHandles {
1251 newGen.Inherit(v.handle)
1253 for _, v := range result.modUpgradeHandles {
1254 newGen.Inherit(v.handle)
1256 for _, v := range result.modWhyHandles {
1257 newGen.Inherit(v.handle)
1259 for _, v := range result.parseModHandles {
1260 newGen.Inherit(v.handle)
1262 // Don't bother copying the importedBy graph,
1263 // as it changes each time we update metadata.
1265 // If the snapshot's workspace mode has changed, the packages loaded using
1266 // the previous mode are no longer relevant, so clear them out.
1267 if s.workspaceMode() != result.workspaceMode() {
1268 result.workspacePackages = map[packageID]packagePath{}
1271 // The snapshot may need to be reinitialized.
1272 if modulesChanged || workspaceChanged || vendorChanged {
1273 if workspaceChanged || result.initializedErr != nil {
1274 result.initializeOnce = &sync.Once{}
1277 return result, workspaceChanged
1280 // guessPackagesForURI returns all packages related to uri. If we haven't seen this
1281 // URI before, we guess based on files in the same directory. This is of course
1282 // incorrect in build systems where packages are not organized by directory.
1283 func guessPackagesForURI(uri span.URI, known map[span.URI][]packageID) []packageID {
1284 packages := known[uri]
1285 if len(packages) > 0 {
1286 // We've seen this file before.
1289 // This is a file we don't yet know about. Guess relevant packages by
1290 // considering files in the same directory.
1292 // Cache of FileInfo to avoid unnecessary stats for multiple files in the
1294 stats := make(map[string]struct {
1298 getInfo := func(dir string) (os.FileInfo, error) {
1299 if res, ok := stats[dir]; ok {
1300 return res.FileInfo, res.error
1302 fi, err := os.Stat(dir)
1303 stats[dir] = struct {
1309 dir := filepath.Dir(uri.Filename())
1310 fi, err := getInfo(dir)
1315 // Aggregate all possibly relevant package IDs.
1316 var found []packageID
1317 for knownURI, ids := range known {
1318 knownDir := filepath.Dir(knownURI.Filename())
1319 knownFI, err := getInfo(knownDir)
1323 if os.SameFile(fi, knownFI) {
1324 found = append(found, ids...)
1330 // fileWasSaved reports whether the FileHandle passed in has been saved. It
1331 // accomplishes this by checking to see if the original and current FileHandles
1332 // are both overlays, and if the current FileHandle is saved while the original
1333 // FileHandle was not saved.
1334 func fileWasSaved(originalFH, currentFH source.FileHandle) bool {
1335 c, ok := currentFH.(*overlay)
1336 if !ok || c == nil {
1339 o, ok := originalFH.(*overlay)
1340 if !ok || o == nil {
1343 return !o.saved && c.saved
1346 // shouldInvalidateMetadata reparses a file's package and import declarations to
1347 // determine if the file requires a metadata reload.
1348 func (s *snapshot) shouldInvalidateMetadata(ctx context.Context, newSnapshot *snapshot, originalFH, currentFH source.FileHandle) bool {
1349 if originalFH == nil {
1352 // If the file hasn't changed, there's no need to reload.
1353 if originalFH.FileIdentity() == currentFH.FileIdentity() {
1356 // If a go.mod in the workspace has been changed, invalidate metadata.
1357 if kind := originalFH.Kind(); kind == source.Mod {
1358 return source.InDir(filepath.Dir(s.view.rootURI.Filename()), filepath.Dir(originalFH.URI().Filename()))
1360 // Get the original and current parsed files in order to check package name
1361 // and imports. Use the new snapshot to parse to avoid modifying the
1362 // current snapshot.
1363 original, originalErr := newSnapshot.ParseGo(ctx, originalFH, source.ParseHeader)
1364 current, currentErr := newSnapshot.ParseGo(ctx, currentFH, source.ParseHeader)
1365 if originalErr != nil || currentErr != nil {
1366 return (originalErr == nil) != (currentErr == nil)
1368 // Check if the package's metadata has changed. The cases handled are:
1369 // 1. A package's name has changed
1370 // 2. A file's imports have changed
1371 if original.File.Name.Name != current.File.Name.Name {
1374 importSet := make(map[string]struct{})
1375 for _, importSpec := range original.File.Imports {
1376 importSet[importSpec.Path.Value] = struct{}{}
1378 // If any of the current imports were not in the original imports.
1379 for _, importSpec := range current.File.Imports {
1380 if _, ok := importSet[importSpec.Path.Value]; ok {
1383 // If the import path is obviously not valid, we can skip reloading
1384 // metadata. For now, valid means properly quoted and without a
1386 path, err := strconv.Unquote(importSpec.Path.Value)
1393 if path[len(path)-1] == '/' {
1401 func (s *snapshot) BuiltinPackage(ctx context.Context) (*source.BuiltinPackage, error) {
1402 s.AwaitInitialized(ctx)
1404 if s.builtin == nil {
1405 return nil, errors.Errorf("no builtin package for view %s", s.view.name)
1407 d, err := s.builtin.handle.Get(ctx, s.generation, s)
1411 data := d.(*builtinPackageData)
1412 return data.parsed, data.err
1415 func (s *snapshot) buildBuiltinPackage(ctx context.Context, goFiles []string) error {
1416 if len(goFiles) != 1 {
1417 return errors.Errorf("only expected 1 file, got %v", len(goFiles))
1419 uri := span.URIFromPath(goFiles[0])
1421 // Get the FileHandle through the cache to avoid adding it to the snapshot
1422 // and to get the file content from disk.
1423 fh, err := s.view.session.cache.getFile(ctx, uri)
1427 h := s.generation.Bind(fh.FileIdentity(), func(ctx context.Context, arg memoize.Arg) interface{} {
1428 snapshot := arg.(*snapshot)
1430 pgh := snapshot.parseGoHandle(ctx, fh, source.ParseFull)
1431 pgf, _, err := snapshot.parseGo(ctx, pgh)
1433 return &builtinPackageData{err: err}
1435 pkg, err := ast.NewPackage(snapshot.view.session.cache.fset, map[string]*ast.File{
1436 pgf.URI.Filename(): pgf.File,
1439 return &builtinPackageData{err: err}
1441 return &builtinPackageData{
1442 parsed: &source.BuiltinPackage{
1448 s.builtin = &builtinPackageHandle{handle: h}
1452 // BuildGoplsMod generates a go.mod file for all modules in the workspace. It
1453 // bypasses any existing gopls.mod.
1454 func BuildGoplsMod(ctx context.Context, root span.URI, fs source.FileSource) (*modfile.File, error) {
1455 allModules, err := findAllModules(ctx, root)
1459 return buildWorkspaceModFile(ctx, allModules, fs)
1462 // TODO(rfindley): move this to workspacemodule.go
1463 func buildWorkspaceModFile(ctx context.Context, modFiles map[span.URI]struct{}, fs source.FileSource) (*modfile.File, error) {
1464 file := &modfile.File{}
1465 file.AddModuleStmt("gopls-workspace")
1467 paths := make(map[string]span.URI)
1468 for modURI := range modFiles {
1469 fh, err := fs.GetFile(ctx, modURI)
1473 content, err := fh.Read()
1477 parsed, err := modfile.Parse(fh.URI().Filename(), content, nil)
1481 if file == nil || parsed.Module == nil {
1482 return nil, fmt.Errorf("no module declaration for %s", modURI)
1484 path := parsed.Module.Mod.Path
1485 paths[path] = modURI
1486 // If the module's path includes a major version, we expect it to have
1487 // a matching major version.
1488 _, majorVersion, _ := module.SplitPathVersion(path)
1489 if majorVersion == "" {
1490 majorVersion = "/v0"
1492 majorVersion = strings.TrimLeft(majorVersion, "/.") // handle gopkg.in versions
1493 file.AddNewRequire(path, source.WorkspaceModuleVersion(majorVersion), false)
1494 if err := file.AddReplace(path, "", dirURI(modURI).Filename(), ""); err != nil {
1498 // Go back through all of the modules to handle any of their replace
1500 for modURI := range modFiles {
1501 fh, err := fs.GetFile(ctx, modURI)
1505 content, err := fh.Read()
1509 parsed, err := modfile.Parse(fh.URI().Filename(), content, nil)
1513 // If any of the workspace modules have replace directives, they need
1514 // to be reflected in the workspace module.
1515 for _, rep := range parsed.Replace {
1516 // Don't replace any modules that are in our workspace--we should
1517 // always use the version in the workspace.
1518 if _, ok := paths[rep.Old.Path]; ok {
1521 newPath := rep.New.Path
1522 newVersion := rep.New.Version
1523 // If a replace points to a module in the workspace, make sure we
1524 // direct it to version of the module in the workspace.
1525 if m, ok := paths[rep.New.Path]; ok {
1526 newPath = dirURI(m).Filename()
1528 } else if rep.New.Version == "" && !filepath.IsAbs(rep.New.Path) {
1529 // Make any relative paths absolute.
1530 newPath = filepath.Join(dirURI(modURI).Filename(), rep.New.Path)
1532 if err := file.AddReplace(rep.Old.Path, rep.Old.Version, newPath, newVersion); err != nil {