blob: d1d2b1fb7b9b7f74904d742069769cad625354c8 [file] [log] [blame]
Robert Findleyb15dac22022-08-30 14:40:12 -04001// 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
5package cache
6
7import (
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "go/ast"
13 "go/token"
14 "go/types"
15 "io"
16 "io/ioutil"
17 "log"
18 "os"
19 "path/filepath"
20 "regexp"
21 "runtime"
22 "sort"
23 "strconv"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "unsafe"
28
29 "golang.org/x/mod/modfile"
30 "golang.org/x/mod/module"
31 "golang.org/x/mod/semver"
32 "golang.org/x/sync/errgroup"
33 "golang.org/x/tools/go/packages"
Robert Findleyb15dac22022-08-30 14:40:12 -040034 "golang.org/x/tools/gopls/internal/lsp/source"
Robert Findley9c639112022-09-28 12:03:51 -040035 "golang.org/x/tools/internal/bug"
36 "golang.org/x/tools/internal/event"
37 "golang.org/x/tools/internal/event/tag"
38 "golang.org/x/tools/internal/gocommand"
Robert Findleyb15dac22022-08-30 14:40:12 -040039 "golang.org/x/tools/internal/memoize"
40 "golang.org/x/tools/internal/packagesinternal"
41 "golang.org/x/tools/internal/persistent"
42 "golang.org/x/tools/internal/span"
43 "golang.org/x/tools/internal/typesinternal"
44)
45
46type snapshot struct {
47 id uint64
48 view *View
49
50 cancel func()
51 backgroundCtx context.Context
52
53 store *memoize.Store // cache of handles shared by all snapshots
54
55 refcount sync.WaitGroup // number of references
56 destroyedBy *string // atomically set to non-nil in Destroy once refcount = 0
57
58 // initialized reports whether the snapshot has been initialized. Concurrent
59 // initialization is guarded by the view.initializationSema. Each snapshot is
60 // initialized at most once: concurrent initialization is guarded by
61 // view.initializationSema.
62 initialized bool
63 // initializedErr holds the last error resulting from initialization. If
64 // initialization fails, we only retry when the the workspace modules change,
65 // to avoid too many go/packages calls.
66 initializedErr *source.CriticalError
67
68 // mu guards all of the maps in the snapshot, as well as the builtin URI.
69 mu sync.Mutex
70
71 // builtin pins the AST and package for builtin.go in memory.
72 builtin span.URI
73
74 // meta holds loaded metadata.
75 //
76 // meta is guarded by mu, but the metadataGraph itself is immutable.
77 // TODO(rfindley): in many places we hold mu while operating on meta, even
78 // though we only need to hold mu while reading the pointer.
79 meta *metadataGraph
80
81 // files maps file URIs to their corresponding FileHandles.
82 // It may invalidated when a file's content changes.
83 files filesMap
84
85 // parsedGoFiles maps a parseKey to the handle of the future result of parsing it.
86 parsedGoFiles *persistent.Map // from parseKey to *memoize.Promise[parseGoResult]
87
88 // parseKeysByURI records the set of keys of parsedGoFiles that
89 // need to be invalidated for each URI.
90 // TODO(adonovan): opt: parseKey = ParseMode + URI, so this could
91 // be just a set of ParseModes, or we could loop over AllParseModes.
92 parseKeysByURI parseKeysByURIMap
93
94 // symbolizeHandles maps each file URI to a handle for the future
95 // result of computing the symbols declared in that file.
96 symbolizeHandles *persistent.Map // from span.URI to *memoize.Promise[symbolizeResult]
97
98 // packages maps a packageKey to a *packageHandle.
99 // It may be invalidated when a file's content changes.
100 //
101 // Invariants to preserve:
102 // - packages.Get(id).m.Metadata == meta.metadata[id].Metadata for all ids
103 // - if a package is in packages, then all of its dependencies should also
104 // be in packages, unless there is a missing import
105 packages *persistent.Map // from packageKey to *memoize.Promise[*packageHandle]
106
107 // isActivePackageCache maps package ID to the cached value if it is active or not.
108 // It may be invalidated when metadata changes or a new file is opened or closed.
109 isActivePackageCache isActivePackageCacheMap
110
111 // actions maps an actionKey to the handle for the future
112 // result of execution an analysis pass on a package.
113 actions *persistent.Map // from actionKey to *actionHandle
114
115 // workspacePackages contains the workspace's packages, which are loaded
116 // when the view is created.
117 workspacePackages map[PackageID]PackagePath
118
119 // shouldLoad tracks packages that need to be reloaded, mapping a PackageID
120 // to the package paths that should be used to reload it
121 //
122 // When we try to load a package, we clear it from the shouldLoad map
123 // regardless of whether the load succeeded, to prevent endless loads.
124 shouldLoad map[PackageID][]PackagePath
125
126 // unloadableFiles keeps track of files that we've failed to load.
127 unloadableFiles map[span.URI]struct{}
128
129 // parseModHandles keeps track of any parseModHandles for the snapshot.
130 // The handles need not refer to only the view's go.mod file.
131 parseModHandles *persistent.Map // from span.URI to *memoize.Promise[parseModResult]
132
133 // parseWorkHandles keeps track of any parseWorkHandles for the snapshot.
134 // The handles need not refer to only the view's go.work file.
135 parseWorkHandles *persistent.Map // from span.URI to *memoize.Promise[parseWorkResult]
136
137 // Preserve go.mod-related handles to avoid garbage-collecting the results
138 // of various calls to the go command. The handles need not refer to only
139 // the view's go.mod file.
140 modTidyHandles *persistent.Map // from span.URI to *memoize.Promise[modTidyResult]
141 modWhyHandles *persistent.Map // from span.URI to *memoize.Promise[modWhyResult]
142
143 workspace *workspace // (not guarded by mu)
144
145 // The cached result of makeWorkspaceDir, created on demand and deleted by Snapshot.Destroy.
146 workspaceDir string
147 workspaceDirErr error
148
149 // knownSubdirs is the set of subdirectories in the workspace, used to
150 // create glob patterns for file watching.
151 knownSubdirs knownDirsSet
152 knownSubdirsPatternCache string
153 // unprocessedSubdirChanges are any changes that might affect the set of
154 // subdirectories in the workspace. They are not reflected to knownSubdirs
155 // during the snapshot cloning step as it can slow down cloning.
156 unprocessedSubdirChanges []*fileChange
157}
158
159var _ memoize.RefCounted = (*snapshot)(nil) // snapshots are reference-counted
160
161// Acquire prevents the snapshot from being destroyed until the returned function is called.
162//
163// (s.Acquire().release() could instead be expressed as a pair of
164// method calls s.IncRef(); s.DecRef(). The latter has the advantage
165// that the DecRefs are fungible and don't require holding anything in
166// addition to the refcounted object s, but paradoxically that is also
167// an advantage of the current approach, which forces the caller to
168// consider the release function at every stage, making a reference
169// leak more obvious.)
170func (s *snapshot) Acquire() func() {
171 type uP = unsafe.Pointer
172 if destroyedBy := atomic.LoadPointer((*uP)(uP(&s.destroyedBy))); destroyedBy != nil {
173 log.Panicf("%d: acquire() after Destroy(%q)", s.id, *(*string)(destroyedBy))
174 }
175 s.refcount.Add(1)
176 return s.refcount.Done
177}
178
179func (s *snapshot) awaitPromise(ctx context.Context, p *memoize.Promise) (interface{}, error) {
180 return p.Get(ctx, s)
181}
182
183// destroy waits for all leases on the snapshot to expire then releases
184// any resources (reference counts and files) associated with it.
185// Snapshots being destroyed can be awaited using v.destroyWG.
186//
187// TODO(adonovan): move this logic into the release function returned
188// by Acquire when the reference count becomes zero. (This would cost
189// us the destroyedBy debug info, unless we add it to the signature of
190// memoize.RefCounted.Acquire.)
191//
192// The destroyedBy argument is used for debugging.
193//
194// v.snapshotMu must be held while calling this function, in order to preserve
195// the invariants described by the the docstring for v.snapshot.
196func (v *View) destroy(s *snapshot, destroyedBy string) {
197 v.snapshotWG.Add(1)
198 go func() {
199 defer v.snapshotWG.Done()
200 s.destroy(destroyedBy)
201 }()
202}
203
204func (s *snapshot) destroy(destroyedBy string) {
205 // Wait for all leases to end before commencing destruction.
206 s.refcount.Wait()
207
208 // Report bad state as a debugging aid.
209 // Not foolproof: another thread could acquire() at this moment.
210 type uP = unsafe.Pointer // looking forward to generics...
211 if old := atomic.SwapPointer((*uP)(uP(&s.destroyedBy)), uP(&destroyedBy)); old != nil {
212 log.Panicf("%d: Destroy(%q) after Destroy(%q)", s.id, destroyedBy, *(*string)(old))
213 }
214
215 s.packages.Destroy()
216 s.isActivePackageCache.Destroy()
217 s.actions.Destroy()
218 s.files.Destroy()
219 s.parsedGoFiles.Destroy()
220 s.parseKeysByURI.Destroy()
221 s.knownSubdirs.Destroy()
222 s.symbolizeHandles.Destroy()
223 s.parseModHandles.Destroy()
224 s.parseWorkHandles.Destroy()
225 s.modTidyHandles.Destroy()
226 s.modWhyHandles.Destroy()
227
228 if s.workspaceDir != "" {
229 if err := os.RemoveAll(s.workspaceDir); err != nil {
230 event.Error(context.Background(), "cleaning workspace dir", err)
231 }
232 }
233}
234
235func (s *snapshot) ID() uint64 {
236 return s.id
237}
238
239func (s *snapshot) View() source.View {
240 return s.view
241}
242
243func (s *snapshot) BackgroundContext() context.Context {
244 return s.backgroundCtx
245}
246
247func (s *snapshot) FileSet() *token.FileSet {
248 return s.view.session.cache.fset
249}
250
251func (s *snapshot) ModFiles() []span.URI {
252 var uris []span.URI
253 for modURI := range s.workspace.getActiveModFiles() {
254 uris = append(uris, modURI)
255 }
256 return uris
257}
258
259func (s *snapshot) WorkFile() span.URI {
260 return s.workspace.workFile
261}
262
263func (s *snapshot) Templates() map[span.URI]source.VersionedFileHandle {
264 s.mu.Lock()
265 defer s.mu.Unlock()
266
267 tmpls := map[span.URI]source.VersionedFileHandle{}
268 s.files.Range(func(k span.URI, fh source.VersionedFileHandle) {
269 if s.view.FileKind(fh) == source.Tmpl {
270 tmpls[k] = fh
271 }
272 })
273 return tmpls
274}
275
276func (s *snapshot) ValidBuildConfiguration() bool {
277 // Since we only really understand the `go` command, if the user has a
278 // different GOPACKAGESDRIVER, assume that their configuration is valid.
279 if s.view.hasGopackagesDriver {
280 return true
281 }
282 // Check if the user is working within a module or if we have found
283 // multiple modules in the workspace.
284 if len(s.workspace.getActiveModFiles()) > 0 {
285 return true
286 }
287 // The user may have a multiple directories in their GOPATH.
288 // Check if the workspace is within any of them.
289 for _, gp := range filepath.SplitList(s.view.gopath) {
290 if source.InDir(filepath.Join(gp, "src"), s.view.rootURI.Filename()) {
291 return true
292 }
293 }
294 return false
295}
296
297// workspaceMode describes the way in which the snapshot's workspace should
298// be loaded.
299func (s *snapshot) workspaceMode() workspaceMode {
300 var mode workspaceMode
301
302 // If the view has an invalid configuration, don't build the workspace
303 // module.
304 validBuildConfiguration := s.ValidBuildConfiguration()
305 if !validBuildConfiguration {
306 return mode
307 }
308 // If the view is not in a module and contains no modules, but still has a
309 // valid workspace configuration, do not create the workspace module.
310 // It could be using GOPATH or a different build system entirely.
311 if len(s.workspace.getActiveModFiles()) == 0 && validBuildConfiguration {
312 return mode
313 }
314 mode |= moduleMode
315 options := s.view.Options()
316 // The -modfile flag is available for Go versions >= 1.14.
317 if options.TempModfile && s.view.workspaceInformation.goversion >= 14 {
318 mode |= tempModfile
319 }
320 return mode
321}
322
323// config returns the configuration used for the snapshot's interaction with
324// the go/packages API. It uses the given working directory.
325//
326// TODO(rstambler): go/packages requires that we do not provide overlays for
327// multiple modules in on config, so buildOverlay needs to filter overlays by
328// module.
329func (s *snapshot) config(ctx context.Context, inv *gocommand.Invocation) *packages.Config {
330 s.view.optionsMu.Lock()
331 verboseOutput := s.view.options.VerboseOutput
332 s.view.optionsMu.Unlock()
333
334 cfg := &packages.Config{
335 Context: ctx,
336 Dir: inv.WorkingDir,
337 Env: inv.Env,
338 BuildFlags: inv.BuildFlags,
339 Mode: packages.NeedName |
340 packages.NeedFiles |
341 packages.NeedCompiledGoFiles |
342 packages.NeedImports |
343 packages.NeedDeps |
344 packages.NeedTypesSizes |
345 packages.NeedModule |
346 packages.LoadMode(packagesinternal.DepsErrors) |
347 packages.LoadMode(packagesinternal.ForTest),
348 Fset: s.FileSet(),
349 Overlay: s.buildOverlay(),
350 ParseFile: func(*token.FileSet, string, []byte) (*ast.File, error) {
351 panic("go/packages must not be used to parse files")
352 },
353 Logf: func(format string, args ...interface{}) {
354 if verboseOutput {
355 event.Log(ctx, fmt.Sprintf(format, args...))
356 }
357 },
358 Tests: true,
359 }
360 packagesinternal.SetModFile(cfg, inv.ModFile)
361 packagesinternal.SetModFlag(cfg, inv.ModFlag)
362 // We want to type check cgo code if go/types supports it.
363 if typesinternal.SetUsesCgo(&types.Config{}) {
364 cfg.Mode |= packages.LoadMode(packagesinternal.TypecheckCgo)
365 }
366 packagesinternal.SetGoCmdRunner(cfg, s.view.session.gocmdRunner)
367 return cfg
368}
369
370func (s *snapshot) RunGoCommandDirect(ctx context.Context, mode source.InvocationFlags, inv *gocommand.Invocation) (*bytes.Buffer, error) {
371 _, inv, cleanup, err := s.goCommandInvocation(ctx, mode, inv)
372 if err != nil {
373 return nil, err
374 }
375 defer cleanup()
376
377 return s.view.session.gocmdRunner.Run(ctx, *inv)
378}
379
380func (s *snapshot) RunGoCommandPiped(ctx context.Context, mode source.InvocationFlags, inv *gocommand.Invocation, stdout, stderr io.Writer) error {
381 _, inv, cleanup, err := s.goCommandInvocation(ctx, mode, inv)
382 if err != nil {
383 return err
384 }
385 defer cleanup()
386 return s.view.session.gocmdRunner.RunPiped(ctx, *inv, stdout, stderr)
387}
388
389func (s *snapshot) RunGoCommands(ctx context.Context, allowNetwork bool, wd string, run func(invoke func(...string) (*bytes.Buffer, error)) error) (bool, []byte, []byte, error) {
390 var flags source.InvocationFlags
391 if s.workspaceMode()&tempModfile != 0 {
392 flags = source.WriteTemporaryModFile
393 } else {
394 flags = source.Normal
395 }
396 if allowNetwork {
397 flags |= source.AllowNetwork
398 }
399 tmpURI, inv, cleanup, err := s.goCommandInvocation(ctx, flags, &gocommand.Invocation{WorkingDir: wd})
400 if err != nil {
401 return false, nil, nil, err
402 }
403 defer cleanup()
404 invoke := func(args ...string) (*bytes.Buffer, error) {
405 inv.Verb = args[0]
406 inv.Args = args[1:]
407 return s.view.session.gocmdRunner.Run(ctx, *inv)
408 }
409 if err := run(invoke); err != nil {
410 return false, nil, nil, err
411 }
412 if flags.Mode() != source.WriteTemporaryModFile {
413 return false, nil, nil, nil
414 }
415 var modBytes, sumBytes []byte
416 modBytes, err = ioutil.ReadFile(tmpURI.Filename())
417 if err != nil && !os.IsNotExist(err) {
418 return false, nil, nil, err
419 }
420 sumBytes, err = ioutil.ReadFile(strings.TrimSuffix(tmpURI.Filename(), ".mod") + ".sum")
421 if err != nil && !os.IsNotExist(err) {
422 return false, nil, nil, err
423 }
424 return true, modBytes, sumBytes, nil
425}
426
427// goCommandInvocation populates inv with configuration for running go commands on the snapshot.
428//
429// TODO(rfindley): refactor this function to compose the required configuration
430// explicitly, rather than implicitly deriving it from flags and inv.
431//
432// TODO(adonovan): simplify cleanup mechanism. It's hard to see, but
433// it used only after call to tempModFile. Clarify that it is only
434// non-nil on success.
435func (s *snapshot) goCommandInvocation(ctx context.Context, flags source.InvocationFlags, inv *gocommand.Invocation) (tmpURI span.URI, updatedInv *gocommand.Invocation, cleanup func(), err error) {
436 s.view.optionsMu.Lock()
437 allowModfileModificationOption := s.view.options.AllowModfileModifications
438 allowNetworkOption := s.view.options.AllowImplicitNetworkAccess
439
440 // TODO(rfindley): this is very hard to follow, and may not even be doing the
441 // right thing: should inv.Env really trample view.options? Do we ever invoke
442 // this with a non-empty inv.Env?
443 //
444 // We should refactor to make it clearer that the correct env is being used.
445 inv.Env = append(append(append(os.Environ(), s.view.options.EnvSlice()...), inv.Env...), "GO111MODULE="+s.view.effectiveGo111Module)
446 inv.BuildFlags = append([]string{}, s.view.options.BuildFlags...)
447 s.view.optionsMu.Unlock()
448 cleanup = func() {} // fallback
449
450 // All logic below is for module mode.
451 if s.workspaceMode()&moduleMode == 0 {
452 return "", inv, cleanup, nil
453 }
454
455 mode, allowNetwork := flags.Mode(), flags.AllowNetwork()
456 if !allowNetwork && !allowNetworkOption {
457 inv.Env = append(inv.Env, "GOPROXY=off")
458 }
459
460 // What follows is rather complicated logic for how to actually run the go
461 // command. A word of warning: this is the result of various incremental
462 // features added to gopls, and varying behavior of the Go command across Go
463 // versions. It can surely be cleaned up significantly, but tread carefully.
464 //
465 // Roughly speaking we need to resolve four things:
466 // - the working directory.
467 // - the -mod flag
468 // - the -modfile flag
469 //
470 // These are dependent on a number of factors: whether we need to run in a
471 // synthetic workspace, whether flags are supported at the current go
472 // version, and what we're actually trying to achieve (the
473 // source.InvocationFlags).
474
475 var modURI span.URI
476 // Select the module context to use.
477 // If we're type checking, we need to use the workspace context, meaning
478 // the main (workspace) module. Otherwise, we should use the module for
479 // the passed-in working dir.
480 if mode == source.LoadWorkspace {
481 switch s.workspace.moduleSource {
482 case legacyWorkspace:
483 for m := range s.workspace.getActiveModFiles() { // range to access the only element
484 modURI = m
485 }
486 case goWorkWorkspace:
487 if s.view.goversion >= 18 {
488 break
489 }
490 // Before go 1.18, the Go command did not natively support go.work files,
491 // so we 'fake' them with a workspace module.
492 fallthrough
493 case fileSystemWorkspace, goplsModWorkspace:
494 var tmpDir span.URI
495 var err error
496 tmpDir, err = s.getWorkspaceDir(ctx)
497 if err != nil {
498 return "", nil, cleanup, err
499 }
500 inv.WorkingDir = tmpDir.Filename()
501 modURI = span.URIFromPath(filepath.Join(tmpDir.Filename(), "go.mod"))
502 }
503 } else {
504 modURI = s.GoModForFile(span.URIFromPath(inv.WorkingDir))
505 }
506
507 var modContent []byte
508 if modURI != "" {
509 modFH, err := s.GetFile(ctx, modURI)
510 if err != nil {
511 return "", nil, cleanup, err
512 }
513 modContent, err = modFH.Read()
514 if err != nil {
515 return "", nil, cleanup, err
516 }
517 }
518
519 // TODO(rfindley): in the case of go.work mode, modURI is empty and we fall
520 // back on the default behavior of vendorEnabled with an empty modURI. Figure
521 // out what is correct here and implement it explicitly.
522 vendorEnabled, err := s.vendorEnabled(ctx, modURI, modContent)
523 if err != nil {
524 return "", nil, cleanup, err
525 }
526
527 mutableModFlag := ""
528 // If the mod flag isn't set, populate it based on the mode and workspace.
529 if inv.ModFlag == "" {
530 if s.view.goversion >= 16 {
531 mutableModFlag = "mod"
532 }
533
534 switch mode {
535 case source.LoadWorkspace, source.Normal:
536 if vendorEnabled {
537 inv.ModFlag = "vendor"
538 } else if !allowModfileModificationOption {
539 inv.ModFlag = "readonly"
540 } else {
541 inv.ModFlag = mutableModFlag
542 }
543 case source.WriteTemporaryModFile:
544 inv.ModFlag = mutableModFlag
545 // -mod must be readonly when using go.work files - see issue #48941
546 inv.Env = append(inv.Env, "GOWORK=off")
547 }
548 }
549
550 // Only use a temp mod file if the modfile can actually be mutated.
551 needTempMod := inv.ModFlag == mutableModFlag
552 useTempMod := s.workspaceMode()&tempModfile != 0
553 if needTempMod && !useTempMod {
554 return "", nil, cleanup, source.ErrTmpModfileUnsupported
555 }
556
557 // We should use -modfile if:
558 // - the workspace mode supports it
559 // - we're using a go.work file on go1.18+, or we need a temp mod file (for
560 // example, if running go mod tidy in a go.work workspace)
561 //
562 // TODO(rfindley): this is very hard to follow. Refactor.
563 useWorkFile := !needTempMod && s.workspace.moduleSource == goWorkWorkspace && s.view.goversion >= 18
564 if useWorkFile {
565 // Since we're running in the workspace root, the go command will resolve GOWORK automatically.
566 } else if useTempMod {
567 if modURI == "" {
568 return "", nil, cleanup, fmt.Errorf("no go.mod file found in %s", inv.WorkingDir)
569 }
570 modFH, err := s.GetFile(ctx, modURI)
571 if err != nil {
572 return "", nil, cleanup, err
573 }
574 // Use the go.sum if it happens to be available.
575 gosum := s.goSum(ctx, modURI)
576 tmpURI, cleanup, err = tempModFile(modFH, gosum)
577 if err != nil {
578 return "", nil, cleanup, err
579 }
580 inv.ModFile = tmpURI.Filename()
581 }
582
583 return tmpURI, inv, cleanup, nil
584}
585
586// usesWorkspaceDir reports whether the snapshot should use a synthetic
587// workspace directory for running workspace go commands such as go list.
588//
589// TODO(rfindley): this logic is duplicated with goCommandInvocation. Clean up
590// the latter, and deduplicate.
591func (s *snapshot) usesWorkspaceDir() bool {
592 switch s.workspace.moduleSource {
593 case legacyWorkspace:
594 return false
595 case goWorkWorkspace:
596 if s.view.goversion >= 18 {
597 return false
598 }
599 // Before go 1.18, the Go command did not natively support go.work files,
600 // so we 'fake' them with a workspace module.
601 }
602 return true
603}
604
605func (s *snapshot) buildOverlay() map[string][]byte {
606 s.mu.Lock()
607 defer s.mu.Unlock()
608
609 overlays := make(map[string][]byte)
610 s.files.Range(func(uri span.URI, fh source.VersionedFileHandle) {
611 overlay, ok := fh.(*overlay)
612 if !ok {
613 return
614 }
615 if overlay.saved {
616 return
617 }
618 // TODO(rstambler): Make sure not to send overlays outside of the current view.
619 overlays[uri.Filename()] = overlay.text
620 })
621 return overlays
622}
623
624func (s *snapshot) PackagesForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode, includeTestVariants bool) ([]source.Package, error) {
625 ctx = event.Label(ctx, tag.URI.Of(uri))
626
627 phs, err := s.packageHandlesForFile(ctx, uri, mode, includeTestVariants)
628 if err != nil {
629 return nil, err
630 }
631 var pkgs []source.Package
632 for _, ph := range phs {
633 pkg, err := ph.await(ctx, s)
634 if err != nil {
635 return nil, err
636 }
637 pkgs = append(pkgs, pkg)
638 }
639 return pkgs, nil
640}
641
642func (s *snapshot) PackageForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode, pkgPolicy source.PackageFilter) (source.Package, error) {
643 ctx = event.Label(ctx, tag.URI.Of(uri))
644
645 phs, err := s.packageHandlesForFile(ctx, uri, mode, false)
646 if err != nil {
647 return nil, err
648 }
649
650 if len(phs) < 1 {
651 return nil, fmt.Errorf("no packages")
652 }
653
654 ph := phs[0]
655 for _, handle := range phs[1:] {
656 switch pkgPolicy {
657 case source.WidestPackage:
658 if ph == nil || len(handle.CompiledGoFiles()) > len(ph.CompiledGoFiles()) {
659 ph = handle
660 }
661 case source.NarrowestPackage:
662 if ph == nil || len(handle.CompiledGoFiles()) < len(ph.CompiledGoFiles()) {
663 ph = handle
664 }
665 }
666 }
667 if ph == nil {
668 return nil, fmt.Errorf("no packages in input")
669 }
670
671 return ph.await(ctx, s)
672}
673
674func (s *snapshot) packageHandlesForFile(ctx context.Context, uri span.URI, mode source.TypecheckMode, includeTestVariants bool) ([]*packageHandle, error) {
675 // TODO(rfindley): why can't/shouldn't we awaitLoaded here? It seems that if
676 // we ask for package handles for a file, we should wait for pending loads.
677 // Else we will reload orphaned files before the initial load completes.
678
679 // Check if we should reload metadata for the file. We don't invalidate IDs
680 // (though we should), so the IDs will be a better source of truth than the
681 // metadata. If there are no IDs for the file, then we should also reload.
682 fh, err := s.GetFile(ctx, uri)
683 if err != nil {
684 return nil, err
685 }
686 if kind := s.view.FileKind(fh); kind != source.Go {
687 return nil, fmt.Errorf("no packages for non-Go file %s (%v)", uri, kind)
688 }
689 knownIDs, err := s.getOrLoadIDsForURI(ctx, uri)
690 if err != nil {
691 return nil, err
692 }
693
694 var phs []*packageHandle
695 for _, id := range knownIDs {
696 // Filter out any intermediate test variants. We typically aren't
697 // interested in these packages for file= style queries.
698 if m := s.getMetadata(id); m != nil && m.IsIntermediateTestVariant && !includeTestVariants {
699 continue
700 }
701 var parseModes []source.ParseMode
702 switch mode {
703 case source.TypecheckAll:
704 if s.workspaceParseMode(id) == source.ParseFull {
705 parseModes = []source.ParseMode{source.ParseFull}
706 } else {
707 parseModes = []source.ParseMode{source.ParseExported, source.ParseFull}
708 }
709 case source.TypecheckFull:
710 parseModes = []source.ParseMode{source.ParseFull}
711 case source.TypecheckWorkspace:
712 parseModes = []source.ParseMode{s.workspaceParseMode(id)}
713 }
714
715 for _, parseMode := range parseModes {
716 ph, err := s.buildPackageHandle(ctx, id, parseMode)
717 if err != nil {
718 return nil, err
719 }
720 phs = append(phs, ph)
721 }
722 }
723 return phs, nil
724}
725
726func (s *snapshot) getOrLoadIDsForURI(ctx context.Context, uri span.URI) ([]PackageID, error) {
727 s.mu.Lock()
728 ids := s.meta.ids[uri]
729 reload := len(ids) == 0
730 for _, id := range ids {
731 // If the file is part of a package that needs reloading, reload it now to
732 // improve our responsiveness.
733 if len(s.shouldLoad[id]) > 0 {
734 reload = true
735 break
736 }
737 // TODO(golang/go#36918): Previously, we would reload any package with
738 // missing dependencies. This is expensive and results in too many
739 // calls to packages.Load. Determine what we should do instead.
740 }
741 s.mu.Unlock()
742
743 if reload {
744 scope := fileURI(uri)
745 err := s.load(ctx, false, scope)
746
747 // As in reloadWorkspace, we must clear scopes after loading.
748 //
749 // TODO(rfindley): simply call reloadWorkspace here, first, to avoid this
750 // duplication.
751 if !errors.Is(err, context.Canceled) {
752 s.clearShouldLoad(scope)
753 }
754
755 // TODO(rfindley): this doesn't look right. If we don't reload, we use
756 // invalid metadata anyway, but if we DO reload and it fails, we don't?
757 if !s.useInvalidMetadata() && err != nil {
758 return nil, err
759 }
760
761 s.mu.Lock()
762 ids = s.meta.ids[uri]
763 s.mu.Unlock()
764
765 // We've tried to reload and there are still no known IDs for the URI.
766 // Return the load error, if there was one.
767 if len(ids) == 0 {
768 return nil, err
769 }
770 }
771
772 return ids, nil
773}
774
775// Only use invalid metadata for Go versions >= 1.13. Go 1.12 and below has
776// issues with overlays that will cause confusing error messages if we reuse
777// old metadata.
778func (s *snapshot) useInvalidMetadata() bool {
779 return s.view.goversion >= 13 && s.view.Options().ExperimentalUseInvalidMetadata
780}
781
782func (s *snapshot) GetReverseDependencies(ctx context.Context, id string) ([]source.Package, error) {
783 if err := s.awaitLoaded(ctx); err != nil {
784 return nil, err
785 }
786 s.mu.Lock()
787 meta := s.meta
788 s.mu.Unlock()
789 ids := meta.reverseTransitiveClosure(s.useInvalidMetadata(), PackageID(id))
790
791 // Make sure to delete the original package ID from the map.
792 delete(ids, PackageID(id))
793
794 var pkgs []source.Package
795 for id := range ids {
796 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
797 if err != nil {
798 return nil, err
799 }
800 pkgs = append(pkgs, pkg)
801 }
802 return pkgs, nil
803}
804
805func (s *snapshot) checkedPackage(ctx context.Context, id PackageID, mode source.ParseMode) (*pkg, error) {
806 ph, err := s.buildPackageHandle(ctx, id, mode)
807 if err != nil {
808 return nil, err
809 }
810 return ph.await(ctx, s)
811}
812
813func (s *snapshot) getImportedBy(id PackageID) []PackageID {
814 s.mu.Lock()
815 defer s.mu.Unlock()
816 return s.meta.importedBy[id]
817}
818
819func (s *snapshot) workspacePackageIDs() (ids []PackageID) {
820 s.mu.Lock()
821 defer s.mu.Unlock()
822
823 for id := range s.workspacePackages {
824 ids = append(ids, id)
825 }
826 return ids
827}
828
829func (s *snapshot) activePackageIDs() (ids []PackageID) {
830 if s.view.Options().MemoryMode == source.ModeNormal {
831 return s.workspacePackageIDs()
832 }
833
834 s.mu.Lock()
835 defer s.mu.Unlock()
836
837 for id := range s.workspacePackages {
838 if s.isActiveLocked(id) {
839 ids = append(ids, id)
840 }
841 }
842 return ids
843}
844
845func (s *snapshot) isActiveLocked(id PackageID) (active bool) {
846 if seen, ok := s.isActivePackageCache.Get(id); ok {
847 return seen
848 }
849 defer func() {
850 s.isActivePackageCache.Set(id, active)
851 }()
852 m, ok := s.meta.metadata[id]
853 if !ok {
854 return false
855 }
856 for _, cgf := range m.CompiledGoFiles {
857 if s.isOpenLocked(cgf) {
858 return true
859 }
860 }
861 // TODO(rfindley): it looks incorrect that we don't also check GoFiles here.
862 // If a CGo file is open, we want to consider the package active.
863 for _, dep := range m.Deps {
864 if s.isActiveLocked(dep) {
865 return true
866 }
867 }
868 return false
869}
870
871func (s *snapshot) resetIsActivePackageLocked() {
872 s.isActivePackageCache.Destroy()
873 s.isActivePackageCache = newIsActivePackageCacheMap()
874}
875
876const fileExtensions = "go,mod,sum,work"
877
878func (s *snapshot) fileWatchingGlobPatterns(ctx context.Context) map[string]struct{} {
879 extensions := fileExtensions
880 for _, ext := range s.View().Options().TemplateExtensions {
881 extensions += "," + ext
882 }
883 // Work-around microsoft/vscode#100870 by making sure that we are,
884 // at least, watching the user's entire workspace. This will still be
885 // applied to every folder in the workspace.
886 patterns := map[string]struct{}{
887 fmt.Sprintf("**/*.{%s}", extensions): {},
888 }
889
890 if s.view.explicitGowork != "" {
891 patterns[s.view.explicitGowork.Filename()] = struct{}{}
892 }
893
894 // Add a pattern for each Go module in the workspace that is not within the view.
895 dirs := s.workspace.dirs(ctx, s)
896 for _, dir := range dirs {
897 dirName := dir.Filename()
898
899 // If the directory is within the view's folder, we're already watching
900 // it with the pattern above.
901 if source.InDir(s.view.folder.Filename(), dirName) {
902 continue
903 }
904 // TODO(rstambler): If microsoft/vscode#3025 is resolved before
905 // microsoft/vscode#101042, we will need a work-around for Windows
906 // drive letter casing.
907 patterns[fmt.Sprintf("%s/**/*.{%s}", dirName, extensions)] = struct{}{}
908 }
909
910 // Some clients do not send notifications for changes to directories that
911 // contain Go code (golang/go#42348). To handle this, explicitly watch all
912 // of the directories in the workspace. We find them by adding the
913 // directories of every file in the snapshot's workspace directories.
914 // There may be thousands.
915 if pattern := s.getKnownSubdirsPattern(dirs); pattern != "" {
916 patterns[pattern] = struct{}{}
917 }
918
919 return patterns
920}
921
922func (s *snapshot) getKnownSubdirsPattern(wsDirs []span.URI) string {
923 s.mu.Lock()
924 defer s.mu.Unlock()
925
926 // First, process any pending changes and update the set of known
927 // subdirectories.
928 // It may change list of known subdirs and therefore invalidate the cache.
929 s.applyKnownSubdirsChangesLocked(wsDirs)
930
931 if s.knownSubdirsPatternCache == "" {
932 var builder strings.Builder
933 s.knownSubdirs.Range(func(uri span.URI) {
934 if builder.Len() == 0 {
935 builder.WriteString("{")
936 } else {
937 builder.WriteString(",")
938 }
939 builder.WriteString(uri.Filename())
940 })
941 if builder.Len() > 0 {
942 builder.WriteString("}")
943 s.knownSubdirsPatternCache = builder.String()
944 }
945 }
946
947 return s.knownSubdirsPatternCache
948}
949
950// collectAllKnownSubdirs collects all of the subdirectories within the
951// snapshot's workspace directories. None of the workspace directories are
952// included.
953func (s *snapshot) collectAllKnownSubdirs(ctx context.Context) {
954 dirs := s.workspace.dirs(ctx, s)
955
956 s.mu.Lock()
957 defer s.mu.Unlock()
958
959 s.knownSubdirs.Destroy()
960 s.knownSubdirs = newKnownDirsSet()
961 s.knownSubdirsPatternCache = ""
962 s.files.Range(func(uri span.URI, fh source.VersionedFileHandle) {
963 s.addKnownSubdirLocked(uri, dirs)
964 })
965}
966
967func (s *snapshot) getKnownSubdirs(wsDirs []span.URI) knownDirsSet {
968 s.mu.Lock()
969 defer s.mu.Unlock()
970
971 // First, process any pending changes and update the set of known
972 // subdirectories.
973 s.applyKnownSubdirsChangesLocked(wsDirs)
974
975 return s.knownSubdirs.Clone()
976}
977
978func (s *snapshot) applyKnownSubdirsChangesLocked(wsDirs []span.URI) {
979 for _, c := range s.unprocessedSubdirChanges {
980 if c.isUnchanged {
981 continue
982 }
983 if !c.exists {
984 s.removeKnownSubdirLocked(c.fileHandle.URI())
985 } else {
986 s.addKnownSubdirLocked(c.fileHandle.URI(), wsDirs)
987 }
988 }
989 s.unprocessedSubdirChanges = nil
990}
991
992func (s *snapshot) addKnownSubdirLocked(uri span.URI, dirs []span.URI) {
993 dir := filepath.Dir(uri.Filename())
994 // First check if the directory is already known, because then we can
995 // return early.
996 if s.knownSubdirs.Contains(span.URIFromPath(dir)) {
997 return
998 }
999 var matched span.URI
1000 for _, wsDir := range dirs {
1001 if source.InDir(wsDir.Filename(), dir) {
1002 matched = wsDir
1003 break
1004 }
1005 }
1006 // Don't watch any directory outside of the workspace directories.
1007 if matched == "" {
1008 return
1009 }
1010 for {
1011 if dir == "" || dir == matched.Filename() {
1012 break
1013 }
1014 uri := span.URIFromPath(dir)
1015 if s.knownSubdirs.Contains(uri) {
1016 break
1017 }
1018 s.knownSubdirs.Insert(uri)
1019 dir = filepath.Dir(dir)
1020 s.knownSubdirsPatternCache = ""
1021 }
1022}
1023
1024func (s *snapshot) removeKnownSubdirLocked(uri span.URI) {
1025 dir := filepath.Dir(uri.Filename())
1026 for dir != "" {
1027 uri := span.URIFromPath(dir)
1028 if !s.knownSubdirs.Contains(uri) {
1029 break
1030 }
1031 if info, _ := os.Stat(dir); info == nil {
1032 s.knownSubdirs.Remove(uri)
1033 s.knownSubdirsPatternCache = ""
1034 }
1035 dir = filepath.Dir(dir)
1036 }
1037}
1038
1039// knownFilesInDir returns the files known to the given snapshot that are in
1040// the given directory. It does not respect symlinks.
1041func (s *snapshot) knownFilesInDir(ctx context.Context, dir span.URI) []span.URI {
1042 var files []span.URI
1043 s.mu.Lock()
1044 defer s.mu.Unlock()
1045
1046 s.files.Range(func(uri span.URI, fh source.VersionedFileHandle) {
1047 if source.InDir(dir.Filename(), uri.Filename()) {
1048 files = append(files, uri)
1049 }
1050 })
1051 return files
1052}
1053
1054func (s *snapshot) ActivePackages(ctx context.Context) ([]source.Package, error) {
1055 phs, err := s.activePackageHandles(ctx)
1056 if err != nil {
1057 return nil, err
1058 }
1059 var pkgs []source.Package
1060 for _, ph := range phs {
1061 pkg, err := ph.await(ctx, s)
1062 if err != nil {
1063 return nil, err
1064 }
1065 pkgs = append(pkgs, pkg)
1066 }
1067 return pkgs, nil
1068}
1069
1070func (s *snapshot) activePackageHandles(ctx context.Context) ([]*packageHandle, error) {
1071 if err := s.awaitLoaded(ctx); err != nil {
1072 return nil, err
1073 }
1074 var phs []*packageHandle
1075 for _, pkgID := range s.activePackageIDs() {
1076 ph, err := s.buildPackageHandle(ctx, pkgID, s.workspaceParseMode(pkgID))
1077 if err != nil {
1078 return nil, err
1079 }
1080 phs = append(phs, ph)
1081 }
1082 return phs, nil
1083}
1084
1085// Symbols extracts and returns the symbols for each file in all the snapshot's views.
1086func (s *snapshot) Symbols(ctx context.Context) map[span.URI][]source.Symbol {
1087 var (
1088 group errgroup.Group
1089 nprocs = 2 * runtime.GOMAXPROCS(-1) // symbolize is a mix of I/O and CPU
1090 iolimit = make(chan struct{}, nprocs) // I/O limiting counting semaphore
1091 resultMu sync.Mutex
1092 result = make(map[span.URI][]source.Symbol)
1093 )
1094 s.files.Range(func(uri span.URI, f source.VersionedFileHandle) {
1095 if s.View().FileKind(f) != source.Go {
1096 return // workspace symbols currently supports only Go files.
1097 }
1098
1099 // TODO(adonovan): upgrade errgroup and use group.SetLimit(nprocs).
1100 iolimit <- struct{}{} // acquire token
1101 group.Go(func() error {
1102 defer func() { <-iolimit }() // release token
1103 symbols, err := s.symbolize(ctx, f)
1104 if err != nil {
1105 return err
1106 }
1107 resultMu.Lock()
1108 result[uri] = symbols
1109 resultMu.Unlock()
1110 return nil
1111 })
1112 })
1113 // Keep going on errors, but log the first failure.
1114 // Partial results are better than no symbol results.
1115 if err := group.Wait(); err != nil {
1116 event.Error(ctx, "getting snapshot symbols", err)
1117 }
1118 return result
1119}
1120
1121func (s *snapshot) MetadataForFile(ctx context.Context, uri span.URI) ([]source.Metadata, error) {
1122 knownIDs, err := s.getOrLoadIDsForURI(ctx, uri)
1123 if err != nil {
1124 return nil, err
1125 }
1126 var mds []source.Metadata
1127 for _, id := range knownIDs {
1128 md := s.getMetadata(id)
1129 // TODO(rfindley): knownIDs and metadata should be in sync, but existing
1130 // code is defensive of nil metadata.
1131 if md != nil {
1132 mds = append(mds, md)
1133 }
1134 }
1135 return mds, nil
1136}
1137
1138func (s *snapshot) KnownPackages(ctx context.Context) ([]source.Package, error) {
1139 if err := s.awaitLoaded(ctx); err != nil {
1140 return nil, err
1141 }
1142
1143 // The WorkspaceSymbols implementation relies on this function returning
1144 // workspace packages first.
1145 ids := s.workspacePackageIDs()
1146 s.mu.Lock()
1147 for id := range s.meta.metadata {
1148 if _, ok := s.workspacePackages[id]; ok {
1149 continue
1150 }
1151 ids = append(ids, id)
1152 }
1153 s.mu.Unlock()
1154
1155 var pkgs []source.Package
1156 for _, id := range ids {
1157 pkg, err := s.checkedPackage(ctx, id, s.workspaceParseMode(id))
1158 if err != nil {
1159 return nil, err
1160 }
1161 pkgs = append(pkgs, pkg)
1162 }
1163 return pkgs, nil
1164}
1165
1166func (s *snapshot) CachedImportPaths(ctx context.Context) (map[string]source.Package, error) {
1167 // Don't reload workspace package metadata.
1168 // This function is meant to only return currently cached information.
1169 s.AwaitInitialized(ctx)
1170
1171 s.mu.Lock()
1172 defer s.mu.Unlock()
1173
1174 results := map[string]source.Package{}
1175 s.packages.Range(func(_, v interface{}) {
1176 cachedPkg, err := v.(*packageHandle).cached()
1177 if err != nil {
1178 return
1179 }
1180 for importPath, newPkg := range cachedPkg.imports {
1181 if oldPkg, ok := results[string(importPath)]; ok {
1182 // Using the same trick as NarrowestPackage, prefer non-variants.
1183 if len(newPkg.compiledGoFiles) < len(oldPkg.(*pkg).compiledGoFiles) {
1184 results[string(importPath)] = newPkg
1185 }
1186 } else {
1187 results[string(importPath)] = newPkg
1188 }
1189 }
1190 })
1191 return results, nil
1192}
1193
1194func (s *snapshot) GoModForFile(uri span.URI) span.URI {
1195 return moduleForURI(s.workspace.activeModFiles, uri)
1196}
1197
1198func moduleForURI(modFiles map[span.URI]struct{}, uri span.URI) span.URI {
1199 var match span.URI
1200 for modURI := range modFiles {
1201 if !source.InDir(dirURI(modURI).Filename(), uri.Filename()) {
1202 continue
1203 }
1204 if len(modURI) > len(match) {
1205 match = modURI
1206 }
1207 }
1208 return match
1209}
1210
1211func (s *snapshot) getMetadata(id PackageID) *KnownMetadata {
1212 s.mu.Lock()
1213 defer s.mu.Unlock()
1214
1215 return s.meta.metadata[id]
1216}
1217
1218// clearShouldLoad clears package IDs that no longer need to be reloaded after
1219// scopes has been loaded.
1220func (s *snapshot) clearShouldLoad(scopes ...interface{}) {
1221 s.mu.Lock()
1222 defer s.mu.Unlock()
1223
1224 for _, scope := range scopes {
1225 switch scope := scope.(type) {
1226 case PackagePath:
1227 var toDelete []PackageID
1228 for id, pkgPaths := range s.shouldLoad {
1229 for _, pkgPath := range pkgPaths {
1230 if pkgPath == scope {
1231 toDelete = append(toDelete, id)
1232 }
1233 }
1234 }
1235 for _, id := range toDelete {
1236 delete(s.shouldLoad, id)
1237 }
1238 case fileURI:
1239 uri := span.URI(scope)
1240 ids := s.meta.ids[uri]
1241 for _, id := range ids {
1242 delete(s.shouldLoad, id)
1243 }
1244 }
1245 }
1246}
1247
1248// noValidMetadataForURILocked reports whether there is any valid metadata for
1249// the given URI.
1250func (s *snapshot) noValidMetadataForURILocked(uri span.URI) bool {
1251 ids, ok := s.meta.ids[uri]
1252 if !ok {
1253 return true
1254 }
1255 for _, id := range ids {
1256 if m, ok := s.meta.metadata[id]; ok && m.Valid {
1257 return false
1258 }
1259 }
1260 return true
1261}
1262
1263func (s *snapshot) isWorkspacePackage(id PackageID) bool {
1264 s.mu.Lock()
1265 defer s.mu.Unlock()
1266
1267 _, ok := s.workspacePackages[id]
1268 return ok
1269}
1270
1271func (s *snapshot) FindFile(uri span.URI) source.VersionedFileHandle {
1272 f := s.view.getFile(uri)
1273
1274 s.mu.Lock()
1275 defer s.mu.Unlock()
1276
1277 result, _ := s.files.Get(f.URI())
1278 return result
1279}
1280
1281// GetVersionedFile returns a File for the given URI. If the file is unknown it
1282// is added to the managed set.
1283//
1284// GetVersionedFile succeeds even if the file does not exist. A non-nil error return
1285// indicates some type of internal error, for example if ctx is cancelled.
1286func (s *snapshot) GetVersionedFile(ctx context.Context, uri span.URI) (source.VersionedFileHandle, error) {
1287 f := s.view.getFile(uri)
1288
1289 s.mu.Lock()
1290 defer s.mu.Unlock()
1291 return s.getFileLocked(ctx, f)
1292}
1293
1294// GetFile implements the fileSource interface by wrapping GetVersionedFile.
1295func (s *snapshot) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) {
1296 return s.GetVersionedFile(ctx, uri)
1297}
1298
1299func (s *snapshot) getFileLocked(ctx context.Context, f *fileBase) (source.VersionedFileHandle, error) {
1300 if fh, ok := s.files.Get(f.URI()); ok {
1301 return fh, nil
1302 }
1303
1304 fh, err := s.view.session.cache.getFile(ctx, f.URI()) // read the file
1305 if err != nil {
1306 return nil, err
1307 }
1308 closed := &closedFile{fh}
1309 s.files.Set(f.URI(), closed)
1310 return closed, nil
1311}
1312
1313func (s *snapshot) IsOpen(uri span.URI) bool {
1314 s.mu.Lock()
1315 defer s.mu.Unlock()
1316 return s.isOpenLocked(uri)
1317
1318}
1319
1320func (s *snapshot) openFiles() []source.VersionedFileHandle {
1321 s.mu.Lock()
1322 defer s.mu.Unlock()
1323
1324 var open []source.VersionedFileHandle
1325 s.files.Range(func(uri span.URI, fh source.VersionedFileHandle) {
1326 if isFileOpen(fh) {
1327 open = append(open, fh)
1328 }
1329 })
1330 return open
1331}
1332
1333func (s *snapshot) isOpenLocked(uri span.URI) bool {
1334 fh, _ := s.files.Get(uri)
1335 return isFileOpen(fh)
1336}
1337
1338func isFileOpen(fh source.VersionedFileHandle) bool {
1339 _, open := fh.(*overlay)
1340 return open
1341}
1342
1343func (s *snapshot) awaitLoaded(ctx context.Context) error {
1344 loadErr := s.awaitLoadedAllErrors(ctx)
1345
1346 s.mu.Lock()
1347 defer s.mu.Unlock()
1348
1349 // If we still have absolutely no metadata, check if the view failed to
1350 // initialize and return any errors.
1351 if s.useInvalidMetadata() && len(s.meta.metadata) > 0 {
1352 return nil
1353 }
1354 for _, m := range s.meta.metadata {
1355 if m.Valid {
1356 return nil
1357 }
1358 }
1359 if loadErr != nil {
1360 return loadErr.MainError
1361 }
1362 return nil
1363}
1364
1365func (s *snapshot) GetCriticalError(ctx context.Context) *source.CriticalError {
1366 if wsErr := s.workspace.criticalError(ctx, s); wsErr != nil {
1367 return wsErr
1368 }
1369
1370 loadErr := s.awaitLoadedAllErrors(ctx)
1371 if loadErr != nil && errors.Is(loadErr.MainError, context.Canceled) {
1372 return nil
1373 }
1374
1375 // Even if packages didn't fail to load, we still may want to show
1376 // additional warnings.
1377 if loadErr == nil {
1378 wsPkgs, _ := s.ActivePackages(ctx)
1379 if msg := shouldShowAdHocPackagesWarning(s, wsPkgs); msg != "" {
1380 return &source.CriticalError{
1381 MainError: errors.New(msg),
1382 }
1383 }
1384 // Even if workspace packages were returned, there still may be an error
1385 // with the user's workspace layout. Workspace packages that only have the
1386 // ID "command-line-arguments" are usually a symptom of a bad workspace
1387 // configuration.
1388 //
1389 // TODO(rfindley): re-evaluate this heuristic.
1390 if containsCommandLineArguments(wsPkgs) {
1391 return s.workspaceLayoutError(ctx)
1392 }
1393 return nil
1394 }
1395
1396 if errMsg := loadErr.MainError.Error(); strings.Contains(errMsg, "cannot find main module") || strings.Contains(errMsg, "go.mod file not found") {
1397 return s.workspaceLayoutError(ctx)
1398 }
1399 return loadErr
1400}
1401
1402const adHocPackagesWarning = `You are outside of a module and outside of $GOPATH/src.
1403If you are using modules, please open your editor to a directory in your module.
1404If you believe this warning is incorrect, please file an issue: https://github.com/golang/go/issues/new.`
1405
1406func shouldShowAdHocPackagesWarning(snapshot source.Snapshot, pkgs []source.Package) string {
1407 if snapshot.ValidBuildConfiguration() {
1408 return ""
1409 }
1410 for _, pkg := range pkgs {
1411 if len(pkg.MissingDependencies()) > 0 {
1412 return adHocPackagesWarning
1413 }
1414 }
1415 return ""
1416}
1417
1418func containsCommandLineArguments(pkgs []source.Package) bool {
1419 for _, pkg := range pkgs {
1420 if source.IsCommandLineArguments(pkg.ID()) {
1421 return true
1422 }
1423 }
1424 return false
1425}
1426
1427func (s *snapshot) awaitLoadedAllErrors(ctx context.Context) *source.CriticalError {
1428 // Do not return results until the snapshot's view has been initialized.
1429 s.AwaitInitialized(ctx)
1430
1431 // TODO(rfindley): Should we be more careful about returning the
1432 // initialization error? Is it possible for the initialization error to be
1433 // corrected without a successful reinitialization?
1434 s.mu.Lock()
1435 initializedErr := s.initializedErr
1436 s.mu.Unlock()
1437
1438 if initializedErr != nil {
1439 return initializedErr
1440 }
1441
1442 // TODO(rfindley): revisit this handling. Calling reloadWorkspace with a
1443 // cancelled context should have the same effect, so this preemptive handling
1444 // should not be necessary.
1445 //
1446 // Also: GetCriticalError ignores context cancellation errors. Should we be
1447 // returning nil here?
1448 if ctx.Err() != nil {
1449 return &source.CriticalError{MainError: ctx.Err()}
1450 }
1451
1452 // TODO(rfindley): reloading is not idempotent: if we try to reload or load
1453 // orphaned files below and fail, we won't try again. For that reason, we
1454 // could get different results from subsequent calls to this function, which
1455 // may cause critical errors to be suppressed.
1456
1457 if err := s.reloadWorkspace(ctx); err != nil {
1458 diags := s.extractGoCommandErrors(ctx, err)
1459 return &source.CriticalError{
1460 MainError: err,
1461 Diagnostics: diags,
1462 }
1463 }
1464
1465 if err := s.reloadOrphanedFiles(ctx); err != nil {
1466 diags := s.extractGoCommandErrors(ctx, err)
1467 return &source.CriticalError{
1468 MainError: err,
1469 Diagnostics: diags,
1470 }
1471 }
1472 return nil
1473}
1474
1475func (s *snapshot) getInitializationError(ctx context.Context) *source.CriticalError {
1476 s.mu.Lock()
1477 defer s.mu.Unlock()
1478
1479 return s.initializedErr
1480}
1481
1482func (s *snapshot) AwaitInitialized(ctx context.Context) {
1483 select {
1484 case <-ctx.Done():
1485 return
1486 case <-s.view.initialWorkspaceLoad:
1487 }
1488 // We typically prefer to run something as intensive as the IWL without
1489 // blocking. I'm not sure if there is a way to do that here.
1490 s.initialize(ctx, false)
1491}
1492
1493// reloadWorkspace reloads the metadata for all invalidated workspace packages.
1494func (s *snapshot) reloadWorkspace(ctx context.Context) error {
1495 var scopes []interface{}
1496 var seen map[PackagePath]bool
1497 s.mu.Lock()
1498 for _, pkgPaths := range s.shouldLoad {
1499 for _, pkgPath := range pkgPaths {
1500 if seen == nil {
1501 seen = make(map[PackagePath]bool)
1502 }
1503 if seen[pkgPath] {
1504 continue
1505 }
1506 seen[pkgPath] = true
1507 scopes = append(scopes, pkgPath)
1508 }
1509 }
1510 s.mu.Unlock()
1511
1512 if len(scopes) == 0 {
1513 return nil
1514 }
1515
1516 // If the view's build configuration is invalid, we cannot reload by
1517 // package path. Just reload the directory instead.
1518 if !s.ValidBuildConfiguration() {
1519 scopes = []interface{}{viewLoadScope("LOAD_INVALID_VIEW")}
1520 }
1521
1522 err := s.load(ctx, false, scopes...)
1523
1524 // Unless the context was canceled, set "shouldLoad" to false for all
1525 // of the metadata we attempted to load.
1526 if !errors.Is(err, context.Canceled) {
1527 s.clearShouldLoad(scopes...)
1528 }
1529
1530 return err
1531}
1532
1533func (s *snapshot) reloadOrphanedFiles(ctx context.Context) error {
1534 // When we load ./... or a package path directly, we may not get packages
1535 // that exist only in overlays. As a workaround, we search all of the files
1536 // available in the snapshot and reload their metadata individually using a
1537 // file= query if the metadata is unavailable.
1538 files := s.orphanedFiles()
1539
1540 // Files without a valid package declaration can't be loaded. Don't try.
1541 var scopes []interface{}
1542 for _, file := range files {
1543 pgf, err := s.ParseGo(ctx, file, source.ParseHeader)
1544 if err != nil {
1545 continue
1546 }
1547 if !pgf.File.Package.IsValid() {
1548 continue
1549 }
1550 scopes = append(scopes, fileURI(file.URI()))
1551 }
1552
1553 if len(scopes) == 0 {
1554 return nil
1555 }
1556
1557 // The regtests match this exact log message, keep them in sync.
1558 event.Log(ctx, "reloadOrphanedFiles reloading", tag.Query.Of(scopes))
1559 err := s.load(ctx, false, scopes...)
1560
1561 // If we failed to load some files, i.e. they have no metadata,
1562 // mark the failures so we don't bother retrying until the file's
1563 // content changes.
1564 //
1565 // TODO(rstambler): This may be an overestimate if the load stopped
1566 // early for an unrelated errors. Add a fallback?
1567 //
1568 // Check for context cancellation so that we don't incorrectly mark files
1569 // as unloadable, but don't return before setting all workspace packages.
1570 if ctx.Err() == nil && err != nil {
1571 event.Error(ctx, "reloadOrphanedFiles: failed to load", err, tag.Query.Of(scopes))
1572 s.mu.Lock()
1573 for _, scope := range scopes {
1574 uri := span.URI(scope.(fileURI))
1575 if s.noValidMetadataForURILocked(uri) {
1576 s.unloadableFiles[uri] = struct{}{}
1577 }
1578 }
1579 s.mu.Unlock()
1580 }
1581 return nil
1582}
1583
1584func (s *snapshot) orphanedFiles() []source.VersionedFileHandle {
1585 s.mu.Lock()
1586 defer s.mu.Unlock()
1587
1588 var files []source.VersionedFileHandle
1589 s.files.Range(func(uri span.URI, fh source.VersionedFileHandle) {
1590 // Don't try to reload metadata for go.mod files.
1591 if s.view.FileKind(fh) != source.Go {
1592 return
1593 }
1594 // If the URI doesn't belong to this view, then it's not in a workspace
1595 // package and should not be reloaded directly.
1596 if !source.InDir(s.view.folder.Filename(), uri.Filename()) {
1597 return
1598 }
1599 // If the file is not open and is in a vendor directory, don't treat it
1600 // like a workspace package.
1601 if _, ok := fh.(*overlay); !ok && inVendor(uri) {
1602 return
1603 }
1604 // Don't reload metadata for files we've already deemed unloadable.
1605 if _, ok := s.unloadableFiles[uri]; ok {
1606 return
1607 }
1608 if s.noValidMetadataForURILocked(uri) {
1609 files = append(files, fh)
1610 }
1611 })
1612 return files
1613}
1614
Robert Findleyb15dac22022-08-30 14:40:12 -04001615// TODO(golang/go#53756): this function needs to consider more than just the
1616// absolute URI, for example:
1617// - the position of /vendor/ with respect to the relevant module root
1618// - whether or not go.work is in use (as vendoring isn't supported in workspace mode)
1619//
1620// Most likely, each call site of inVendor needs to be reconsidered to
1621// understand and correctly implement the desired behavior.
1622func inVendor(uri span.URI) bool {
1623 if !strings.Contains(string(uri), "/vendor/") {
1624 return false
1625 }
1626 // Only packages in _subdirectories_ of /vendor/ are considered vendored
1627 // (/vendor/a/foo.go is vendored, /vendor/foo.go is not).
1628 split := strings.Split(string(uri), "/vendor/")
1629 if len(split) < 2 {
1630 return false
1631 }
1632 return strings.Contains(split[1], "/")
1633}
1634
1635// unappliedChanges is a file source that handles an uncloned snapshot.
1636type unappliedChanges struct {
1637 originalSnapshot *snapshot
1638 changes map[span.URI]*fileChange
1639}
1640
1641func (ac *unappliedChanges) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) {
1642 if c, ok := ac.changes[uri]; ok {
1643 return c.fileHandle, nil
1644 }
1645 return ac.originalSnapshot.GetFile(ctx, uri)
1646}
1647
1648func (s *snapshot) clone(ctx, bgCtx context.Context, changes map[span.URI]*fileChange, forceReloadMetadata bool) (*snapshot, func()) {
1649 ctx, done := event.Start(ctx, "snapshot.clone")
1650 defer done()
1651
1652 newWorkspace, reinit := s.workspace.Clone(ctx, changes, &unappliedChanges{
1653 originalSnapshot: s,
1654 changes: changes,
1655 })
1656
1657 s.mu.Lock()
1658 defer s.mu.Unlock()
1659
1660 // If there is an initialization error and a vendor directory changed, try to
1661 // reinit.
1662 if s.initializedErr != nil {
1663 for uri := range changes {
1664 if inVendor(uri) {
1665 reinit = true
1666 break
1667 }
1668 }
1669 }
1670
1671 bgCtx, cancel := context.WithCancel(bgCtx)
1672 result := &snapshot{
1673 id: s.id + 1,
1674 store: s.store,
1675 view: s.view,
1676 backgroundCtx: bgCtx,
1677 cancel: cancel,
1678 builtin: s.builtin,
1679 initialized: s.initialized,
1680 initializedErr: s.initializedErr,
1681 packages: s.packages.Clone(),
1682 isActivePackageCache: s.isActivePackageCache.Clone(),
1683 actions: s.actions.Clone(),
1684 files: s.files.Clone(),
1685 parsedGoFiles: s.parsedGoFiles.Clone(),
1686 parseKeysByURI: s.parseKeysByURI.Clone(),
1687 symbolizeHandles: s.symbolizeHandles.Clone(),
1688 workspacePackages: make(map[PackageID]PackagePath, len(s.workspacePackages)),
1689 unloadableFiles: make(map[span.URI]struct{}, len(s.unloadableFiles)),
1690 parseModHandles: s.parseModHandles.Clone(),
1691 parseWorkHandles: s.parseWorkHandles.Clone(),
1692 modTidyHandles: s.modTidyHandles.Clone(),
1693 modWhyHandles: s.modWhyHandles.Clone(),
1694 knownSubdirs: s.knownSubdirs.Clone(),
1695 workspace: newWorkspace,
1696 }
1697
1698 // The snapshot should be initialized if either s was uninitialized, or we've
1699 // detected a change that triggers reinitialization.
1700 if reinit {
1701 result.initialized = false
1702 }
1703
1704 // Create a lease on the new snapshot.
1705 // (Best to do this early in case the code below hides an
1706 // incref/decref operation that might destroy it prematurely.)
1707 release := result.Acquire()
1708
1709 // Copy the set of unloadable files.
1710 //
1711 // TODO(rfindley): this looks wrong. Shouldn't we clear unloadableFiles on
1712 // changes to environment or workspace layout, or more generally on any
1713 // metadata change?
1714 for k, v := range s.unloadableFiles {
1715 result.unloadableFiles[k] = v
1716 }
1717
1718 // TODO(adonovan): merge loops over "changes".
1719 for uri := range changes {
1720 keys, ok := result.parseKeysByURI.Get(uri)
1721 if ok {
1722 for _, key := range keys {
1723 result.parsedGoFiles.Delete(key)
1724 }
1725 result.parseKeysByURI.Delete(uri)
1726 }
1727
1728 // Invalidate go.mod-related handles.
1729 result.modTidyHandles.Delete(uri)
1730 result.modWhyHandles.Delete(uri)
1731
1732 // Invalidate handles for cached symbols.
1733 result.symbolizeHandles.Delete(uri)
1734 }
1735
1736 // Add all of the known subdirectories, but don't update them for the
1737 // changed files. We need to rebuild the workspace module to know the
1738 // true set of known subdirectories, but we don't want to do that in clone.
1739 result.knownSubdirs = s.knownSubdirs.Clone()
1740 result.knownSubdirsPatternCache = s.knownSubdirsPatternCache
1741 for _, c := range changes {
1742 result.unprocessedSubdirChanges = append(result.unprocessedSubdirChanges, c)
1743 }
1744
1745 // directIDs keeps track of package IDs that have directly changed.
1746 // It maps id->invalidateMetadata.
1747 directIDs := map[PackageID]bool{}
1748
1749 // Invalidate all package metadata if the workspace module has changed.
1750 if reinit {
1751 for k := range s.meta.metadata {
1752 directIDs[k] = true
1753 }
1754 }
1755
1756 // Compute invalidations based on file changes.
1757 anyImportDeleted := false // import deletions can resolve cycles
1758 anyFileOpenedOrClosed := false // opened files affect workspace packages
1759 anyFileAdded := false // adding a file can resolve missing dependencies
1760
1761 for uri, change := range changes {
1762 // The original FileHandle for this URI is cached on the snapshot.
1763 originalFH, _ := s.files.Get(uri)
1764 var originalOpen, newOpen bool
1765 _, originalOpen = originalFH.(*overlay)
1766 _, newOpen = change.fileHandle.(*overlay)
1767 anyFileOpenedOrClosed = anyFileOpenedOrClosed || (originalOpen != newOpen)
1768 anyFileAdded = anyFileAdded || (originalFH == nil && change.fileHandle != nil)
1769
1770 // If uri is a Go file, check if it has changed in a way that would
1771 // invalidate metadata. Note that we can't use s.view.FileKind here,
1772 // because the file type that matters is not what the *client* tells us,
1773 // but what the Go command sees.
1774 var invalidateMetadata, pkgFileChanged, importDeleted bool
1775 if strings.HasSuffix(uri.Filename(), ".go") {
1776 invalidateMetadata, pkgFileChanged, importDeleted = metadataChanges(ctx, s, originalFH, change.fileHandle)
1777 }
1778
1779 invalidateMetadata = invalidateMetadata || forceReloadMetadata || reinit
1780 anyImportDeleted = anyImportDeleted || importDeleted
1781
1782 // Mark all of the package IDs containing the given file.
1783 filePackageIDs := invalidatedPackageIDs(uri, s.meta.ids, pkgFileChanged)
1784 for id := range filePackageIDs {
1785 directIDs[id] = directIDs[id] || invalidateMetadata
1786 }
1787
1788 // Invalidate the previous modTidyHandle if any of the files have been
1789 // saved or if any of the metadata has been invalidated.
1790 if invalidateMetadata || fileWasSaved(originalFH, change.fileHandle) {
1791 // TODO(maybe): Only delete mod handles for
1792 // which the withoutURI is relevant.
1793 // Requires reverse-engineering the go command. (!)
1794
1795 result.modTidyHandles.Clear()
1796 result.modWhyHandles.Clear()
1797 }
1798
1799 result.parseModHandles.Delete(uri)
1800 result.parseWorkHandles.Delete(uri)
1801 // Handle the invalidated file; it may have new contents or not exist.
1802 if !change.exists {
1803 result.files.Delete(uri)
1804 } else {
1805 result.files.Set(uri, change.fileHandle)
1806 }
1807
1808 // Make sure to remove the changed file from the unloadable set.
1809 delete(result.unloadableFiles, uri)
1810 }
1811
1812 // Deleting an import can cause list errors due to import cycles to be
1813 // resolved. The best we can do without parsing the list error message is to
1814 // hope that list errors may have been resolved by a deleted import.
1815 //
1816 // We could do better by parsing the list error message. We already do this
1817 // to assign a better range to the list error, but for such critical
1818 // functionality as metadata, it's better to be conservative until it proves
1819 // impractical.
1820 //
1821 // We could also do better by looking at which imports were deleted and
1822 // trying to find cycles they are involved in. This fails when the file goes
1823 // from an unparseable state to a parseable state, as we don't have a
1824 // starting point to compare with.
1825 if anyImportDeleted {
1826 for id, metadata := range s.meta.metadata {
1827 if len(metadata.Errors) > 0 {
1828 directIDs[id] = true
1829 }
1830 }
1831 }
1832
1833 // Adding a file can resolve missing dependencies from existing packages.
1834 //
1835 // We could be smart here and try to guess which packages may have been
1836 // fixed, but until that proves necessary, just invalidate metadata for any
1837 // package with missing dependencies.
1838 if anyFileAdded {
1839 for id, metadata := range s.meta.metadata {
1840 if len(metadata.MissingDeps) > 0 {
1841 directIDs[id] = true
1842 }
1843 }
1844 }
1845
1846 // Invalidate reverse dependencies too.
1847 // idsToInvalidate keeps track of transitive reverse dependencies.
1848 // If an ID is present in the map, invalidate its types.
1849 // If an ID's value is true, invalidate its metadata too.
1850 idsToInvalidate := map[PackageID]bool{}
1851 var addRevDeps func(PackageID, bool)
1852 addRevDeps = func(id PackageID, invalidateMetadata bool) {
1853 current, seen := idsToInvalidate[id]
1854 newInvalidateMetadata := current || invalidateMetadata
1855
1856 // If we've already seen this ID, and the value of invalidate
1857 // metadata has not changed, we can return early.
1858 if seen && current == newInvalidateMetadata {
1859 return
1860 }
1861 idsToInvalidate[id] = newInvalidateMetadata
1862 for _, rid := range s.meta.importedBy[id] {
1863 addRevDeps(rid, invalidateMetadata)
1864 }
1865 }
1866 for id, invalidateMetadata := range directIDs {
1867 addRevDeps(id, invalidateMetadata)
1868 }
1869
1870 // Delete invalidated package type information.
1871 for id := range idsToInvalidate {
1872 for _, mode := range source.AllParseModes {
1873 key := packageKey{mode, id}
1874 result.packages.Delete(key)
1875 }
1876 }
1877
1878 // Copy actions.
1879 // TODO(adonovan): opt: avoid iteration over s.actions.
1880 var actionsToDelete []actionKey
1881 s.actions.Range(func(k, _ interface{}) {
1882 key := k.(actionKey)
Alan Donovand49f9602022-08-31 14:41:23 -04001883 if _, ok := idsToInvalidate[key.pkgid]; ok {
Robert Findleyb15dac22022-08-30 14:40:12 -04001884 actionsToDelete = append(actionsToDelete, key)
1885 }
1886 })
1887 for _, key := range actionsToDelete {
1888 result.actions.Delete(key)
1889 }
1890
1891 // If a file has been deleted, we must delete metadata for all packages
1892 // containing that file.
1893 //
1894 // TODO(rfindley): why not keep invalid metadata in this case? If we
1895 // otherwise allow operate on invalid metadata, why not continue to do so,
1896 // skipping the missing file?
1897 skipID := map[PackageID]bool{}
1898 for _, c := range changes {
1899 if c.exists {
1900 continue
1901 }
1902 // The file has been deleted.
1903 if ids, ok := s.meta.ids[c.fileHandle.URI()]; ok {
1904 for _, id := range ids {
1905 skipID[id] = true
1906 }
1907 }
1908 }
1909
1910 // Any packages that need loading in s still need loading in the new
1911 // snapshot.
1912 for k, v := range s.shouldLoad {
1913 if result.shouldLoad == nil {
1914 result.shouldLoad = make(map[PackageID][]PackagePath)
1915 }
1916 result.shouldLoad[k] = v
1917 }
1918
1919 // TODO(rfindley): consolidate the this workspace mode detection with
1920 // workspace invalidation.
1921 workspaceModeChanged := s.workspaceMode() != result.workspaceMode()
1922
1923 // We delete invalid metadata in the following cases:
1924 // - If we are forcing a reload of metadata.
1925 // - If the workspace mode has changed, as stale metadata may produce
1926 // confusing or incorrect diagnostics.
1927 //
1928 // TODO(rfindley): we should probably also clear metadata if we are
1929 // reinitializing the workspace, as otherwise we could leave around a bunch
1930 // of irrelevant and duplicate metadata (for example, if the module path
1931 // changed). However, this breaks the "experimentalUseInvalidMetadata"
1932 // feature, which relies on stale metadata when, for example, a go.mod file
1933 // is broken via invalid syntax.
1934 deleteInvalidMetadata := forceReloadMetadata || workspaceModeChanged
1935
1936 // Compute which metadata updates are required. We only need to invalidate
1937 // packages directly containing the affected file, and only if it changed in
1938 // a relevant way.
1939 metadataUpdates := make(map[PackageID]*KnownMetadata)
1940 for k, v := range s.meta.metadata {
1941 invalidateMetadata := idsToInvalidate[k]
1942
1943 // For metadata that has been newly invalidated, capture package paths
1944 // requiring reloading in the shouldLoad map.
1945 if invalidateMetadata && !source.IsCommandLineArguments(string(v.ID)) {
1946 if result.shouldLoad == nil {
1947 result.shouldLoad = make(map[PackageID][]PackagePath)
1948 }
1949 needsReload := []PackagePath{v.PkgPath}
1950 if v.ForTest != "" && v.ForTest != v.PkgPath {
1951 // When reloading test variants, always reload their ForTest package as
1952 // well. Otherwise, we may miss test variants in the resulting load.
1953 //
1954 // TODO(rfindley): is this actually sufficient? Is it possible that
1955 // other test variants may be invalidated? Either way, we should
1956 // determine exactly what needs to be reloaded here.
1957 needsReload = append(needsReload, v.ForTest)
1958 }
1959 result.shouldLoad[k] = needsReload
1960 }
1961
1962 // Check whether the metadata should be deleted.
1963 if skipID[k] || (invalidateMetadata && deleteInvalidMetadata) {
1964 metadataUpdates[k] = nil
1965 continue
1966 }
1967
1968 // Check if the metadata has changed.
1969 valid := v.Valid && !invalidateMetadata
1970 if valid != v.Valid {
1971 // Mark invalidated metadata rather than deleting it outright.
1972 metadataUpdates[k] = &KnownMetadata{
1973 Metadata: v.Metadata,
1974 Valid: valid,
1975 }
1976 }
1977 }
1978
1979 // Update metadata, if necessary.
1980 result.meta = s.meta.Clone(metadataUpdates)
1981
1982 // Update workspace and active packages, if necessary.
1983 if result.meta != s.meta || anyFileOpenedOrClosed {
1984 result.workspacePackages = computeWorkspacePackagesLocked(result, result.meta)
1985 result.resetIsActivePackageLocked()
1986 } else {
1987 result.workspacePackages = s.workspacePackages
1988 }
1989
1990 // Don't bother copying the importedBy graph,
1991 // as it changes each time we update metadata.
1992
1993 // If the snapshot's workspace mode has changed, the packages loaded using
1994 // the previous mode are no longer relevant, so clear them out.
1995 if workspaceModeChanged {
1996 result.workspacePackages = map[PackageID]PackagePath{}
1997 }
1998 result.dumpWorkspace("clone")
1999 return result, release
2000}
2001
2002// invalidatedPackageIDs returns all packages invalidated by a change to uri.
2003// If we haven't seen this URI before, we guess based on files in the same
2004// directory. This is of course incorrect in build systems where packages are
2005// not organized by directory.
2006//
2007// If packageFileChanged is set, the file is either a new file, or has a new
2008// package name. In this case, all known packages in the directory will be
2009// invalidated.
2010func invalidatedPackageIDs(uri span.URI, known map[span.URI][]PackageID, packageFileChanged bool) map[PackageID]struct{} {
2011 invalidated := make(map[PackageID]struct{})
2012
2013 // At a minimum, we invalidate packages known to contain uri.
2014 for _, id := range known[uri] {
2015 invalidated[id] = struct{}{}
2016 }
2017
2018 // If the file didn't move to a new package, we should only invalidate the
2019 // packages it is currently contained inside.
2020 if !packageFileChanged && len(invalidated) > 0 {
2021 return invalidated
2022 }
2023
2024 // This is a file we don't yet know about, or which has moved packages. Guess
2025 // relevant packages by considering files in the same directory.
2026
2027 // Cache of FileInfo to avoid unnecessary stats for multiple files in the
2028 // same directory.
2029 stats := make(map[string]struct {
2030 os.FileInfo
2031 error
2032 })
2033 getInfo := func(dir string) (os.FileInfo, error) {
2034 if res, ok := stats[dir]; ok {
2035 return res.FileInfo, res.error
2036 }
2037 fi, err := os.Stat(dir)
2038 stats[dir] = struct {
2039 os.FileInfo
2040 error
2041 }{fi, err}
2042 return fi, err
2043 }
2044 dir := filepath.Dir(uri.Filename())
2045 fi, err := getInfo(dir)
2046 if err == nil {
2047 // Aggregate all possibly relevant package IDs.
2048 for knownURI, ids := range known {
2049 knownDir := filepath.Dir(knownURI.Filename())
2050 knownFI, err := getInfo(knownDir)
2051 if err != nil {
2052 continue
2053 }
2054 if os.SameFile(fi, knownFI) {
2055 for _, id := range ids {
2056 invalidated[id] = struct{}{}
2057 }
2058 }
2059 }
2060 }
2061 return invalidated
2062}
2063
2064// fileWasSaved reports whether the FileHandle passed in has been saved. It
2065// accomplishes this by checking to see if the original and current FileHandles
2066// are both overlays, and if the current FileHandle is saved while the original
2067// FileHandle was not saved.
2068func fileWasSaved(originalFH, currentFH source.FileHandle) bool {
2069 c, ok := currentFH.(*overlay)
2070 if !ok || c == nil {
2071 return true
2072 }
2073 o, ok := originalFH.(*overlay)
2074 if !ok || o == nil {
2075 return c.saved
2076 }
2077 return !o.saved && c.saved
2078}
2079
2080// metadataChanges detects features of the change from oldFH->newFH that may
2081// affect package metadata.
2082//
2083// It uses lockedSnapshot to access cached parse information. lockedSnapshot
2084// must be locked.
2085//
2086// The result parameters have the following meaning:
2087// - invalidate means that package metadata for packages containing the file
2088// should be invalidated.
2089// - pkgFileChanged means that the file->package associates for the file have
2090// changed (possibly because the file is new, or because its package name has
2091// changed).
2092// - importDeleted means that an import has been deleted, or we can't
2093// determine if an import was deleted due to errors.
2094func metadataChanges(ctx context.Context, lockedSnapshot *snapshot, oldFH, newFH source.FileHandle) (invalidate, pkgFileChanged, importDeleted bool) {
2095 if oldFH == nil || newFH == nil { // existential changes
2096 changed := (oldFH == nil) != (newFH == nil)
2097 return changed, changed, (newFH == nil) // we don't know if an import was deleted
2098 }
2099
2100 // If the file hasn't changed, there's no need to reload.
2101 if oldFH.FileIdentity() == newFH.FileIdentity() {
2102 return false, false, false
2103 }
2104
2105 // Parse headers to compare package names and imports.
2106 oldHead, oldErr := peekOrParse(ctx, lockedSnapshot, oldFH, source.ParseHeader)
2107 newHead, newErr := peekOrParse(ctx, lockedSnapshot, newFH, source.ParseHeader)
2108
2109 if oldErr != nil || newErr != nil {
2110 // TODO(rfindley): we can get here if newFH does not exists. There is
2111 // asymmetry here, in that newFH may be non-nil even if the underlying file
2112 // does not exist.
2113 //
2114 // We should not produce a non-nil filehandle for a file that does not exist.
2115 errChanged := (oldErr == nil) != (newErr == nil)
2116 return errChanged, errChanged, (newErr != nil) // we don't know if an import was deleted
2117 }
2118
2119 // `go list` fails completely if the file header cannot be parsed. If we go
2120 // from a non-parsing state to a parsing state, we should reload.
2121 if oldHead.ParseErr != nil && newHead.ParseErr == nil {
2122 return true, true, true // We don't know what changed, so fall back on full invalidation.
2123 }
2124
2125 // If a package name has changed, the set of package imports may have changed
2126 // in ways we can't detect here. Assume an import has been deleted.
2127 if oldHead.File.Name.Name != newHead.File.Name.Name {
2128 return true, true, true
2129 }
2130
2131 // Check whether package imports have changed. Only consider potentially
2132 // valid imports paths.
2133 oldImports := validImports(oldHead.File.Imports)
2134 newImports := validImports(newHead.File.Imports)
2135
2136 for path := range newImports {
2137 if _, ok := oldImports[path]; ok {
2138 delete(oldImports, path)
2139 } else {
2140 invalidate = true // a new, potentially valid import was added
2141 }
2142 }
2143
2144 if len(oldImports) > 0 {
2145 invalidate = true
2146 importDeleted = true
2147 }
2148
2149 // If the change does not otherwise invalidate metadata, get the full ASTs in
2150 // order to check magic comments.
2151 //
2152 // Note: if this affects performance we can probably avoid parsing in the
2153 // common case by first scanning the source for potential comments.
2154 if !invalidate {
2155 origFull, oldErr := peekOrParse(ctx, lockedSnapshot, oldFH, source.ParseFull)
2156 currFull, newErr := peekOrParse(ctx, lockedSnapshot, newFH, source.ParseFull)
2157 if oldErr == nil && newErr == nil {
2158 invalidate = magicCommentsChanged(origFull.File, currFull.File)
2159 } else {
2160 // At this point, we shouldn't ever fail to produce a ParsedGoFile, as
2161 // we're already past header parsing.
2162 bug.Reportf("metadataChanges: unparseable file %v (old error: %v, new error: %v)", oldFH.URI(), oldErr, newErr)
2163 }
2164 }
2165
2166 return invalidate, pkgFileChanged, importDeleted
2167}
2168
2169// peekOrParse returns the cached ParsedGoFile if it exists,
2170// otherwise parses without populating the cache.
2171//
2172// It returns an error if the file could not be read (note that parsing errors
2173// are stored in ParsedGoFile.ParseErr).
2174//
2175// lockedSnapshot must be locked.
2176func peekOrParse(ctx context.Context, lockedSnapshot *snapshot, fh source.FileHandle, mode source.ParseMode) (*source.ParsedGoFile, error) {
2177 // Peek in the cache without populating it.
2178 // We do this to reduce retained heap, not work.
2179 if parsed, _ := lockedSnapshot.peekParseGoLocked(fh, mode); parsed != nil {
2180 return parsed, nil // cache hit
2181 }
2182 return parseGoImpl(ctx, token.NewFileSet(), fh, mode)
2183}
2184
2185func magicCommentsChanged(original *ast.File, current *ast.File) bool {
2186 oldComments := extractMagicComments(original)
2187 newComments := extractMagicComments(current)
2188 if len(oldComments) != len(newComments) {
2189 return true
2190 }
2191 for i := range oldComments {
2192 if oldComments[i] != newComments[i] {
2193 return true
2194 }
2195 }
2196 return false
2197}
2198
2199// validImports extracts the set of valid import paths from imports.
2200func validImports(imports []*ast.ImportSpec) map[string]struct{} {
2201 m := make(map[string]struct{})
2202 for _, spec := range imports {
2203 if path := spec.Path.Value; validImportPath(path) {
2204 m[path] = struct{}{}
2205 }
2206 }
2207 return m
2208}
2209
2210func validImportPath(path string) bool {
2211 path, err := strconv.Unquote(path)
2212 if err != nil {
2213 return false
2214 }
2215 if path == "" {
2216 return false
2217 }
2218 if path[len(path)-1] == '/' {
2219 return false
2220 }
2221 return true
2222}
2223
2224var buildConstraintOrEmbedRe = regexp.MustCompile(`^//(go:embed|go:build|\s*\+build).*`)
2225
2226// extractMagicComments finds magic comments that affect metadata in f.
2227func extractMagicComments(f *ast.File) []string {
2228 var results []string
2229 for _, cg := range f.Comments {
2230 for _, c := range cg.List {
2231 if buildConstraintOrEmbedRe.MatchString(c.Text) {
2232 results = append(results, c.Text)
2233 }
2234 }
2235 }
2236 return results
2237}
2238
2239func (s *snapshot) BuiltinFile(ctx context.Context) (*source.ParsedGoFile, error) {
2240 s.AwaitInitialized(ctx)
2241
2242 s.mu.Lock()
2243 builtin := s.builtin
2244 s.mu.Unlock()
2245
2246 if builtin == "" {
2247 return nil, fmt.Errorf("no builtin package for view %s", s.view.name)
2248 }
2249
2250 fh, err := s.GetFile(ctx, builtin)
2251 if err != nil {
2252 return nil, err
2253 }
2254 return s.ParseGo(ctx, fh, source.ParseFull)
2255}
2256
2257func (s *snapshot) IsBuiltin(ctx context.Context, uri span.URI) bool {
2258 s.mu.Lock()
2259 defer s.mu.Unlock()
2260 // We should always get the builtin URI in a canonical form, so use simple
2261 // string comparison here. span.CompareURI is too expensive.
2262 return uri == s.builtin
2263}
2264
2265func (s *snapshot) setBuiltin(path string) {
2266 s.mu.Lock()
2267 defer s.mu.Unlock()
2268
2269 s.builtin = span.URIFromPath(path)
2270}
2271
2272// BuildGoplsMod generates a go.mod file for all modules in the workspace. It
2273// bypasses any existing gopls.mod.
2274func (s *snapshot) BuildGoplsMod(ctx context.Context) (*modfile.File, error) {
2275 allModules, err := findModules(s.view.folder, pathExcludedByFilterFunc(s.view.rootURI.Filename(), s.view.gomodcache, s.View().Options()), 0)
2276 if err != nil {
2277 return nil, err
2278 }
2279 return buildWorkspaceModFile(ctx, allModules, s)
2280}
2281
2282// TODO(rfindley): move this to workspace.go
2283func buildWorkspaceModFile(ctx context.Context, modFiles map[span.URI]struct{}, fs source.FileSource) (*modfile.File, error) {
2284 file := &modfile.File{}
2285 file.AddModuleStmt("gopls-workspace")
2286 // Track the highest Go version, to be set on the workspace module.
2287 // Fall back to 1.12 -- old versions insist on having some version.
2288 goVersion := "1.12"
2289
2290 paths := map[string]span.URI{}
2291 excludes := map[string][]string{}
2292 var sortedModURIs []span.URI
2293 for uri := range modFiles {
2294 sortedModURIs = append(sortedModURIs, uri)
2295 }
2296 sort.Slice(sortedModURIs, func(i, j int) bool {
2297 return sortedModURIs[i] < sortedModURIs[j]
2298 })
2299 for _, modURI := range sortedModURIs {
2300 fh, err := fs.GetFile(ctx, modURI)
2301 if err != nil {
2302 return nil, err
2303 }
2304 content, err := fh.Read()
2305 if err != nil {
2306 return nil, err
2307 }
2308 parsed, err := modfile.Parse(fh.URI().Filename(), content, nil)
2309 if err != nil {
2310 return nil, err
2311 }
2312 if file == nil || parsed.Module == nil {
2313 return nil, fmt.Errorf("no module declaration for %s", modURI)
2314 }
2315 // Prepend "v" to go versions to make them valid semver.
2316 if parsed.Go != nil && semver.Compare("v"+goVersion, "v"+parsed.Go.Version) < 0 {
2317 goVersion = parsed.Go.Version
2318 }
2319 path := parsed.Module.Mod.Path
2320 if seen, ok := paths[path]; ok {
2321 return nil, fmt.Errorf("found module %q multiple times in the workspace, at:\n\t%q\n\t%q", path, seen, modURI)
2322 }
2323 paths[path] = modURI
2324 // If the module's path includes a major version, we expect it to have
2325 // a matching major version.
2326 _, majorVersion, _ := module.SplitPathVersion(path)
2327 if majorVersion == "" {
2328 majorVersion = "/v0"
2329 }
2330 majorVersion = strings.TrimLeft(majorVersion, "/.") // handle gopkg.in versions
2331 file.AddNewRequire(path, source.WorkspaceModuleVersion(majorVersion), false)
2332 if err := file.AddReplace(path, "", dirURI(modURI).Filename(), ""); err != nil {
2333 return nil, err
2334 }
2335 for _, exclude := range parsed.Exclude {
2336 excludes[exclude.Mod.Path] = append(excludes[exclude.Mod.Path], exclude.Mod.Version)
2337 }
2338 }
2339 if goVersion != "" {
2340 file.AddGoStmt(goVersion)
2341 }
2342 // Go back through all of the modules to handle any of their replace
2343 // statements.
2344 for _, modURI := range sortedModURIs {
2345 fh, err := fs.GetFile(ctx, modURI)
2346 if err != nil {
2347 return nil, err
2348 }
2349 content, err := fh.Read()
2350 if err != nil {
2351 return nil, err
2352 }
2353 parsed, err := modfile.Parse(fh.URI().Filename(), content, nil)
2354 if err != nil {
2355 return nil, err
2356 }
2357 // If any of the workspace modules have replace directives, they need
2358 // to be reflected in the workspace module.
2359 for _, rep := range parsed.Replace {
2360 // Don't replace any modules that are in our workspace--we should
2361 // always use the version in the workspace.
2362 if _, ok := paths[rep.Old.Path]; ok {
2363 continue
2364 }
2365 newPath := rep.New.Path
2366 newVersion := rep.New.Version
2367 // If a replace points to a module in the workspace, make sure we
2368 // direct it to version of the module in the workspace.
2369 if m, ok := paths[rep.New.Path]; ok {
2370 newPath = dirURI(m).Filename()
2371 newVersion = ""
2372 } else if rep.New.Version == "" && !filepath.IsAbs(rep.New.Path) {
2373 // Make any relative paths absolute.
2374 newPath = filepath.Join(dirURI(modURI).Filename(), rep.New.Path)
2375 }
2376 if err := file.AddReplace(rep.Old.Path, rep.Old.Version, newPath, newVersion); err != nil {
2377 return nil, err
2378 }
2379 }
2380 }
2381 for path, versions := range excludes {
2382 for _, version := range versions {
2383 file.AddExclude(path, version)
2384 }
2385 }
2386 file.SortBlocks()
2387 return file, nil
2388}
2389
2390func buildWorkspaceSumFile(ctx context.Context, modFiles map[span.URI]struct{}, fs source.FileSource) ([]byte, error) {
2391 allSums := map[module.Version][]string{}
2392 for modURI := range modFiles {
2393 // TODO(rfindley): factor out this pattern into a uripath package.
2394 sumURI := span.URIFromPath(filepath.Join(filepath.Dir(modURI.Filename()), "go.sum"))
2395 fh, err := fs.GetFile(ctx, sumURI)
2396 if err != nil {
2397 continue
2398 }
2399 data, err := fh.Read()
2400 if os.IsNotExist(err) {
2401 continue
2402 }
2403 if err != nil {
2404 return nil, fmt.Errorf("reading go sum: %w", err)
2405 }
2406 if err := readGoSum(allSums, sumURI.Filename(), data); err != nil {
2407 return nil, err
2408 }
2409 }
2410 // This logic to write go.sum is copied (with minor modifications) from
2411 // https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/modfetch/fetch.go;l=631;drc=762eda346a9f4062feaa8a9fc0d17d72b11586f0
2412 var mods []module.Version
2413 for m := range allSums {
2414 mods = append(mods, m)
2415 }
2416 module.Sort(mods)
2417
2418 var buf bytes.Buffer
2419 for _, m := range mods {
2420 list := allSums[m]
2421 sort.Strings(list)
2422 // Note (rfindley): here we add all sum lines without verification, because
2423 // the assumption is that if they come from a go.sum file, they are
2424 // trusted.
2425 for _, h := range list {
2426 fmt.Fprintf(&buf, "%s %s %s\n", m.Path, m.Version, h)
2427 }
2428 }
2429 return buf.Bytes(), nil
2430}
2431
2432// readGoSum is copied (with minor modifications) from
2433// https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/modfetch/fetch.go;l=398;drc=762eda346a9f4062feaa8a9fc0d17d72b11586f0
2434func readGoSum(dst map[module.Version][]string, file string, data []byte) error {
2435 lineno := 0
2436 for len(data) > 0 {
2437 var line []byte
2438 lineno++
2439 i := bytes.IndexByte(data, '\n')
2440 if i < 0 {
2441 line, data = data, nil
2442 } else {
2443 line, data = data[:i], data[i+1:]
2444 }
2445 f := strings.Fields(string(line))
2446 if len(f) == 0 {
2447 // blank line; skip it
2448 continue
2449 }
2450 if len(f) != 3 {
2451 return fmt.Errorf("malformed go.sum:\n%s:%d: wrong number of fields %v", file, lineno, len(f))
2452 }
2453 mod := module.Version{Path: f[0], Version: f[1]}
2454 dst[mod] = append(dst[mod], f[2])
2455 }
2456 return nil
2457}