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.
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"
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
33 // A reportSet collects diagnostics for publication, sorting them by file and
35 type reportSet struct {
38 reports map[idWithAnalysis]map[string]*source.Diagnostic
41 func (s *reportSet) add(id source.VersionedFileIdentity, withAnalysis bool, diags ...*source.Diagnostic) {
45 s.reports = make(map[idWithAnalysis]map[string]*source.Diagnostic)
47 key := idWithAnalysis{
49 withAnalysis: withAnalysis,
51 if _, ok := s.reports[key]; !ok {
52 s.reports[key] = map[string]*source.Diagnostic{}
54 for _, d := range diags {
55 s.reports[key][diagnosticKey(d)] = d
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
62 func diagnosticKey(d *source.Diagnostic) string {
63 var tags, related string
64 for _, t := range d.Tags {
65 tags += fmt.Sprintf("%s", t)
67 for _, r := range d.Related {
68 related += fmt.Sprintf("%s%s%s", r.URI, r.Message, r.Range)
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)))
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)
79 // If a view has been created or the configuration changed, warn the user.
80 s.client.ShowMessage(ctx, shows)
82 s.publishReports(ctx, snapshot, reports)
85 func (s *Server) diagnoseSnapshot(snapshot source.Snapshot, changedURIs []span.URI) {
86 ctx := snapshot.View().BackgroundContext()
88 delay := snapshot.View().Options().ExperimentalDiagnosticsDelay
90 // Experimental 2-phase diagnostics.
92 // The first phase just parses and checks packages that have been affected
93 // by file modifications (no analysis).
95 // The second phase does everything, and is debounced by the configured delay.
96 reports, err := s.diagnoseChangedFiles(ctx, snapshot, changedURIs)
98 if !errors.Is(err, context.Canceled) {
99 event.Error(ctx, "diagnosing changed files", err)
102 s.publishReports(ctx, snapshot, reports)
103 s.debouncer.debounce(snapshot.View().Name(), snapshot.ID(), delay, func() {
104 reports, _ := s.diagnose(ctx, snapshot, false)
105 s.publishReports(ctx, snapshot, reports)
110 // Ignore possible workspace configuration warnings in the normal flow.
111 reports, _ := s.diagnose(ctx, snapshot, false)
112 s.publishReports(ctx, snapshot, reports)
115 func (s *Server) diagnoseChangedFiles(ctx context.Context, snapshot source.Snapshot, uris []span.URI) (*reportSet, error) {
116 ctx, done := event.Start(ctx, "Server.diagnoseChangedFiles")
118 packages := make(map[source.Package]struct{})
119 for _, uri := range uris {
120 pkgs, err := snapshot.PackagesForFile(ctx, uri, source.TypecheckWorkspace)
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).
127 for _, pkg := range pkgs {
128 packages[pkg] = struct{}{}
131 reports := new(reportSet)
132 for pkg := range packages {
133 pkgReports, _, err := source.Diagnostics(ctx, snapshot, pkg, false)
137 for id, diags := range pkgReports {
138 reports.add(id, false, diags...)
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")
150 // Wait for a free diagnostics slot.
154 case s.diagnosticsSema <- struct{}{}:
160 reports := new(reportSet)
162 // First, diagnose the go.mod file.
163 modReports, modErr := mod.Diagnostics(ctx, snapshot)
164 if ctx.Err() != nil {
168 event.Error(ctx, "warning: diagnose go.mod", modErr, tag.Directory.Of(snapshot.View().Folder().Filename()), tag.Snapshot.Of(snapshot.ID()))
170 for id, diags := range modReports {
172 event.Error(ctx, "missing URI for module diagnostics", fmt.Errorf("empty URI"), tag.Directory.Of(snapshot.View().Folder().Filename()))
175 reports.add(id, true, diags...) // treat go.mod diagnostics like analyses
178 // Diagnose all of the packages in the workspace.
179 wsPkgs, err := snapshot.WorkspacePackages(ctx)
181 if errors.Is(err, context.Canceled) {
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 {
190 // Try constructing a more helpful error message out of this error.
191 if s.handleFatalErrors(ctx, snapshot, modErr, err) {
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.
203 event.Error(ctx, "ShowMessage failed", err, tag.Directory.Of(snapshot.View().Folder().Filename()))
210 showMsg *protocol.ShowMessageParams
213 for _, pkg := range wsPkgs {
215 go func(pkg source.Package) {
218 withAnalysis := 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) {
224 if gcDetailsDir == "" {
225 dirURI := span.URIFromPath(filepath.Dir(pgf.URI.Filename()))
226 s.gcOptimizationDetailsMu.Lock()
227 _, ok := s.gcOptimizatonDetails[dirURI]
228 s.gcOptimizationDetailsMu.Unlock()
230 gcDetailsDir = dirURI
235 pkgReports, warn, err := source.Diagnostics(ctx, snapshot, pkg, withAnalysis)
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() {
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.`,
248 event.Error(ctx, "warning: diagnose package", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
252 // Add all reports to the global map, checking for duplicates.
253 for id, diags := range pkgReports {
254 reports.add(id, withAnalysis, diags...)
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)
261 event.Error(ctx, "warning: gc details", err, tag.Snapshot.Of(snapshot.ID()))
263 for id, diags := range gcReports {
264 reports.add(id, withAnalysis, diags...)
270 // Confirm that every opened file belongs to a package (if any exist in
271 // the workspace). Otherwise, add a diagnostic to the file.
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.
277 for _, withAnalysis := range []bool{true, false} {
278 _, ok := reports.reports[idWithAnalysis{
279 id: o.VersionedFileIdentity(),
280 withAnalysis: withAnalysis,
287 diagnostic := s.checkForOrphanedFile(ctx, snapshot, o)
288 if diagnostic == nil {
291 reports.add(o.VersionedFileIdentity(), true, diagnostic)
294 return reports, showMsg
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 {
304 pkgs, err := snapshot.PackagesForFile(ctx, fh.URI(), source.TypecheckWorkspace)
305 if len(pkgs) > 0 || err == nil {
308 pgf, err := snapshot.ParseGo(ctx, fh, source.ParseHeader)
312 spn, err := span.NewRange(snapshot.FileSet(), pgf.File.Name.Pos(), pgf.File.Name.End()).Span()
316 rng, err := pgf.Mapper.Range(spn)
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{
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,
334 func errorsToDiagnostic(ctx context.Context, snapshot source.Snapshot, errors []*source.Error, reports *reportSet) error {
335 for _, e := range errors {
336 diagnostic := &source.Diagnostic{
340 Severity: protocol.SeverityError,
343 fh, err := snapshot.GetVersionedFile(ctx, e.URI)
347 reports.add(fh.VersionedFileIdentity(), false, diagnostic)
352 func (s *Server) publishReports(ctx context.Context, snapshot source.Snapshot, reports *reportSet) {
353 // Check for context cancellation before publishing diagnostics.
354 if ctx.Err() != nil || reports == nil {
359 defer s.deliveredMu.Unlock()
361 for key, diagnosticsMap := range reports.reports {
362 // Don't deliver diagnostics if the context has already been canceled.
363 if ctx.Err() != nil {
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)
371 source.SortDiagnostics(diagnostics)
372 toSend := sentDiagnostics{
375 withAnalysis: key.withAnalysis,
376 snapshotID: snapshot.ID(),
379 // We use the zero values if this is an unknown file.
380 delivered := s.delivered[key.id.URI]
382 // Snapshot IDs are always increasing, so we use them instead of file
383 // versions to create the correct order for diagnostics.
385 // If we've already delivered diagnostics for a future snapshot for this file,
386 // do not deliver them.
387 if delivered.snapshotID > toSend.snapshotID {
388 // Do not update the delivered map since it already contains newer diagnostics.
392 // Check if we should reuse the cached diagnostics.
393 if equalDiagnostics(delivered.sorted, diagnostics) {
394 // Make sure to update the delivered map.
395 s.delivered[key.id.URI] = toSend
399 // If we've already delivered diagnostics for this file, at this
400 // snapshot, with analyses, do not send diagnostics without analyses.
401 if delivered.snapshotID == toSend.snapshotID && delivered.id == toSend.id &&
402 delivered.withAnalysis && !toSend.withAnalysis {
403 // Do not update the delivered map since it already contains better diagnostics.
406 if err := s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{
407 Diagnostics: toProtocolDiagnostics(diagnostics),
408 URI: protocol.URIFromSpanURI(key.id.URI),
409 Version: key.id.Version,
411 event.Error(ctx, "publishReports: failed to deliver diagnostic", err, tag.URI.Of(key.id.URI))
414 // Update the delivered map.
415 s.delivered[key.id.URI] = toSend
419 // equalDiagnostics returns true if the 2 lists of diagnostics are equal.
420 // It assumes that both a and b are already sorted.
421 func equalDiagnostics(a, b []*source.Diagnostic) bool {
422 if len(a) != len(b) {
425 for i := 0; i < len(a); i++ {
426 if source.CompareDiagnostic(a[i], b[i]) != 0 {
433 func toProtocolDiagnostics(diagnostics []*source.Diagnostic) []protocol.Diagnostic {
434 reports := []protocol.Diagnostic{}
435 for _, diag := range diagnostics {
436 related := make([]protocol.DiagnosticRelatedInformation, 0, len(diag.Related))
437 for _, rel := range diag.Related {
438 related = append(related, protocol.DiagnosticRelatedInformation{
439 Location: protocol.Location{
440 URI: protocol.URIFromSpanURI(rel.URI),
443 Message: rel.Message,
446 reports = append(reports, protocol.Diagnostic{
447 // diag.Message might start with \n or \t
448 Message: strings.TrimSpace(diag.Message),
450 Severity: diag.Severity,
453 RelatedInformation: related,
459 func (s *Server) handleFatalErrors(ctx context.Context, snapshot source.Snapshot, modErr, loadErr error) bool {
460 // If the folder has no Go code in it, we shouldn't spam the user with a warning.
462 _ = filepath.Walk(snapshot.View().Folder().Filename(), func(path string, info os.FileInfo, err error) error {
466 if !strings.HasSuffix(info.Name(), ".go") {
470 return errors.New("done")
476 // All other workarounds are for errors associated with modules.
477 if len(snapshot.ModFiles()) == 0 {
482 case source.InconsistentVendoring:
483 item, err := s.client.ShowMessageRequest(ctx, &protocol.ShowMessageRequestParams{
484 Type: protocol.Error,
485 Message: `Inconsistent vendoring detected. Please re-run "go mod vendor".
486 See https://github.com/golang/go/issues/39164 for more detail on this issue.`,
487 Actions: []protocol.MessageActionItem{
488 {Title: "go mod vendor"},
491 // If the user closes the pop-up, don't show them further errors.
496 event.Error(ctx, "go mod vendor ShowMessageRequest failed", err, tag.Directory.Of(snapshot.View().Folder().Filename()))
499 // Right now, we don't have a good way of mapping the error message
500 // to a specific module, so this will re-run `go mod vendor` in every
501 // known module with a vendor directory.
502 // TODO(rstambler): Only re-run `go mod vendor` in the relevant module.
503 for _, uri := range snapshot.ModFiles() {
504 // Check that there is a vendor directory in the module before
505 // running `go mod vendor`.
506 if info, _ := os.Stat(filepath.Join(filepath.Dir(uri.Filename()), "vendor")); info == nil {
509 if err := s.directGoModCommand(ctx, protocol.URIFromSpanURI(uri), "mod", []string{"vendor"}...); err != nil {
510 if err := s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
511 Type: protocol.Error,
512 Message: fmt.Sprintf(`"go mod vendor" failed with %v`, err),
515 event.Error(ctx, "go mod vendor ShowMessage failed", err, tag.Directory.Of(snapshot.View().Folder().Filename()))