Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201105173854-bc9fc8d8c4bc / internal / lsp / diagnostics.go
1 // Copyright 2018 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 lsp
6
7 import (
8         "context"
9         "crypto/sha256"
10         "fmt"
11         "os"
12         "path/filepath"
13         "strings"
14         "sync"
15
16         "golang.org/x/tools/internal/event"
17         "golang.org/x/tools/internal/lsp/debug/tag"
18         "golang.org/x/tools/internal/lsp/mod"
19         "golang.org/x/tools/internal/lsp/protocol"
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 // idWithAnalysis is used to track if the diagnostics for a given file were
27 // computed with analyses.
28 type idWithAnalysis struct {
29         id              source.VersionedFileIdentity
30         includeAnalysis bool
31 }
32
33 // A reportSet collects diagnostics for publication, sorting them by file and
34 // de-duplicating.
35 type reportSet struct {
36         mu sync.Mutex
37         // lazily allocated
38         reports map[idWithAnalysis]map[string]*source.Diagnostic
39 }
40
41 func (s *reportSet) add(id source.VersionedFileIdentity, includeAnalysis bool, diags ...*source.Diagnostic) {
42         s.mu.Lock()
43         defer s.mu.Unlock()
44         if s.reports == nil {
45                 s.reports = make(map[idWithAnalysis]map[string]*source.Diagnostic)
46         }
47         key := idWithAnalysis{
48                 id:              id,
49                 includeAnalysis: includeAnalysis,
50         }
51         if _, ok := s.reports[key]; !ok {
52                 s.reports[key] = map[string]*source.Diagnostic{}
53         }
54         for _, d := range diags {
55                 s.reports[key][diagnosticKey(d)] = d
56         }
57 }
58
59 // diagnosticKey creates a unique identifier for a given diagnostic, since we
60 // cannot use source.Diagnostics as map keys. This is used to de-duplicate
61 // diagnostics.
62 func diagnosticKey(d *source.Diagnostic) string {
63         var tags, related string
64         for _, t := range d.Tags {
65                 tags += fmt.Sprintf("%s", t)
66         }
67         for _, r := range d.Related {
68                 related += fmt.Sprintf("%s%s%s", r.URI, r.Message, r.Range)
69         }
70         key := fmt.Sprintf("%s%s%s%s%s%s", d.Message, d.Range, d.Severity, d.Source, tags, related)
71         return fmt.Sprintf("%x", sha256.Sum256([]byte(key)))
72 }
73
74 func (s *Server) diagnoseDetached(snapshot source.Snapshot) {
75         ctx := snapshot.View().BackgroundContext()
76         ctx = xcontext.Detach(ctx)
77         reports, shows := s.diagnose(ctx, snapshot, false)
78         if shows != nil {
79                 // If a view has been created or the configuration changed, warn the user.
80                 s.client.ShowMessage(ctx, shows)
81         }
82         s.publishReports(ctx, snapshot, reports, false)
83 }
84
85 func (s *Server) diagnoseSnapshot(snapshot source.Snapshot, changedURIs []span.URI) {
86         ctx := snapshot.View().BackgroundContext()
87
88         delay := snapshot.View().Options().ExperimentalDiagnosticsDelay
89         if delay > 0 {
90                 // Experimental 2-phase diagnostics.
91                 //
92                 // The first phase just parses and checks packages that have been affected
93                 // by file modifications (no analysis).
94                 //
95                 // The second phase does everything, and is debounced by the configured delay.
96                 reports, err := s.diagnoseChangedFiles(ctx, snapshot, changedURIs)
97                 if err != nil {
98                         if !errors.Is(err, context.Canceled) {
99                                 event.Error(ctx, "diagnosing changed files", err)
100                         }
101                 }
102                 s.publishReports(ctx, snapshot, reports, true)
103                 s.debouncer.debounce(snapshot.View().Name(), snapshot.ID(), delay, func() {
104                         reports, _ := s.diagnose(ctx, snapshot, false)
105                         s.publishReports(ctx, snapshot, reports, false)
106                 })
107                 return
108         }
109
110         // Ignore possible workspace configuration warnings in the normal flow.
111         reports, _ := s.diagnose(ctx, snapshot, false)
112         s.publishReports(ctx, snapshot, reports, false)
113 }
114
115 func (s *Server) diagnoseChangedFiles(ctx context.Context, snapshot source.Snapshot, uris []span.URI) (*reportSet, error) {
116         ctx, done := event.Start(ctx, "Server.diagnoseChangedFiles")
117         defer done()
118         packages := make(map[source.Package]struct{})
119         for _, uri := range uris {
120                 pkgs, err := snapshot.PackagesForFile(ctx, uri, source.TypecheckWorkspace)
121                 if err != nil {
122                         // TODO (rFindley): we should probably do something with the error here,
123                         // but as of now this can fail repeatedly if load fails, so can be too
124                         // noisy to log (and we'll handle things later in the slow pass).
125                         continue
126                 }
127                 for _, pkg := range pkgs {
128                         packages[pkg] = struct{}{}
129                 }
130         }
131         reports := new(reportSet)
132         for pkg := range packages {
133                 pkgReports, _, err := source.Diagnostics(ctx, snapshot, pkg, false)
134                 if err != nil {
135                         return nil, err
136                 }
137                 for id, diags := range pkgReports {
138                         reports.add(id, false, diags...)
139                 }
140         }
141         return reports, nil
142 }
143
144 // diagnose is a helper function for running diagnostics with a given context.
145 // Do not call it directly.
146 func (s *Server) diagnose(ctx context.Context, snapshot source.Snapshot, alwaysAnalyze bool) (diagReports *reportSet, _ *protocol.ShowMessageParams) {
147         ctx, done := event.Start(ctx, "Server.diagnose")
148         defer done()
149
150         // Wait for a free diagnostics slot.
151         select {
152         case <-ctx.Done():
153                 return nil, nil
154         case s.diagnosticsSema <- struct{}{}:
155         }
156         defer func() {
157                 <-s.diagnosticsSema
158         }()
159
160         reports := new(reportSet)
161
162         // First, diagnose the go.mod file.
163         modReports, modErr := mod.Diagnostics(ctx, snapshot)
164         if ctx.Err() != nil {
165                 return nil, nil
166         }
167         if modErr != nil {
168                 event.Error(ctx, "warning: diagnose go.mod", modErr, tag.Directory.Of(snapshot.View().Folder().Filename()), tag.Snapshot.Of(snapshot.ID()))
169         }
170         for id, diags := range modReports {
171                 if id.URI == "" {
172                         event.Error(ctx, "missing URI for module diagnostics", fmt.Errorf("empty URI"), tag.Directory.Of(snapshot.View().Folder().Filename()))
173                         continue
174                 }
175                 reports.add(id, true, diags...) // treat go.mod diagnostics like analyses
176         }
177
178         // Diagnose all of the packages in the workspace.
179         wsPkgs, err := snapshot.WorkspacePackages(ctx)
180         if err != nil {
181                 if errors.Is(err, context.Canceled) {
182                         return nil, nil
183                 }
184                 // Some error messages can be displayed as diagnostics.
185                 if errList := (*source.ErrorList)(nil); errors.As(err, &errList) {
186                         if err := errorsToDiagnostic(ctx, snapshot, *errList, reports); err == nil {
187                                 return reports, nil
188                         }
189                 }
190                 // Try constructing a more helpful error message out of this error.
191                 if s.handleFatalErrors(ctx, snapshot, modErr, err) {
192                         return nil, nil
193                 }
194                 event.Error(ctx, "errors diagnosing workspace", err, tag.Snapshot.Of(snapshot.ID()), tag.Directory.Of(snapshot.View().Folder()))
195                 // Present any `go list` errors directly to the user.
196                 if errors.Is(err, source.PackagesLoadError) {
197                         if err := s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
198                                 Type: protocol.Error,
199                                 Message: fmt.Sprintf(`The code in the workspace failed to compile (see the error message below).
200 If you believe this is a mistake, please file an issue: https://github.com/golang/go/issues/new.
201 %v`, err),
202                         }); err != nil {
203                                 event.Error(ctx, "ShowMessage failed", err, tag.Directory.Of(snapshot.View().Folder().Filename()))
204                         }
205                 }
206                 return nil, nil
207         }
208         var (
209                 showMsgMu sync.Mutex
210                 showMsg   *protocol.ShowMessageParams
211                 wg        sync.WaitGroup
212         )
213         for _, pkg := range wsPkgs {
214                 wg.Add(1)
215                 go func(pkg source.Package) {
216                         defer wg.Done()
217
218                         includeAnalysis := alwaysAnalyze // only run analyses for packages with open files
219                         var gcDetailsDir span.URI        // find the package's optimization details, if available
220                         for _, pgf := range pkg.CompiledGoFiles() {
221                                 if snapshot.IsOpen(pgf.URI) {
222                                         includeAnalysis = true
223                                 }
224                                 if gcDetailsDir == "" {
225                                         dirURI := span.URIFromPath(filepath.Dir(pgf.URI.Filename()))
226                                         s.gcOptimizationDetailsMu.Lock()
227                                         _, ok := s.gcOptimizationDetails[dirURI]
228                                         s.gcOptimizationDetailsMu.Unlock()
229                                         if ok {
230                                                 gcDetailsDir = dirURI
231                                         }
232                                 }
233                         }
234
235                         pkgReports, warn, err := source.Diagnostics(ctx, snapshot, pkg, includeAnalysis)
236
237                         // Check if might want to warn the user about their build configuration.
238                         // Our caller decides whether to send the message.
239                         if warn && !snapshot.ValidBuildConfiguration() {
240                                 showMsgMu.Lock()
241                                 showMsg = &protocol.ShowMessageParams{
242                                         Type:    protocol.Warning,
243                                         Message: `You are neither in a module nor in your GOPATH. If you are using modules, please open your editor to a directory in your module. If you believe this warning is incorrect, please file an issue: https://github.com/golang/go/issues/new.`,
244                                 }
245                                 showMsgMu.Unlock()
246                         }
247                         if err != nil {
248                                 event.Error(ctx, "warning: diagnose package", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
249                                 return
250                         }
251
252                         // Add all reports to the global map, checking for duplicates.
253                         for id, diags := range pkgReports {
254                                 reports.add(id, includeAnalysis, diags...)
255                         }
256                         // If gc optimization details are available, add them to the
257                         // diagnostic reports.
258                         if gcDetailsDir != "" {
259                                 gcReports, err := source.GCOptimizationDetails(ctx, snapshot, gcDetailsDir)
260                                 if err != nil {
261                                         event.Error(ctx, "warning: gc details", err, tag.Snapshot.Of(snapshot.ID()))
262                                 }
263                                 for id, diags := range gcReports {
264                                         reports.add(id, includeAnalysis, diags...)
265                                 }
266                         }
267                 }(pkg)
268         }
269         wg.Wait()
270         // Confirm that every opened file belongs to a package (if any exist in
271         // the workspace). Otherwise, add a diagnostic to the file.
272         if len(wsPkgs) > 0 {
273                 for _, o := range s.session.Overlays() {
274                         // Check if we already have diagnostic reports for the given file,
275                         // meaning that we have already seen its package.
276                         var seen bool
277                         for _, includeAnalysis := range []bool{true, false} {
278                                 _, ok := reports.reports[idWithAnalysis{
279                                         id:              o.VersionedFileIdentity(),
280                                         includeAnalysis: includeAnalysis,
281                                 }]
282                                 seen = seen || ok
283                         }
284                         if seen {
285                                 continue
286                         }
287                         diagnostic := s.checkForOrphanedFile(ctx, snapshot, o)
288                         if diagnostic == nil {
289                                 continue
290                         }
291                         reports.add(o.VersionedFileIdentity(), true, diagnostic)
292                 }
293         }
294         return reports, showMsg
295 }
296
297 // checkForOrphanedFile checks that the given URIs can be mapped to packages.
298 // If they cannot and the workspace is not otherwise unloaded, it also surfaces
299 // a warning, suggesting that the user check the file for build tags.
300 func (s *Server) checkForOrphanedFile(ctx context.Context, snapshot source.Snapshot, fh source.VersionedFileHandle) *source.Diagnostic {
301         if fh.Kind() != source.Go {
302                 return nil
303         }
304         pkgs, err := snapshot.PackagesForFile(ctx, fh.URI(), source.TypecheckWorkspace)
305         if len(pkgs) > 0 || err == nil {
306                 return nil
307         }
308         pgf, err := snapshot.ParseGo(ctx, fh, source.ParseHeader)
309         if err != nil {
310                 return nil
311         }
312         spn, err := span.NewRange(snapshot.FileSet(), pgf.File.Name.Pos(), pgf.File.Name.End()).Span()
313         if err != nil {
314                 return nil
315         }
316         rng, err := pgf.Mapper.Range(spn)
317         if err != nil {
318                 return nil
319         }
320         // TODO(rstambler): We should be able to parse the build tags in the
321         // file and show a more specific error message. For now, put the diagnostic
322         // on the package declaration.
323         return &source.Diagnostic{
324                 Range: rng,
325                 Message: fmt.Sprintf(`No packages found for open file %s: %v.
326 If this file contains build tags, try adding "-tags=<build tag>" to your gopls "buildFlag" configuration (see (https://github.com/golang/tools/blob/master/gopls/doc/settings.md#buildflags-string).
327 Otherwise, see the troubleshooting guidelines for help investigating (https://github.com/golang/tools/blob/master/gopls/doc/troubleshooting.md).
328 `, fh.URI().Filename(), err),
329                 Severity: protocol.SeverityWarning,
330                 Source:   "compiler",
331         }
332 }
333
334 func errorsToDiagnostic(ctx context.Context, snapshot source.Snapshot, errors []*source.Error, reports *reportSet) error {
335         for _, e := range errors {
336                 diagnostic := &source.Diagnostic{
337                         Range:    e.Range,
338                         Message:  e.Message,
339                         Related:  e.Related,
340                         Severity: protocol.SeverityError,
341                         Source:   e.Category,
342                 }
343                 fh, err := snapshot.GetVersionedFile(ctx, e.URI)
344                 if err != nil {
345                         return err
346                 }
347                 reports.add(fh.VersionedFileIdentity(), true, diagnostic)
348         }
349         return nil
350 }
351
352 func (s *Server) publishReports(ctx context.Context, snapshot source.Snapshot, reports *reportSet, isFirstPass bool) {
353         // Check for context cancellation before publishing diagnostics.
354         if ctx.Err() != nil || reports == nil {
355                 return
356         }
357
358         s.deliveredMu.Lock()
359         defer s.deliveredMu.Unlock()
360
361         for key, diagnosticsMap := range reports.reports {
362                 // Don't deliver diagnostics if the context has already been canceled.
363                 if ctx.Err() != nil {
364                         break
365                 }
366                 // Pre-sort diagnostics to avoid extra work when we compare them.
367                 var diagnostics []*source.Diagnostic
368                 for _, d := range diagnosticsMap {
369                         diagnostics = append(diagnostics, d)
370                 }
371                 source.SortDiagnostics(diagnostics)
372                 toSend := sentDiagnostics{
373                         id:              key.id,
374                         sorted:          diagnostics,
375                         includeAnalysis: key.includeAnalysis,
376                         snapshotID:      snapshot.ID(),
377                 }
378
379                 // We use the zero values if this is an unknown file.
380                 delivered := s.delivered[key.id.URI]
381
382                 // Snapshot IDs are always increasing, so we use them instead of file
383                 // versions to create the correct order for diagnostics.
384
385                 // If we've already delivered diagnostics for a future snapshot for
386                 // this file, do not deliver them.
387                 if delivered.snapshotID > toSend.snapshotID {
388                         // Do not update the delivered map since it already contains newer
389                         // diagnostics.
390                         continue
391                 }
392
393                 // Check if we should reuse the cached diagnostics.
394                 if equalDiagnostics(delivered.sorted, diagnostics) {
395                         // Make sure to update the delivered map.
396                         s.delivered[key.id.URI] = toSend
397                         continue
398                 }
399
400                 // If we've already delivered diagnostics for this file, at this
401                 // snapshot, with analyses, do not send diagnostics without analyses.
402                 if delivered.snapshotID == toSend.snapshotID && delivered.id == toSend.id &&
403                         delivered.includeAnalysis && !toSend.includeAnalysis {
404                         // Do not update the delivered map since it already contains better diagnostics.
405                         continue
406                 }
407
408                 // If we've previously delivered non-empty diagnostics and this is a
409                 // first diagnostic pass, wait for a subsequent pass to complete before
410                 // sending empty diagnostics to avoid flickering diagnostics.
411                 if isFirstPass && delivered.includeAnalysis && !toSend.includeAnalysis && len(toSend.sorted) == 0 {
412                         continue
413                 }
414
415                 if err := s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{
416                         Diagnostics: toProtocolDiagnostics(diagnostics),
417                         URI:         protocol.URIFromSpanURI(key.id.URI),
418                         Version:     key.id.Version,
419                 }); err != nil {
420                         event.Error(ctx, "publishReports: failed to deliver diagnostic", err, tag.URI.Of(key.id.URI))
421                         continue
422                 }
423                 // Update the delivered map.
424                 s.delivered[key.id.URI] = toSend
425         }
426 }
427
428 // equalDiagnostics returns true if the 2 lists of diagnostics are equal.
429 // It assumes that both a and b are already sorted.
430 func equalDiagnostics(a, b []*source.Diagnostic) bool {
431         if len(a) != len(b) {
432                 return false
433         }
434         for i := 0; i < len(a); i++ {
435                 if source.CompareDiagnostic(a[i], b[i]) != 0 {
436                         return false
437                 }
438         }
439         return true
440 }
441
442 func toProtocolDiagnostics(diagnostics []*source.Diagnostic) []protocol.Diagnostic {
443         reports := []protocol.Diagnostic{}
444         for _, diag := range diagnostics {
445                 related := make([]protocol.DiagnosticRelatedInformation, 0, len(diag.Related))
446                 for _, rel := range diag.Related {
447                         related = append(related, protocol.DiagnosticRelatedInformation{
448                                 Location: protocol.Location{
449                                         URI:   protocol.URIFromSpanURI(rel.URI),
450                                         Range: rel.Range,
451                                 },
452                                 Message: rel.Message,
453                         })
454                 }
455                 reports = append(reports, protocol.Diagnostic{
456                         // diag.Message might start with \n or \t
457                         Message:            strings.TrimSpace(diag.Message),
458                         Range:              diag.Range,
459                         Severity:           diag.Severity,
460                         Source:             diag.Source,
461                         Tags:               diag.Tags,
462                         RelatedInformation: related,
463                 })
464         }
465         return reports
466 }
467
468 func (s *Server) handleFatalErrors(ctx context.Context, snapshot source.Snapshot, modErr, loadErr error) bool {
469         // If the folder has no Go code in it, we shouldn't spam the user with a warning.
470         var hasGo bool
471         _ = filepath.Walk(snapshot.View().Folder().Filename(), func(path string, info os.FileInfo, err error) error {
472                 if err != nil {
473                         return err
474                 }
475                 if !strings.HasSuffix(info.Name(), ".go") {
476                         return nil
477                 }
478                 hasGo = true
479                 return errors.New("done")
480         })
481         return !hasGo
482 }