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