.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.1.1-0.20210319172145-bda8f5cee399 / 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/log"
18         "golang.org/x/tools/internal/lsp/debug/tag"
19         "golang.org/x/tools/internal/lsp/mod"
20         "golang.org/x/tools/internal/lsp/protocol"
21         "golang.org/x/tools/internal/lsp/source"
22         "golang.org/x/tools/internal/span"
23         "golang.org/x/tools/internal/xcontext"
24         errors "golang.org/x/xerrors"
25 )
26
27 // diagnosticSource differentiates different sources of diagnostics.
28 type diagnosticSource int
29
30 const (
31         modSource diagnosticSource = iota
32         gcDetailsSource
33         analysisSource
34         typeCheckSource
35         orphanedSource
36 )
37
38 // A diagnosticReport holds results for a single diagnostic source.
39 type diagnosticReport struct {
40         snapshotID    uint64
41         publishedHash string
42         diags         map[string]*source.Diagnostic
43 }
44
45 // fileReports holds a collection of diagnostic reports for a single file, as
46 // well as the hash of the last published set of diagnostics.
47 type fileReports struct {
48         snapshotID    uint64
49         publishedHash string
50         reports       map[diagnosticSource]diagnosticReport
51 }
52
53 func (d diagnosticSource) String() string {
54         switch d {
55         case modSource:
56                 return "FromSource"
57         case gcDetailsSource:
58                 return "FromGCDetails"
59         case analysisSource:
60                 return "FromAnalysis"
61         case typeCheckSource:
62                 return "FromTypeChecking"
63         case orphanedSource:
64                 return "FromOrphans"
65         default:
66                 return fmt.Sprintf("From?%d?", d)
67         }
68 }
69
70 // hashDiagnostics computes a hash to identify diags.
71 func hashDiagnostics(diags ...*source.Diagnostic) string {
72         source.SortDiagnostics(diags)
73         h := sha256.New()
74         for _, d := range diags {
75                 for _, t := range d.Tags {
76                         fmt.Fprintf(h, "%s", t)
77                 }
78                 for _, r := range d.Related {
79                         fmt.Fprintf(h, "%s%s%s", r.URI, r.Message, r.Range)
80                 }
81                 fmt.Fprintf(h, "%s%s%s%s", d.Message, d.Range, d.Severity, d.Source)
82         }
83         return fmt.Sprintf("%x", h.Sum(nil))
84 }
85
86 func (s *Server) diagnoseDetached(snapshot source.Snapshot) {
87         ctx := snapshot.BackgroundContext()
88         ctx = xcontext.Detach(ctx)
89         s.diagnose(ctx, snapshot, false)
90         s.publishDiagnostics(ctx, true, snapshot)
91 }
92
93 func (s *Server) diagnoseSnapshot(snapshot source.Snapshot, changedURIs []span.URI, onDisk bool) {
94         ctx := snapshot.BackgroundContext()
95         ctx, done := event.Start(ctx, "Server.diagnoseSnapshot", tag.Snapshot.Of(snapshot.ID()))
96         defer done()
97
98         delay := snapshot.View().Options().ExperimentalDiagnosticsDelay
99         if delay > 0 {
100                 // Experimental 2-phase diagnostics.
101                 //
102                 // The first phase just parses and checks packages that have been
103                 // affected by file modifications (no analysis).
104                 //
105                 // The second phase does everything, and is debounced by the configured
106                 // delay.
107                 s.diagnoseChangedFiles(ctx, snapshot, changedURIs, onDisk)
108                 s.publishDiagnostics(ctx, false, snapshot)
109                 s.debouncer.debounce(snapshot.View().Name(), snapshot.ID(), delay, func() {
110                         s.diagnose(ctx, snapshot, false)
111                         s.publishDiagnostics(ctx, true, snapshot)
112                 })
113                 return
114         }
115
116         // Ignore possible workspace configuration warnings in the normal flow.
117         s.diagnose(ctx, snapshot, false)
118         s.publishDiagnostics(ctx, true, snapshot)
119 }
120
121 func (s *Server) diagnoseChangedFiles(ctx context.Context, snapshot source.Snapshot, uris []span.URI, onDisk bool) {
122         ctx, done := event.Start(ctx, "Server.diagnoseChangedFiles", tag.Snapshot.Of(snapshot.ID()))
123         defer done()
124         packages := make(map[source.Package]struct{})
125         for _, uri := range uris {
126                 // If the change is only on-disk and the file is not open, don't
127                 // directly request its package. It may not be a workspace package.
128                 if onDisk && !snapshot.IsOpen(uri) {
129                         continue
130                 }
131                 // If the file is not known to the snapshot (e.g., if it was deleted),
132                 // don't diagnose it.
133                 if snapshot.FindFile(uri) == nil {
134                         continue
135                 }
136                 pkgs, err := snapshot.PackagesForFile(ctx, uri, source.TypecheckFull)
137                 if err != nil {
138                         // TODO (findleyr): we should probably do something with the error here,
139                         // but as of now this can fail repeatedly if load fails, so can be too
140                         // noisy to log (and we'll handle things later in the slow pass).
141                         continue
142                 }
143                 for _, pkg := range pkgs {
144                         packages[pkg] = struct{}{}
145                 }
146         }
147         var wg sync.WaitGroup
148         for pkg := range packages {
149                 wg.Add(1)
150
151                 go func(pkg source.Package) {
152                         defer wg.Done()
153
154                         s.diagnosePkg(ctx, snapshot, pkg, false)
155                 }(pkg)
156         }
157         wg.Wait()
158 }
159
160 // diagnose is a helper function for running diagnostics with a given context.
161 // Do not call it directly. forceAnalysis is only true for testing purposes.
162 func (s *Server) diagnose(ctx context.Context, snapshot source.Snapshot, forceAnalysis bool) {
163         ctx, done := event.Start(ctx, "Server.diagnose", tag.Snapshot.Of(snapshot.ID()))
164         defer done()
165
166         // Wait for a free diagnostics slot.
167         select {
168         case <-ctx.Done():
169                 return
170         case s.diagnosticsSema <- struct{}{}:
171         }
172         defer func() {
173                 <-s.diagnosticsSema
174         }()
175
176         // First, diagnose the go.mod file.
177         modReports, modErr := mod.Diagnostics(ctx, snapshot)
178         if ctx.Err() != nil {
179                 log.Trace.Log(ctx, "diagnose cancelled")
180                 return
181         }
182         if modErr != nil {
183                 event.Error(ctx, "warning: diagnose go.mod", modErr, tag.Directory.Of(snapshot.View().Folder().Filename()), tag.Snapshot.Of(snapshot.ID()))
184         }
185         for id, diags := range modReports {
186                 if id.URI == "" {
187                         event.Error(ctx, "missing URI for module diagnostics", fmt.Errorf("empty URI"), tag.Directory.Of(snapshot.View().Folder().Filename()))
188                         continue
189                 }
190                 s.storeDiagnostics(snapshot, id.URI, modSource, diags)
191         }
192
193         // Diagnose all of the packages in the workspace.
194         wsPkgs, err := snapshot.WorkspacePackages(ctx)
195         if s.shouldIgnoreError(ctx, snapshot, err) {
196                 return
197         }
198         criticalErr := snapshot.GetCriticalError(ctx)
199
200         // Show the error as a progress error report so that it appears in the
201         // status bar. If a client doesn't support progress reports, the error
202         // will still be shown as a ShowMessage. If there is no error, any running
203         // error progress reports will be closed.
204         s.showCriticalErrorStatus(ctx, snapshot, criticalErr)
205
206         // If there are no workspace packages, there is nothing to diagnose and
207         // there are no orphaned files.
208         if len(wsPkgs) == 0 {
209                 return
210         }
211
212         var (
213                 wg   sync.WaitGroup
214                 seen = map[span.URI]struct{}{}
215         )
216         for _, pkg := range wsPkgs {
217                 wg.Add(1)
218
219                 for _, pgf := range pkg.CompiledGoFiles() {
220                         seen[pgf.URI] = struct{}{}
221                 }
222
223                 go func(pkg source.Package) {
224                         defer wg.Done()
225
226                         s.diagnosePkg(ctx, snapshot, pkg, forceAnalysis)
227                 }(pkg)
228         }
229         wg.Wait()
230
231         // Confirm that every opened file belongs to a package (if any exist in
232         // the workspace). Otherwise, add a diagnostic to the file.
233         for _, o := range s.session.Overlays() {
234                 if _, ok := seen[o.URI()]; ok {
235                         continue
236                 }
237                 diagnostic := s.checkForOrphanedFile(ctx, snapshot, o)
238                 if diagnostic == nil {
239                         continue
240                 }
241                 s.storeDiagnostics(snapshot, o.URI(), orphanedSource, []*source.Diagnostic{diagnostic})
242         }
243 }
244
245 func (s *Server) diagnosePkg(ctx context.Context, snapshot source.Snapshot, pkg source.Package, alwaysAnalyze bool) {
246         ctx, done := event.Start(ctx, "Server.diagnosePkg", tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
247         defer done()
248         enableDiagnostics := false
249         includeAnalysis := alwaysAnalyze // only run analyses for packages with open files
250         for _, pgf := range pkg.CompiledGoFiles() {
251                 enableDiagnostics = enableDiagnostics || !snapshot.IgnoredFile(pgf.URI)
252                 includeAnalysis = includeAnalysis || snapshot.IsOpen(pgf.URI)
253         }
254         // Don't show any diagnostics on ignored files.
255         if !enableDiagnostics {
256                 return
257         }
258
259         pkgDiagnostics, err := snapshot.DiagnosePackage(ctx, pkg)
260         if err != nil {
261                 event.Error(ctx, "warning: diagnosing package", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
262                 return
263         }
264         for _, cgf := range pkg.CompiledGoFiles() {
265                 s.storeDiagnostics(snapshot, cgf.URI, typeCheckSource, pkgDiagnostics[cgf.URI])
266         }
267         if includeAnalysis && !pkg.HasListOrParseErrors() {
268                 reports, err := source.Analyze(ctx, snapshot, pkg, false)
269                 if err != nil {
270                         event.Error(ctx, "warning: analyzing package", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
271                         return
272                 }
273                 for _, cgf := range pkg.CompiledGoFiles() {
274                         s.storeDiagnostics(snapshot, cgf.URI, analysisSource, reports[cgf.URI])
275                 }
276         }
277
278         // If gc optimization details are requested, add them to the
279         // diagnostic reports.
280         s.gcOptimizationDetailsMu.Lock()
281         _, enableGCDetails := s.gcOptimizationDetails[pkg.ID()]
282         s.gcOptimizationDetailsMu.Unlock()
283         if enableGCDetails {
284                 gcReports, err := source.GCOptimizationDetails(ctx, snapshot, pkg)
285                 if err != nil {
286                         event.Error(ctx, "warning: gc details", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
287                 }
288                 for id, diags := range gcReports {
289                         fh := snapshot.FindFile(id.URI)
290                         // Don't publish gc details for unsaved buffers, since the underlying
291                         // logic operates on the file on disk.
292                         if fh == nil || !fh.Saved() {
293                                 continue
294                         }
295                         s.storeDiagnostics(snapshot, id.URI, gcDetailsSource, diags)
296                 }
297         }
298 }
299
300 // storeDiagnostics stores results from a single diagnostic source. If merge is
301 // true, it merges results into any existing results for this snapshot.
302 func (s *Server) storeDiagnostics(snapshot source.Snapshot, uri span.URI, dsource diagnosticSource, diags []*source.Diagnostic) {
303         // Safeguard: ensure that the file actually exists in the snapshot
304         // (see golang.org/issues/38602).
305         fh := snapshot.FindFile(uri)
306         if fh == nil {
307                 return
308         }
309         s.diagnosticsMu.Lock()
310         defer s.diagnosticsMu.Unlock()
311         if s.diagnostics[uri] == nil {
312                 s.diagnostics[uri] = &fileReports{
313                         publishedHash: hashDiagnostics(), // Hash for 0 diagnostics.
314                         reports:       map[diagnosticSource]diagnosticReport{},
315                 }
316         }
317         report := s.diagnostics[uri].reports[dsource]
318         // Don't set obsolete diagnostics.
319         if report.snapshotID > snapshot.ID() {
320                 return
321         }
322         if report.diags == nil || report.snapshotID != snapshot.ID() {
323                 report.diags = map[string]*source.Diagnostic{}
324         }
325         report.snapshotID = snapshot.ID()
326         for _, d := range diags {
327                 report.diags[hashDiagnostics(d)] = d
328         }
329         s.diagnostics[uri].reports[dsource] = report
330 }
331
332 // clearDiagnosticSource clears all diagnostics for a given source type. It is
333 // necessary for cases where diagnostics have been invalidated by something
334 // other than a snapshot change, for example when gc_details is toggled.
335 func (s *Server) clearDiagnosticSource(dsource diagnosticSource) {
336         s.diagnosticsMu.Lock()
337         defer s.diagnosticsMu.Unlock()
338         for _, reports := range s.diagnostics {
339                 delete(reports.reports, dsource)
340         }
341 }
342
343 const WorkspaceLoadFailure = "Error loading workspace"
344
345 // showCriticalErrorStatus shows the error as a progress report.
346 // If the error is nil, it clears any existing error progress report.
347 func (s *Server) showCriticalErrorStatus(ctx context.Context, snapshot source.Snapshot, err *source.CriticalError) {
348         s.criticalErrorStatusMu.Lock()
349         defer s.criticalErrorStatusMu.Unlock()
350
351         // Remove all newlines so that the error message can be formatted in a
352         // status bar.
353         var errMsg string
354         if err != nil {
355                 event.Error(ctx, "errors loading workspace", err.MainError, tag.Snapshot.Of(snapshot.ID()), tag.Directory.Of(snapshot.View().Folder()))
356                 for _, d := range err.DiagList {
357                         s.storeDiagnostics(snapshot, d.URI, modSource, []*source.Diagnostic{d})
358                 }
359                 errMsg = strings.Replace(err.MainError.Error(), "\n", " ", -1)
360         }
361
362         if s.criticalErrorStatus == nil {
363                 if errMsg != "" {
364                         s.criticalErrorStatus = s.progress.start(ctx, WorkspaceLoadFailure, errMsg, nil, nil)
365                 }
366                 return
367         }
368
369         // If an error is already shown to the user, update it or mark it as
370         // resolved.
371         if errMsg == "" {
372                 s.criticalErrorStatus.end("Done.")
373                 s.criticalErrorStatus = nil
374         } else {
375                 s.criticalErrorStatus.report(errMsg, 0)
376         }
377 }
378
379 // checkForOrphanedFile checks that the given URIs can be mapped to packages.
380 // If they cannot and the workspace is not otherwise unloaded, it also surfaces
381 // a warning, suggesting that the user check the file for build tags.
382 func (s *Server) checkForOrphanedFile(ctx context.Context, snapshot source.Snapshot, fh source.VersionedFileHandle) *source.Diagnostic {
383         if fh.Kind() != source.Go {
384                 return nil
385         }
386         pkgs, err := snapshot.PackagesForFile(ctx, fh.URI(), source.TypecheckWorkspace)
387         if len(pkgs) > 0 || err == nil {
388                 return nil
389         }
390         pgf, err := snapshot.ParseGo(ctx, fh, source.ParseHeader)
391         if err != nil {
392                 return nil
393         }
394         spn, err := span.NewRange(snapshot.FileSet(), pgf.File.Name.Pos(), pgf.File.Name.End()).Span()
395         if err != nil {
396                 return nil
397         }
398         rng, err := pgf.Mapper.Range(spn)
399         if err != nil {
400                 return nil
401         }
402         // TODO(rstambler): We should be able to parse the build tags in the
403         // file and show a more specific error message. For now, put the diagnostic
404         // on the package declaration.
405         return &source.Diagnostic{
406                 URI:      fh.URI(),
407                 Range:    rng,
408                 Severity: protocol.SeverityWarning,
409                 Source:   source.ListError,
410                 Message: fmt.Sprintf(`No packages found for open file %s: %v.
411 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).
412 Otherwise, see the troubleshooting guidelines for help investigating (https://github.com/golang/tools/blob/master/gopls/doc/troubleshooting.md).
413 `, fh.URI().Filename(), err),
414         }
415 }
416
417 // publishDiagnostics collects and publishes any unpublished diagnostic reports.
418 func (s *Server) publishDiagnostics(ctx context.Context, final bool, snapshot source.Snapshot) {
419         ctx, done := event.Start(ctx, "Server.publishDiagnostics", tag.Snapshot.Of(snapshot.ID()))
420         defer done()
421         s.diagnosticsMu.Lock()
422         defer s.diagnosticsMu.Unlock()
423
424         published := 0
425         defer func() {
426                 log.Trace.Logf(ctx, "published %d diagnostics", published)
427         }()
428
429         for uri, r := range s.diagnostics {
430                 // Snapshot IDs are always increasing, so we use them instead of file
431                 // versions to create the correct order for diagnostics.
432
433                 // If we've already delivered diagnostics for a future snapshot for this
434                 // file, do not deliver them.
435                 if r.snapshotID > snapshot.ID() {
436                         continue
437                 }
438                 anyReportsChanged := false
439                 reportHashes := map[diagnosticSource]string{}
440                 var diags []*source.Diagnostic
441                 for dsource, report := range r.reports {
442                         if report.snapshotID != snapshot.ID() {
443                                 continue
444                         }
445                         var reportDiags []*source.Diagnostic
446                         for _, d := range report.diags {
447                                 diags = append(diags, d)
448                                 reportDiags = append(reportDiags, d)
449                         }
450                         hash := hashDiagnostics(reportDiags...)
451                         if hash != report.publishedHash {
452                                 anyReportsChanged = true
453                         }
454                         reportHashes[dsource] = hash
455                 }
456
457                 if !final && !anyReportsChanged {
458                         // Don't invalidate existing reports on the client if we haven't got any
459                         // new information.
460                         continue
461                 }
462                 source.SortDiagnostics(diags)
463                 hash := hashDiagnostics(diags...)
464                 if hash == r.publishedHash {
465                         // Update snapshotID to be the latest snapshot for which this diagnostic
466                         // hash is valid.
467                         r.snapshotID = snapshot.ID()
468                         continue
469                 }
470                 var version int32
471                 if fh := snapshot.FindFile(uri); fh != nil { // file may have been deleted
472                         version = fh.Version()
473                 }
474                 if err := s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{
475                         Diagnostics: toProtocolDiagnostics(diags),
476                         URI:         protocol.URIFromSpanURI(uri),
477                         Version:     version,
478                 }); err == nil {
479                         published++
480                         r.publishedHash = hash
481                         r.snapshotID = snapshot.ID()
482                         for dsource, hash := range reportHashes {
483                                 report := r.reports[dsource]
484                                 report.publishedHash = hash
485                                 r.reports[dsource] = report
486                         }
487                 } else {
488                         if ctx.Err() != nil {
489                                 // Publish may have failed due to a cancelled context.
490                                 log.Trace.Log(ctx, "publish cancelled")
491                                 return
492                         }
493                         event.Error(ctx, "publishReports: failed to deliver diagnostic", err, tag.URI.Of(uri))
494                 }
495         }
496 }
497
498 func toProtocolDiagnostics(diagnostics []*source.Diagnostic) []protocol.Diagnostic {
499         reports := []protocol.Diagnostic{}
500         for _, diag := range diagnostics {
501                 related := make([]protocol.DiagnosticRelatedInformation, 0, len(diag.Related))
502                 for _, rel := range diag.Related {
503                         related = append(related, protocol.DiagnosticRelatedInformation{
504                                 Location: protocol.Location{
505                                         URI:   protocol.URIFromSpanURI(rel.URI),
506                                         Range: rel.Range,
507                                 },
508                                 Message: rel.Message,
509                         })
510                 }
511                 pdiag := protocol.Diagnostic{
512                         // diag.Message might start with \n or \t
513                         Message:            strings.TrimSpace(diag.Message),
514                         Range:              diag.Range,
515                         Severity:           diag.Severity,
516                         Source:             string(diag.Source),
517                         Tags:               diag.Tags,
518                         RelatedInformation: related,
519                 }
520                 if diag.Code != "" {
521                         pdiag.Code = diag.Code
522                 }
523                 if diag.CodeHref != "" {
524                         pdiag.CodeDescription = &protocol.CodeDescription{Href: diag.CodeHref}
525                 }
526                 reports = append(reports, pdiag)
527         }
528         return reports
529 }
530
531 func (s *Server) shouldIgnoreError(ctx context.Context, snapshot source.Snapshot, err error) bool {
532         if err == nil { // if there is no error at all
533                 return false
534         }
535         if errors.Is(err, context.Canceled) {
536                 return true
537         }
538         // If the folder has no Go code in it, we shouldn't spam the user with a warning.
539         var hasGo bool
540         _ = filepath.Walk(snapshot.View().Folder().Filename(), func(path string, info os.FileInfo, err error) error {
541                 if err != nil {
542                         return err
543                 }
544                 if !strings.HasSuffix(info.Name(), ".go") {
545                         return nil
546                 }
547                 hasGo = true
548                 return errors.New("done")
549         })
550         return !hasGo
551 }
552
553 // Diagnostics formattedfor the debug server
554 // (all the relevant fields of Server are private)
555 // (The alternative is to export them)
556 func (s *Server) Diagnostics() map[string][]string {
557         ans := make(map[string][]string)
558         s.diagnosticsMu.Lock()
559         defer s.diagnosticsMu.Unlock()
560         for k, v := range s.diagnostics {
561                 fn := k.Filename()
562                 for typ, d := range v.reports {
563                         if len(d.diags) == 0 {
564                                 continue
565                         }
566                         for _, dx := range d.diags {
567                                 ans[fn] = append(ans[fn], auxStr(dx, d, typ))
568                         }
569                 }
570         }
571         return ans
572 }
573
574 func auxStr(v *source.Diagnostic, d diagnosticReport, typ diagnosticSource) string {
575         // Tags? RelatedInformation?
576         msg := fmt.Sprintf("(%s)%q(source:%q,code:%q,severity:%s,snapshot:%d,type:%s)",
577                 v.Range, v.Message, v.Source, v.Code, v.Severity, d.snapshotID, typ)
578         for _, r := range v.Related {
579                 msg += fmt.Sprintf(" [%s:%s,%q]", r.URI.Filename(), r.Range, r.Message)
580         }
581         return msg
582 }