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