Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / internal / lsp / cache / session.go
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package cache
6
7 import (
8         "context"
9         "fmt"
10         "os"
11         "path/filepath"
12         "strconv"
13         "strings"
14         "sync"
15         "sync/atomic"
16
17         "golang.org/x/tools/internal/event"
18         "golang.org/x/tools/internal/gocommand"
19         "golang.org/x/tools/internal/imports"
20         "golang.org/x/tools/internal/lsp/source"
21         "golang.org/x/tools/internal/span"
22         "golang.org/x/tools/internal/xcontext"
23         errors "golang.org/x/xerrors"
24 )
25
26 type Session struct {
27         cache *Cache
28         id    string
29
30         optionsMu sync.Mutex
31         options   *source.Options
32
33         viewMu  sync.Mutex
34         views   []*View
35         viewMap map[span.URI]*View
36
37         overlayMu sync.Mutex
38         overlays  map[span.URI]*overlay
39
40         // gocmdRunner guards go command calls from concurrency errors.
41         gocmdRunner *gocommand.Runner
42 }
43
44 type overlay struct {
45         session *Session
46         uri     span.URI
47         text    []byte
48         hash    string
49         version float64
50         kind    source.FileKind
51
52         // saved is true if a file matches the state on disk,
53         // and therefore does not need to be part of the overlay sent to go/packages.
54         saved bool
55 }
56
57 func (o *overlay) Read() ([]byte, error) {
58         return o.text, nil
59 }
60
61 func (o *overlay) FileIdentity() source.FileIdentity {
62         return source.FileIdentity{
63                 URI:  o.uri,
64                 Hash: o.hash,
65                 Kind: o.kind,
66         }
67 }
68
69 func (o *overlay) VersionedFileIdentity() source.VersionedFileIdentity {
70         return source.VersionedFileIdentity{
71                 URI:       o.uri,
72                 SessionID: o.session.id,
73                 Version:   o.version,
74         }
75 }
76
77 func (o *overlay) Kind() source.FileKind {
78         return o.kind
79 }
80
81 func (o *overlay) URI() span.URI {
82         return o.uri
83 }
84
85 func (o *overlay) Version() float64 {
86         return o.version
87 }
88
89 func (o *overlay) Session() string {
90         return o.session.id
91 }
92
93 func (o *overlay) Saved() bool {
94         return o.saved
95 }
96
97 // closedFile implements LSPFile for a file that the editor hasn't told us about.
98 type closedFile struct {
99         source.FileHandle
100 }
101
102 func (c *closedFile) VersionedFileIdentity() source.VersionedFileIdentity {
103         return source.VersionedFileIdentity{
104                 URI:       c.FileHandle.URI(),
105                 SessionID: "",
106                 Version:   0,
107         }
108 }
109
110 func (c *closedFile) Session() string {
111         return ""
112 }
113
114 func (c *closedFile) Version() float64 {
115         return 0
116 }
117
118 func (s *Session) ID() string     { return s.id }
119 func (s *Session) String() string { return s.id }
120
121 func (s *Session) Options() *source.Options {
122         s.optionsMu.Lock()
123         defer s.optionsMu.Unlock()
124         return s.options
125 }
126
127 func (s *Session) SetOptions(options *source.Options) {
128         s.optionsMu.Lock()
129         defer s.optionsMu.Unlock()
130         s.options = options
131 }
132
133 func (s *Session) Shutdown(ctx context.Context) {
134         s.viewMu.Lock()
135         defer s.viewMu.Unlock()
136         for _, view := range s.views {
137                 view.shutdown(ctx)
138         }
139         s.views = nil
140         s.viewMap = nil
141         event.Log(ctx, "Shutdown session", KeyShutdownSession.Of(s))
142 }
143
144 func (s *Session) Cache() interface{} {
145         return s.cache
146 }
147
148 func (s *Session) NewView(ctx context.Context, name string, folder span.URI, options *source.Options) (source.View, source.Snapshot, func(), error) {
149         s.viewMu.Lock()
150         defer s.viewMu.Unlock()
151         view, snapshot, release, err := s.createView(ctx, name, folder, options, 0)
152         if err != nil {
153                 return nil, nil, func() {}, err
154         }
155         s.views = append(s.views, view)
156         // we always need to drop the view map
157         s.viewMap = make(map[span.URI]*View)
158         return view, snapshot, release, nil
159 }
160
161 func (s *Session) createView(ctx context.Context, name string, folder span.URI, options *source.Options, snapshotID uint64) (*View, *snapshot, func(), error) {
162         index := atomic.AddInt64(&viewIndex, 1)
163
164         if s.cache.options != nil {
165                 s.cache.options(options)
166         }
167
168         // Set the module-specific information.
169         ws, err := s.getWorkspaceInformation(ctx, folder, options)
170         if err != nil {
171                 return nil, nil, func() {}, err
172         }
173
174         // If workspace module mode is enabled, find all of the modules in the
175         // workspace. By default, we just find the root module.
176         var modules map[span.URI]*moduleRoot
177         modules, err = findWorkspaceModules(ctx, ws.rootURI, options)
178         if err != nil {
179                 return nil, nil, func() {}, err
180         }
181
182         // We want a true background context and not a detached context here
183         // the spans need to be unrelated and no tag values should pollute it.
184         baseCtx := event.Detach(xcontext.Detach(ctx))
185         backgroundCtx, cancel := context.WithCancel(baseCtx)
186
187         v := &View{
188                 session:              s,
189                 initialized:          make(chan struct{}),
190                 initializationSema:   make(chan struct{}, 1),
191                 initializeOnce:       &sync.Once{},
192                 id:                   strconv.FormatInt(index, 10),
193                 options:              options,
194                 baseCtx:              baseCtx,
195                 backgroundCtx:        backgroundCtx,
196                 cancel:               cancel,
197                 name:                 name,
198                 folder:               folder,
199                 filesByURI:           make(map[span.URI]*fileBase),
200                 filesByBase:          make(map[string][]*fileBase),
201                 workspaceInformation: *ws,
202         }
203         v.importsState = &importsState{
204                 ctx: backgroundCtx,
205                 processEnv: &imports.ProcessEnv{
206                         GocmdRunner: s.gocmdRunner,
207                         WorkingDir:  folder.Filename(),
208                         Env:         ws.goEnv,
209                 },
210         }
211         v.snapshot = &snapshot{
212                 id:                snapshotID,
213                 view:              v,
214                 generation:        s.cache.store.Generation(generationName(v, 0)),
215                 packages:          make(map[packageKey]*packageHandle),
216                 ids:               make(map[span.URI][]packageID),
217                 metadata:          make(map[packageID]*metadata),
218                 files:             make(map[span.URI]source.VersionedFileHandle),
219                 goFiles:           make(map[parseKey]*parseGoHandle),
220                 importedBy:        make(map[packageID][]packageID),
221                 actions:           make(map[actionKey]*actionHandle),
222                 workspacePackages: make(map[packageID]packagePath),
223                 unloadableFiles:   make(map[span.URI]struct{}),
224                 parseModHandles:   make(map[span.URI]*parseModHandle),
225                 modTidyHandles:    make(map[span.URI]*modTidyHandle),
226                 modUpgradeHandles: make(map[span.URI]*modUpgradeHandle),
227                 modWhyHandles:     make(map[span.URI]*modWhyHandle),
228                 modules:           modules,
229         }
230
231         v.snapshot.workspaceDirectories = v.snapshot.findWorkspaceDirectories(ctx)
232
233         // Initialize the view without blocking.
234         initCtx, initCancel := context.WithCancel(xcontext.Detach(ctx))
235         v.initCancelFirstAttempt = initCancel
236         snapshot := v.snapshot
237         release := snapshot.generation.Acquire(initCtx)
238         go func() {
239                 snapshot.initialize(initCtx, true)
240                 release()
241         }()
242         return v, snapshot, snapshot.generation.Acquire(ctx), nil
243 }
244
245 // findWorkspaceModules walks the view's root folder, looking for go.mod files.
246 // Any that are found are added to the view's set of modules, which are then
247 // used to construct the workspace module.
248 //
249 // It assumes that the caller has not yet created the view, and therefore does
250 // not lock any of the internal data structures before accessing them.
251 //
252 // TODO(rstambler): Check overlays for go.mod files.
253 func findWorkspaceModules(ctx context.Context, root span.URI, options *source.Options) (map[span.URI]*moduleRoot, error) {
254         // Walk the view's folder to find all modules in the view.
255         modules := make(map[span.URI]*moduleRoot)
256         if !options.ExperimentalWorkspaceModule {
257                 path := filepath.Join(root.Filename(), "go.mod")
258                 if info, _ := os.Stat(path); info != nil {
259                         if m := getViewModule(ctx, root, span.URIFromPath(path), options); m != nil {
260                                 modules[m.rootURI] = m
261                         }
262                 }
263                 return modules, nil
264         }
265         return modules, filepath.Walk(root.Filename(), func(path string, info os.FileInfo, err error) error {
266                 if err != nil {
267                         // Probably a permission error. Keep looking.
268                         return filepath.SkipDir
269                 }
270                 // For any path that is not the workspace folder, check if the path
271                 // would be ignored by the go command. Vendor directories also do not
272                 // contain workspace modules.
273                 if info.IsDir() && path != root.Filename() {
274                         suffix := strings.TrimPrefix(path, root.Filename())
275                         switch {
276                         case checkIgnored(suffix),
277                                 strings.Contains(filepath.ToSlash(suffix), "/vendor/"):
278                                 return filepath.SkipDir
279                         }
280                 }
281                 // We're only interested in go.mod files.
282                 if filepath.Base(path) == "go.mod" {
283                         if m := getViewModule(ctx, root, span.URIFromPath(path), options); m != nil {
284                                 modules[m.rootURI] = m
285                         }
286                 }
287                 return nil
288         })
289 }
290
291 // View returns the view by name.
292 func (s *Session) View(name string) source.View {
293         s.viewMu.Lock()
294         defer s.viewMu.Unlock()
295         for _, view := range s.views {
296                 if view.Name() == name {
297                         return view
298                 }
299         }
300         return nil
301 }
302
303 // ViewOf returns a view corresponding to the given URI.
304 // If the file is not already associated with a view, pick one using some heuristics.
305 func (s *Session) ViewOf(uri span.URI) (source.View, error) {
306         return s.viewOf(uri)
307 }
308
309 func (s *Session) viewOf(uri span.URI) (*View, error) {
310         s.viewMu.Lock()
311         defer s.viewMu.Unlock()
312
313         // Check if we already know this file.
314         if v, found := s.viewMap[uri]; found {
315                 return v, nil
316         }
317         // Pick the best view for this file and memoize the result.
318         v, err := s.bestView(uri)
319         if err != nil {
320                 return nil, err
321         }
322         s.viewMap[uri] = v
323         return v, nil
324 }
325
326 func (s *Session) viewsOf(uri span.URI) []*View {
327         s.viewMu.Lock()
328         defer s.viewMu.Unlock()
329
330         var views []*View
331         for _, view := range s.views {
332                 if strings.HasPrefix(string(uri), string(view.Folder())) {
333                         views = append(views, view)
334                 }
335         }
336         return views
337 }
338
339 func (s *Session) Views() []source.View {
340         s.viewMu.Lock()
341         defer s.viewMu.Unlock()
342         result := make([]source.View, len(s.views))
343         for i, v := range s.views {
344                 result[i] = v
345         }
346         return result
347 }
348
349 // bestView finds the best view to associate a given URI with.
350 // viewMu must be held when calling this method.
351 func (s *Session) bestView(uri span.URI) (*View, error) {
352         if len(s.views) == 0 {
353                 return nil, errors.Errorf("no views in the session")
354         }
355         // we need to find the best view for this file
356         var longest *View
357         for _, view := range s.views {
358                 if longest != nil && len(longest.Folder()) > len(view.Folder()) {
359                         continue
360                 }
361                 if view.contains(uri) {
362                         longest = view
363                 }
364         }
365         if longest != nil {
366                 return longest, nil
367         }
368         // Try our best to return a view that knows the file.
369         for _, view := range s.views {
370                 if view.knownFile(uri) {
371                         return view, nil
372                 }
373         }
374         // TODO: are there any more heuristics we can use?
375         return s.views[0], nil
376 }
377
378 func (s *Session) removeView(ctx context.Context, view *View) error {
379         s.viewMu.Lock()
380         defer s.viewMu.Unlock()
381         i, err := s.dropView(ctx, view)
382         if err != nil {
383                 return err
384         }
385         // delete this view... we don't care about order but we do want to make
386         // sure we can garbage collect the view
387         s.views[i] = s.views[len(s.views)-1]
388         s.views[len(s.views)-1] = nil
389         s.views = s.views[:len(s.views)-1]
390         return nil
391 }
392
393 func (s *Session) updateView(ctx context.Context, view *View, options *source.Options) (*View, error) {
394         s.viewMu.Lock()
395         defer s.viewMu.Unlock()
396         i, err := s.dropView(ctx, view)
397         if err != nil {
398                 return nil, err
399         }
400         // Preserve the snapshot ID if we are recreating the view.
401         view.snapshotMu.Lock()
402         snapshotID := view.snapshot.id
403         view.snapshotMu.Unlock()
404         v, _, release, err := s.createView(ctx, view.name, view.folder, options, snapshotID)
405         release()
406         if err != nil {
407                 // we have dropped the old view, but could not create the new one
408                 // this should not happen and is very bad, but we still need to clean
409                 // up the view array if it happens
410                 s.views[i] = s.views[len(s.views)-1]
411                 s.views[len(s.views)-1] = nil
412                 s.views = s.views[:len(s.views)-1]
413                 return nil, err
414         }
415         // substitute the new view into the array where the old view was
416         s.views[i] = v
417         return v, nil
418 }
419
420 func (s *Session) dropView(ctx context.Context, v *View) (int, error) {
421         // we always need to drop the view map
422         s.viewMap = make(map[span.URI]*View)
423         for i := range s.views {
424                 if v == s.views[i] {
425                         // we found the view, drop it and return the index it was found at
426                         s.views[i] = nil
427                         v.shutdown(ctx)
428                         return i, nil
429                 }
430         }
431         return -1, errors.Errorf("view %s for %v not found", v.Name(), v.Folder())
432 }
433
434 func (s *Session) ModifyFiles(ctx context.Context, changes []source.FileModification) error {
435         _, _, releases, _, err := s.DidModifyFiles(ctx, changes)
436         for _, release := range releases {
437                 release()
438         }
439         return err
440 }
441
442 func (s *Session) DidModifyFiles(ctx context.Context, changes []source.FileModification) (map[span.URI]source.View, map[source.View]source.Snapshot, []func(), []span.URI, error) {
443         views := make(map[*View]map[span.URI]source.VersionedFileHandle)
444         bestViews := map[span.URI]source.View{}
445         // Keep track of deleted files so that we can clear their diagnostics.
446         // A file might be re-created after deletion, so only mark files that
447         // have truly been deleted.
448         deletions := map[span.URI]struct{}{}
449
450         overlays, err := s.updateOverlays(ctx, changes)
451         if err != nil {
452                 return nil, nil, nil, nil, err
453         }
454         var forceReloadMetadata bool
455         for _, c := range changes {
456                 if c.Action == source.InvalidateMetadata {
457                         forceReloadMetadata = true
458                 }
459
460                 // Build the list of affected views.
461                 bestView, err := s.viewOf(c.URI)
462                 if err != nil {
463                         return nil, nil, nil, nil, err
464                 }
465                 bestViews[c.URI] = bestView
466
467                 var changedViews []*View
468                 for _, view := range s.views {
469                         // Don't propagate changes that are outside of the view's scope
470                         // or knowledge.
471                         if !view.relevantChange(c) {
472                                 continue
473                         }
474                         changedViews = append(changedViews, view)
475                 }
476                 // If no view matched the change, assign it to the best view.
477                 if len(changedViews) == 0 {
478                         changedViews = append(changedViews, bestView)
479                 }
480
481                 // Apply the changes to all affected views.
482                 for _, view := range changedViews {
483                         // Make sure that the file is added to the view.
484                         if _, err := view.getFile(c.URI); err != nil {
485                                 return nil, nil, nil, nil, err
486                         }
487                         if _, ok := views[view]; !ok {
488                                 views[view] = make(map[span.URI]source.VersionedFileHandle)
489                         }
490                         var (
491                                 fh source.VersionedFileHandle
492                                 ok bool
493                         )
494                         if fh, ok = overlays[c.URI]; ok {
495                                 views[view][c.URI] = fh
496                                 delete(deletions, c.URI)
497                         } else {
498                                 fsFile, err := s.cache.getFile(ctx, c.URI)
499                                 if err != nil {
500                                         return nil, nil, nil, nil, err
501                                 }
502                                 fh = &closedFile{fsFile}
503                                 views[view][c.URI] = fh
504                                 if _, err := fh.Read(); err != nil {
505                                         deletions[c.URI] = struct{}{}
506                                 }
507                         }
508                 }
509         }
510
511         snapshots := map[source.View]source.Snapshot{}
512         var releases []func()
513         for view, uris := range views {
514                 snapshot, release := view.invalidateContent(ctx, uris, forceReloadMetadata)
515                 snapshots[view] = snapshot
516                 releases = append(releases, release)
517         }
518         var deletionsSlice []span.URI
519         for uri := range deletions {
520                 deletionsSlice = append(deletionsSlice, uri)
521         }
522         return bestViews, snapshots, releases, deletionsSlice, nil
523 }
524
525 func (s *Session) updateOverlays(ctx context.Context, changes []source.FileModification) (map[span.URI]*overlay, error) {
526         s.overlayMu.Lock()
527         defer s.overlayMu.Unlock()
528
529         for _, c := range changes {
530                 // Don't update overlays for metadata invalidations.
531                 if c.Action == source.InvalidateMetadata {
532                         continue
533                 }
534
535                 o, ok := s.overlays[c.URI]
536
537                 // If the file is not opened in an overlay and the change is on disk,
538                 // there's no need to update an overlay. If there is an overlay, we
539                 // may need to update the overlay's saved value.
540                 if !ok && c.OnDisk {
541                         continue
542                 }
543
544                 // Determine the file kind on open, otherwise, assume it has been cached.
545                 var kind source.FileKind
546                 switch c.Action {
547                 case source.Open:
548                         kind = source.DetectLanguage(c.LanguageID, c.URI.Filename())
549                 default:
550                         if !ok {
551                                 return nil, errors.Errorf("updateOverlays: modifying unopened overlay %v", c.URI)
552                         }
553                         kind = o.kind
554                 }
555                 if kind == source.UnknownKind {
556                         return nil, errors.Errorf("updateOverlays: unknown file kind for %s", c.URI)
557                 }
558
559                 // Closing a file just deletes its overlay.
560                 if c.Action == source.Close {
561                         delete(s.overlays, c.URI)
562                         continue
563                 }
564
565                 // If the file is on disk, check if its content is the same as in the
566                 // overlay. Saves and on-disk file changes don't come with the file's
567                 // content.
568                 text := c.Text
569                 if text == nil && (c.Action == source.Save || c.OnDisk) {
570                         if !ok {
571                                 return nil, fmt.Errorf("no known content for overlay for %s", c.Action)
572                         }
573                         text = o.text
574                 }
575                 // On-disk changes don't come with versions.
576                 version := c.Version
577                 if c.OnDisk {
578                         version = o.version
579                 }
580                 hash := hashContents(text)
581                 var sameContentOnDisk bool
582                 switch c.Action {
583                 case source.Delete:
584                         // Do nothing. sameContentOnDisk should be false.
585                 case source.Save:
586                         // Make sure the version and content (if present) is the same.
587                         if o.version != version {
588                                 return nil, errors.Errorf("updateOverlays: saving %s at version %v, currently at %v", c.URI, c.Version, o.version)
589                         }
590                         if c.Text != nil && o.hash != hash {
591                                 return nil, errors.Errorf("updateOverlays: overlay %s changed on save", c.URI)
592                         }
593                         sameContentOnDisk = true
594                 default:
595                         fh, err := s.cache.getFile(ctx, c.URI)
596                         if err != nil {
597                                 return nil, err
598                         }
599                         _, readErr := fh.Read()
600                         sameContentOnDisk = (readErr == nil && fh.FileIdentity().Hash == hash)
601                 }
602                 o = &overlay{
603                         session: s,
604                         uri:     c.URI,
605                         version: version,
606                         text:    text,
607                         kind:    kind,
608                         hash:    hash,
609                         saved:   sameContentOnDisk,
610                 }
611                 s.overlays[c.URI] = o
612         }
613
614         // Get the overlays for each change while the session's overlay map is
615         // locked.
616         overlays := make(map[span.URI]*overlay)
617         for _, c := range changes {
618                 if o, ok := s.overlays[c.URI]; ok {
619                         overlays[c.URI] = o
620                 }
621         }
622         return overlays, nil
623 }
624
625 func (s *Session) GetFile(ctx context.Context, uri span.URI) (source.FileHandle, error) {
626         if overlay := s.readOverlay(uri); overlay != nil {
627                 return overlay, nil
628         }
629         // Fall back to the cache-level file system.
630         return s.cache.getFile(ctx, uri)
631 }
632
633 func (s *Session) readOverlay(uri span.URI) *overlay {
634         s.overlayMu.Lock()
635         defer s.overlayMu.Unlock()
636
637         if overlay, ok := s.overlays[uri]; ok {
638                 return overlay
639         }
640         return nil
641 }
642
643 func (s *Session) Overlays() []source.Overlay {
644         s.overlayMu.Lock()
645         defer s.overlayMu.Unlock()
646
647         overlays := make([]source.Overlay, 0, len(s.overlays))
648         for _, overlay := range s.overlays {
649                 overlays = append(overlays, overlay)
650         }
651         return overlays
652 }