Debian Codegraph @

gopls/internal/server/diagnostics.go

raw symbols SCIP
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 server
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "os"
12 "path/filepath"
13 "runtime"
14 "slices"
15 "sort"
16 "strings"
17 "sync"
18 "time"
19
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/cache/metadata"
22 "golang.org/x/tools/gopls/internal/file"
23 "golang.org/x/tools/gopls/internal/golang"
24 "golang.org/x/tools/gopls/internal/label"
25 "golang.org/x/tools/gopls/internal/mod"
26 "golang.org/x/tools/gopls/internal/protocol"
27 "golang.org/x/tools/gopls/internal/settings"
28 "golang.org/x/tools/gopls/internal/template"
29 "golang.org/x/tools/gopls/internal/util/moremaps"
30 "golang.org/x/tools/gopls/internal/work"
31 "golang.org/x/tools/internal/event"
32 "golang.org/x/tools/internal/event/keys"
33 "golang.org/x/tools/internal/jsonrpc2"
34 )
35
36 // Diagnostic implements the textDocument/diagnostic LSP request, reporting
37 // diagnostics for the given file.
38 //
39 // This is a work in progress.
40 // TODO(rfindley):
41 // - support RelatedDocuments? If so, how? Maybe include other package diagnostics?
42 // - support resultID (=snapshot ID)
43 // - support multiple views
44 // - add orphaned file diagnostics
45 // - support go.mod, go.work files
46 func (s *server) Diagnostic(ctx context.Context, params *protocol.DocumentDiagnosticParams) (*protocol.DocumentDiagnosticReport, error) {
47 ctx, done := event.Start(ctx, "server.Diagnostic")
48 defer done()
49
50 fh, snapshot, release, err := s.session.FileOf(ctx, params.TextDocument.URI)
51 if err != nil {
52 return nil, err
53 }
54 defer release()
55
56 jsonrpc2.Async(ctx) // allow asynchronous collection of diagnostics
57
58 uri := fh.URI()
59 kind := snapshot.FileKind(fh)
60 var diagnostics []*cache.Diagnostic
61 switch kind {
62 case file.Go:
63 diagnostics, err = golang.DiagnoseFile(ctx, snapshot, uri)
64 if err != nil {
65 return nil, err
66 }
67 default:
68 return nil, fmt.Errorf("pull diagnostics not supported for this file kind")
69 }
70 return &protocol.DocumentDiagnosticReport{
71 Value: protocol.RelatedFullDocumentDiagnosticReport{
72 FullDocumentDiagnosticReport: protocol.FullDocumentDiagnosticReport{
73 Items: cache.ToProtocolDiagnostics(diagnostics...),
74 },
75 },
76 }, nil
77 }
78
79 // fileDiagnostics holds the current state of published diagnostics for a file.
80 type fileDiagnostics struct {
81 publishedHash file.Hash // hash of the last set of diagnostics published for this URI
82 mustPublish bool // if set, publish diagnostics even if they haven't changed
83
84 // Orphaned file diagnostics are not necessarily associated with any *View
85 // (since they are orphaned). Instead, keep track of the modification ID at
86 // which they were orphaned (see server.lastModificationID).
87 orphanedAt uint64 // modification ID at which this file was orphaned.
88 orphanedFileDiagnostics []*cache.Diagnostic
89
90 // Files may have their diagnostics computed by multiple views, and so
91 // diagnostics are organized by View. See the documentation for update for more
92 // details about how the set of file diagnostics evolves over time.
93 byView map[*cache.View]viewDiagnostics
94 }
95
96 // viewDiagnostics holds a set of file diagnostics computed from a given View.
97 type viewDiagnostics struct {
98 snapshot uint64 // snapshot sequence ID
99 version int32 // file version
100 diagnostics []*cache.Diagnostic
101 }
102
103 // common types; for brevity
104 type (
105 viewSet = map[*cache.View]unit
106 diagMap = map[protocol.DocumentURI][]*cache.Diagnostic
107 )
108
109 func sortDiagnostics(d []*cache.Diagnostic) {
110 sort.Slice(d, func(i int, j int) bool {
111 a, b := d[i], d[j]
112 if r := protocol.CompareRange(a.Range, b.Range); r != 0 {
113 return r < 0
114 }
115 if a.Source != b.Source {
116 return a.Source < b.Source
117 }
118 return a.Message < b.Message
119 })
120 }
121
122 func (s *server) diagnoseChangedViews(ctx context.Context, modID uint64, lastChange map[*cache.View][]protocol.DocumentURI, cause ModificationSource) {
123 // Collect views needing diagnosis.
124 s.modificationMu.Lock()
125 needsDiagnosis := moremaps.KeySlice(s.viewsToDiagnose)
126 s.modificationMu.Unlock()
127
128 // Diagnose views concurrently.
129 var wg sync.WaitGroup
130 for _, v := range needsDiagnosis {
131 snapshot, release, err := v.Snapshot()
132 if err != nil {
133 s.modificationMu.Lock()
134 // The View is shut down. Unlike below, no need to check
135 // s.needsDiagnosis[v], since the view can never be diagnosed.
136 delete(s.viewsToDiagnose, v)
137 s.modificationMu.Unlock()
138 continue
139 }
140
141 // Collect uris for fast diagnosis. We only care about the most recent
142 // change here, because this is just an optimization for the case where the
143 // user is actively editing a single file.
144 uris := lastChange[v]
145 if snapshot.Options().DiagnosticsTrigger == settings.DiagnosticsOnSave && cause == FromDidChange {
146 // The user requested to update the diagnostics only on save.
147 // Do not diagnose yet.
148 release()
149 continue
150 }
151
152 wg.Add(1)
153 go func(snapshot *cache.Snapshot, uris []protocol.DocumentURI) {
154 defer release()
155 defer wg.Done()
156 s.diagnoseSnapshot(ctx, snapshot, uris, snapshot.Options().DiagnosticsDelay)
157 s.modificationMu.Lock()
158
159 // Only remove v from s.viewsToDiagnose if the context is not cancelled.
160 // This ensures that the snapshot was not cloned before its state was
161 // fully evaluated, and therefore avoids missing a change that was
162 // irrelevant to an incomplete snapshot.
163 //
164 // See the documentation for s.viewsToDiagnose for details.
165 if ctx.Err() == nil && s.viewsToDiagnose[v] <= modID {
166 delete(s.viewsToDiagnose, v)
167 }
168 s.modificationMu.Unlock()
169 }(snapshot, uris)
170 }
171
172 wg.Wait()
173
174 // Diagnose orphaned files for the session.
175 orphanedFileDiagnostics, err := s.session.OrphanedFileDiagnostics(ctx)
176 if err == nil {
177 err = s.updateOrphanedFileDiagnostics(ctx, modID, orphanedFileDiagnostics)
178 }
179 if err != nil {
180 if ctx.Err() == nil {
181 event.Error(ctx, "warning: while diagnosing orphaned files", err)
182 }
183 }
184 }
185
186 // diagnoseSnapshot computes and publishes diagnostics for the given snapshot.
187 //
188 // If delay is non-zero, computing diagnostics does not start until after this
189 // delay has expired, to allow work to be cancelled by subsequent changes.
190 //
191 // If changedURIs is non-empty, it is a set of recently changed files that
192 // should be diagnosed immediately, and onDisk reports whether these file
193 // changes came from a change to on-disk files.
194 //
195 // If the provided context is cancelled, diagnostics may be partially
196 // published. Therefore, the provided context should only be cancelled if there
197 // will be a subsequent operation to make diagnostics consistent. In general,
198 // if an operation creates a new snapshot, it is responsible for ensuring that
199 // snapshot (or a subsequent snapshot in the same View) is eventually
200 // diagnosed.
201 func (s *server) diagnoseSnapshot(ctx context.Context, snapshot *cache.Snapshot, changedURIs []protocol.DocumentURI, delay time.Duration) {
202 ctx, done := event.Start(ctx, "server.diagnoseSnapshot", snapshot.Labels()...)
203 defer done()
204
205 if delay > 0 {
206 // 2-phase diagnostics.
207 //
208 // The first phase just parses and type-checks (but
209 // does not analyze) packages directly affected by
210 // file modifications.
211 //
212 // The second phase runs after the delay, and does everything.
213
214 if len(changedURIs) > 0 {
215 diagnostics, err := diagnoseChangedFiles(ctx, snapshot, changedURIs)
216 if err != nil {
217 if ctx.Err() == nil {
218 event.Error(ctx, "warning: while diagnosing changed files", err, snapshot.Labels()...)
219 }
220 return
221 }
222 s.updateDiagnostics(ctx, snapshot, diagnostics, false)
223 }
224
225 select {
226 case <-time.After(delay):
227 case <-ctx.Done():
228 return
229 }
230 }
231
232 diagnostics, err := s.diagnose(ctx, snapshot)
233 if err != nil {
234 if ctx.Err() == nil {
235 event.Error(ctx, "warning: while diagnosing snapshot", err, snapshot.Labels()...)
236 }
237 return
238 }
239 s.updateDiagnostics(ctx, snapshot, diagnostics, true)
240 }
241
242 func diagnoseChangedFiles(ctx context.Context, snapshot *cache.Snapshot, uris []protocol.DocumentURI) (diagMap, error) {
243 ctx, done := event.Start(ctx, "server.diagnoseChangedFiles", snapshot.Labels()...)
244 defer done()
245
246 toDiagnose := make(map[metadata.PackageID]*metadata.Package)
247 for _, uri := range uris {
248 // If the file is not open, don't diagnose its package.
249 //
250 // We don't care about fast diagnostics for files that are no longer open,
251 // because the user isn't looking at them. Also, explicitly requesting a
252 // package can lead to "command-line-arguments" packages if the file isn't
253 // covered by the current View. By avoiding requesting packages for e.g.
254 // unrelated file movement, we can minimize these unnecessary packages.
255 if !snapshot.IsOpen(uri) {
256 continue
257 }
258 // If the file is not known to the snapshot (e.g., if it was deleted),
259 // don't diagnose it.
260 if fh, err := snapshot.ReadFile(ctx, uri); err != nil || fh == nil {
261 continue
262 }
263
264 // Don't request type-checking for builtin.go: it's not a real package.
265 if snapshot.IsBuiltin(uri) {
266 continue
267 }
268
269 // Don't diagnose files that are ignored by `go list` (e.g. testdata).
270 if snapshot.IgnoredFile(uri) {
271 continue
272 }
273
274 // Find all packages that include this file and diagnose them in parallel.
275 meta, err := snapshot.NarrowestMetadataForFile(ctx, uri)
276 if err != nil {
277 if ctx.Err() != nil {
278 return nil, ctx.Err()
279 }
280 // TODO(findleyr): we should probably do something with the error here,
281 // but as of now this can fail repeatedly if load fails, so can be too
282 // noisy to log (and we'll handle things later in the slow pass).
283 continue
284 }
285 // golang/go#65801: only diagnose changes to workspace packages. Otherwise,
286 // diagnostics will be unstable, as the slow-path diagnostics will erase
287 // them.
288 if snapshot.IsWorkspacePackage(meta.ID) {
289 toDiagnose[meta.ID] = meta
290 }
291 }
292 diags, err := snapshot.PackageDiagnostics(ctx, moremaps.KeySlice(toDiagnose)...)
293 if err != nil {
294 if ctx.Err() == nil {
295 event.Error(ctx, "warning: diagnostics failed", err, snapshot.Labels()...)
296 }
297 return nil, err
298 }
299 // golang/go#59587: guarantee that we compute type-checking diagnostics
300 // for every compiled package file, otherwise diagnostics won't be quickly
301 // cleared following a fix.
302 for _, meta := range toDiagnose {
303 for _, uri := range meta.CompiledGoFiles {
304 if _, ok := diags[uri]; !ok {
305 diags[uri] = nil
306 }
307 }
308 }
309 return diags, nil
310 }
311
312 func (s *server) diagnose(ctx context.Context, snapshot *cache.Snapshot) (diagMap, error) {
313 ctx, done := event.Start(ctx, "server.diagnose", snapshot.Labels()...)
314 defer done()
315
316 // Wait for a free diagnostics slot.
317 // TODO(adonovan): opt: shouldn't it be the analysis implementation's
318 // job to de-dup and limit resource consumption? In any case this
319 // function spends most its time waiting for awaitLoaded, at
320 // least initially.
321 select {
322 case <-ctx.Done():
323 return nil, ctx.Err()
324 case s.diagnosticsSema <- struct{}{}:
325 }
326 defer func() {
327 <-s.diagnosticsSema
328 }()
329
330 var (
331 diagnosticsMu sync.Mutex
332 diagnostics = make(diagMap)
333 )
334 // common code for dispatching diagnostics
335 store := func(operation string, diagsByFile diagMap, err error) {
336 if err != nil {
337 if ctx.Err() == nil {
338 event.Error(ctx, "warning: while "+operation, err, snapshot.Labels()...)
339 }
340 return
341 }
342 diagnosticsMu.Lock()
343 defer diagnosticsMu.Unlock()
344 for uri, diags := range diagsByFile {
345 diagnostics[uri] = append(diagnostics[uri], diags...)
346 }
347 }
348
349 // Diagnostics below are organized by increasing specificity:
350 // go.work > mod > mod upgrade > mod vuln > package, etc.
351
352 // Diagnose go.work file.
353 workReports, workErr := work.Diagnostics(ctx, snapshot)
354 if ctx.Err() != nil {
355 return nil, ctx.Err()
356 }
357 store("diagnosing go.work file", workReports, workErr)
358
359 // Diagnose go.mod file.
360 modReports, modErr := mod.ParseDiagnostics(ctx, snapshot)
361 if ctx.Err() != nil {
362 return nil, ctx.Err()
363 }
364 store("diagnosing go.mod file", modReports, modErr)
365
366 // Diagnose go.mod upgrades.
367 upgradeReports, upgradeErr := mod.UpgradeDiagnostics(ctx, snapshot)
368 if ctx.Err() != nil {
369 return nil, ctx.Err()
370 }
371 store("diagnosing go.mod upgrades", upgradeReports, upgradeErr)
372
373 // Diagnose vulnerabilities.
374 vulnReports, vulnErr := mod.VulnerabilityDiagnostics(ctx, snapshot)
375 if ctx.Err() != nil {
376 return nil, ctx.Err()
377 }
378 store("diagnosing vulnerabilities", vulnReports, vulnErr)
379
380 workspacePkgs, err := snapshot.WorkspaceMetadata(ctx)
381 if s.shouldIgnoreError(snapshot, err) {
382 return diagnostics, ctx.Err()
383 }
384
385 initialErr := snapshot.InitializationError()
386 if ctx.Err() != nil {
387 // Don't update initialization status if the context is cancelled.
388 return nil, ctx.Err()
389 }
390
391 if initialErr != nil {
392 store("critical error", initialErr.Diagnostics, nil)
393 }
394
395 // Show the error as a progress error report so that it appears in the
396 // status bar. If a client doesn't support progress reports, the error
397 // will still be shown as a ShowMessage. If there is no error, any running
398 // error progress reports will be closed.
399 statusErr := initialErr
400 if len(snapshot.Overlays()) == 0 {
401 // Don't report a hanging status message if there are no open files at this
402 // snapshot.
403 statusErr = nil
404 }
405 s.updateCriticalErrorStatus(ctx, snapshot, statusErr)
406
407 // Diagnose template (.tmpl) files.
408 tmplReports := template.Diagnostics(snapshot)
409 // NOTE(rfindley): typeCheckSource is not accurate here.
410 // (but this will be gone soon anyway).
411 store("diagnosing templates", tmplReports, nil)
412
413 // If there are no workspace packages, there is nothing to diagnose and
414 // there are no orphaned files.
415 if len(workspacePkgs) == 0 {
416 return diagnostics, nil
417 }
418
419 var wg sync.WaitGroup // for potentially slow operations below
420
421 // Maybe run go mod tidy (if it has been invalidated).
422 //
423 // Since go mod tidy can be slow, we run it concurrently to diagnostics.
424 wg.Go(func() {
425 modTidyReports, err := mod.TidyDiagnostics(ctx, snapshot)
426 store("running go mod tidy", modTidyReports, err)
427 })
428
429 // Run type checking and go/analysis diagnosis of packages in parallel.
430 //
431 // For analysis, we use the *widest* package for each open file,
432 // for two reasons:
433 //
434 // - Correctness: some analyzers (e.g. unused{param,func}) depend
435 // on it. If applied to a non-test package for which a
436 // corresponding test package exists, they make assumptions
437 // that are falsified in the test package, for example that
438 // all references to unexported symbols are visible to the
439 // analysis.
440 //
441 // - Efficiency: it may yield a smaller covering set of
442 // PackageIDs for a given set of files. For example, {x.go,
443 // x_test.go} is covered by the single package x_test using
444 // "widest". (Using "narrowest", it would be covered only by
445 // the pair of packages {x, x_test}, Originally we used all
446 // covering packages, so {x.go} alone would be analyzed
447 // twice.)
448 var (
449 toDiagnose = make(map[metadata.PackageID]*metadata.Package)
450 toAnalyze = make(map[metadata.PackageID]*metadata.Package)
451
452 // secondary index, used to eliminate narrower packages.
453 toAnalyzeWidest = make(map[golang.PackagePath]*metadata.Package)
454 )
455 for _, mp := range workspacePkgs {
456 var hasNonIgnored, hasOpenFile bool
457 for _, uri := range mp.CompiledGoFiles {
458 if !hasNonIgnored && !snapshot.IgnoredFile(uri) {
459 hasNonIgnored = true
460 }
461 if !hasOpenFile && snapshot.IsOpen(uri) {
462 hasOpenFile = true
463 }
464 }
465 if hasNonIgnored {
466 toDiagnose[mp.ID] = mp
467 if hasOpenFile {
468 if prev, ok := toAnalyzeWidest[mp.PkgPath]; ok {
469 if len(prev.CompiledGoFiles) >= len(mp.CompiledGoFiles) {
470 // Previous entry is not narrower; keep it.
471 continue
472 }
473 // Evict previous (narrower) entry.
474 delete(toAnalyze, prev.ID)
475 }
476 toAnalyze[mp.ID] = mp
477 toAnalyzeWidest[mp.PkgPath] = mp
478 }
479 }
480 }
481
482 wg.Go(func() {
483 compilerOptDetailsDiags, err := s.compilerOptDetailsDiagnostics(ctx, snapshot, toDiagnose)
484 store("collecting compiler optimization details", compilerOptDetailsDiags, err)
485 })
486
487 // Package diagnostics and analysis diagnostics must both be computed and
488 // merged before they can be reported.
489 var pkgDiags, analysisDiags diagMap
490 // Collect package diagnostics.
491 wg.Go(func() {
492 var err error
493 pkgDiags, err = snapshot.PackageDiagnostics(ctx, moremaps.KeySlice(toDiagnose)...)
494 if err != nil {
495 event.Error(ctx, "warning: diagnostics failed", err, snapshot.Labels()...)
496 }
497 })
498
499 // Get diagnostics from analysis framework.
500 // This includes type-error analyzers, which suggest fixes to compiler errors.
501 wg.Go(func() {
502 var err error
503 // TODO(rfindley): here and above, we should avoid using the first result
504 // if err is non-nil (though as of today it's OK).
505 analysisDiags, err = golang.Analyze(ctx, snapshot, toAnalyze, s.progress)
506
507 // Filter out Hint diagnostics for closed files.
508 // VS Code already omits Hint diagnostics in the Problems tab, but other
509 // clients do not. This filter makes the visibility of Hints more similar
510 // across clients.
511 for uri, diags := range analysisDiags {
512 if !snapshot.IsOpen(uri) {
513 newDiags := slices.DeleteFunc(diags, func(diag *cache.Diagnostic) bool {
514 return diag.Severity == protocol.SeverityHint
515 })
516 if len(newDiags) == 0 {
517 delete(analysisDiags, uri)
518 } else {
519 analysisDiags[uri] = newDiags
520 }
521 }
522 }
523
524 if err != nil {
525 event.Error(ctx, "warning: analyzing package", err, append(snapshot.Labels(), label.Package.Of(keys.Join(moremaps.KeySlice(toDiagnose))))...)
526 return
527 }
528 })
529
530 wg.Wait()
531
532 // Merge analysis diagnostics with package diagnostics, and store the
533 // resulting analysis diagnostics.
534 combinedDiags := make(diagMap)
535 for uri, adiags := range analysisDiags {
536 tdiags := pkgDiags[uri]
537 combinedDiags[uri] = golang.CombineDiagnostics(tdiags, adiags)
538 }
539 for uri, tdiags := range pkgDiags {
540 if _, ok := combinedDiags[uri]; !ok {
541 combinedDiags[uri] = tdiags
542 }
543 }
544 store("type checking and analysing", combinedDiags, nil) // error reported above
545
546 return diagnostics, nil
547 }
548
549 func (s *server) compilerOptDetailsDiagnostics(ctx context.Context, snapshot *cache.Snapshot, toDiagnose map[metadata.PackageID]*metadata.Package) (diagMap, error) {
550 // Process requested diagnostics about compiler optimization details.
551 //
552 // TODO(rfindley): This should memoize its results if the package has not changed.
553 // Consider that these points, in combination with the note below about
554 // races, suggest that compiler optimization details should be tracked on the Snapshot.
555 diagnostics := make(diagMap)
556 seenDirs := make(map[protocol.DocumentURI]bool)
557 for _, mp := range toDiagnose {
558 if len(mp.CompiledGoFiles) == 0 {
559 continue
560 }
561 dir := mp.CompiledGoFiles[0].Dir()
562 if snapshot.WantCompilerOptDetails(dir) {
563 if !seenDirs[dir] {
564 seenDirs[dir] = true
565
566 perFileDiags, err := golang.CompilerOptDetails(ctx, snapshot, dir)
567 if err != nil {
568 event.Error(ctx, "warning: compiler optimization details", err, append(snapshot.Labels(), label.URI.Of(dir))...)
569 continue
570 }
571 for uri, diags := range perFileDiags {
572 diagnostics[uri] = append(diagnostics[uri], diags...)
573 }
574 }
575 }
576 }
577 return diagnostics, nil
578 }
579
580 // mustPublishDiagnostics marks the uri as needing publication, independent of
581 // whether the published contents have changed.
582 //
583 // This can be used for ensuring gopls publishes diagnostics after certain file
584 // events.
585 func (s *server) mustPublishDiagnostics(uri protocol.DocumentURI) {
586 s.diagnosticsMu.Lock()
587 defer s.diagnosticsMu.Unlock()
588
589 if s.diagnostics[uri] == nil {
590 s.diagnostics[uri] = new(fileDiagnostics)
591 }
592 s.diagnostics[uri].mustPublish = true
593 }
594
595 const WorkspaceLoadFailure = "Error loading workspace"
596
597 // updateCriticalErrorStatus updates the critical error progress notification
598 // based on err.
599 //
600 // If err is nil, or if there are no open files, it clears any existing error
601 // progress report.
602 func (s *server) updateCriticalErrorStatus(ctx context.Context, snapshot *cache.Snapshot, err *cache.InitializationError) {
603 s.criticalErrorStatusMu.Lock()
604 defer s.criticalErrorStatusMu.Unlock()
605
606 // Remove all newlines so that the error message can be formatted in a
607 // status bar.
608 var errMsg string
609 if err != nil {
610 errMsg = strings.ReplaceAll(err.MainError.Error(), "\n", " ")
611 }
612
613 if s.criticalErrorStatus == nil {
614 if errMsg != "" {
615 event.Error(ctx, "errors loading workspace", err.MainError, snapshot.Labels()...)
616 s.criticalErrorStatus = s.progress.Start(ctx, WorkspaceLoadFailure, errMsg, nil, nil)
617 }
618 return
619 }
620
621 // If an error is already shown to the user, update it or mark it as
622 // resolved.
623 if errMsg == "" {
624 s.criticalErrorStatus.End(ctx, "Done.")
625 s.criticalErrorStatus = nil
626 } else {
627 s.criticalErrorStatus.Report(ctx, errMsg, 0)
628 }
629 }
630
631 // updateDiagnostics records the result of diagnosing a snapshot, and publishes
632 // any diagnostics that need to be updated on the client.
633 func (s *server) updateDiagnostics(ctx context.Context, snapshot *cache.Snapshot, diagnostics diagMap, final bool) {
634 ctx, done := event.Start(ctx, "server.publishDiagnostics")
635 defer done()
636
637 s.diagnosticsMu.Lock()
638 defer s.diagnosticsMu.Unlock()
639
640 // Before updating any diagnostics, check that the context (i.e. snapshot
641 // background context) is not cancelled.
642 //
643 // If not, then we know that we haven't started diagnosing the next snapshot,
644 // because the previous snapshot is cancelled before the next snapshot is
645 // returned from Invalidate.
646 //
647 // Therefore, even if we publish stale diagnostics here, they should
648 // eventually be overwritten with accurate diagnostics.
649 //
650 // TODO(rfindley): refactor the API to force that snapshots are diagnosed
651 // after they are created.
652 if ctx.Err() != nil {
653 return
654 }
655
656 // golang/go#65312: since the set of diagnostics depends on the set of views,
657 // we get the views *after* locking diagnosticsMu. This ensures that
658 // updateDiagnostics does not incorrectly delete diagnostics that have been
659 // set for an existing view that was created between the call to
660 // s.session.Views() and updateDiagnostics.
661 viewMap := make(viewSet)
662 for _, v := range s.session.Views() {
663 viewMap[v] = unit{}
664 }
665
666 // updateAndPublish updates diagnostics for a file, checking both the latest
667 // diagnostics for the current snapshot, as well as reconciling the set of
668 // views.
669 updateAndPublish := func(uri protocol.DocumentURI, f *fileDiagnostics, diags []*cache.Diagnostic) error {
670 current, ok := f.byView[snapshot.View()]
671 // Update the stored diagnostics if:
672 // 1. we've never seen diagnostics for this view,
673 // 2. diagnostics are for an older snapshot, or
674 // 3. we're overwriting with final diagnostics
675 //
676 // In other words, we shouldn't overwrite existing diagnostics for a
677 // snapshot with non-final diagnostics. This avoids the race described at
678 // https://github.com/golang/go/issues/64765#issuecomment-1890144575.
679 if !ok || current.snapshot < snapshot.SequenceID() || (current.snapshot == snapshot.SequenceID() && final) {
680 fh, err := snapshot.ReadFile(ctx, uri)
681 if err != nil {
682 return err
683 }
684 current = viewDiagnostics{
685 snapshot: snapshot.SequenceID(),
686 version: fh.Version(),
687 diagnostics: diags,
688 }
689 if f.byView == nil {
690 f.byView = make(map[*cache.View]viewDiagnostics)
691 }
692 f.byView[snapshot.View()] = current
693 }
694
695 return s.publishFileDiagnosticsLocked(ctx, viewMap, uri, current.version, f)
696 }
697
698 seen := make(map[protocol.DocumentURI]bool)
699 for uri, diags := range diagnostics {
700 f, ok := s.diagnostics[uri]
701 if !ok {
702 f = new(fileDiagnostics)
703 s.diagnostics[uri] = f
704 }
705 seen[uri] = true
706 if err := updateAndPublish(uri, f, diags); err != nil {
707 if ctx.Err() != nil {
708 return
709 } else {
710 event.Error(ctx, "updateDiagnostics: failed to deliver diagnostics", err, label.URI.Of(uri))
711 }
712 }
713 }
714
715 // TODO(rfindley): perhaps we should clean up files that have no diagnostics.
716 // One could imagine a large operation generating diagnostics for a great
717 // number of files, after which gopls has to do more bookkeeping into the
718 // future.
719 if final {
720 for uri, f := range s.diagnostics {
721 if !seen[uri] {
722 if err := updateAndPublish(uri, f, nil); err != nil {
723 if ctx.Err() != nil {
724 return
725 } else {
726 event.Error(ctx, "updateDiagnostics: failed to deliver diagnostics", err, label.URI.Of(uri))
727 }
728 }
729 }
730 }
731 }
732 }
733
734 // updateOrphanedFileDiagnostics records and publishes orphaned file
735 // diagnostics as a given modification time.
736 func (s *server) updateOrphanedFileDiagnostics(ctx context.Context, modID uint64, diagnostics diagMap) error {
737 views := s.session.Views()
738 viewSet := make(viewSet)
739 for _, v := range views {
740 viewSet[v] = unit{}
741 }
742
743 s.diagnosticsMu.Lock()
744 defer s.diagnosticsMu.Unlock()
745
746 for uri, diags := range diagnostics {
747 f, ok := s.diagnostics[uri]
748 if !ok {
749 f = new(fileDiagnostics)
750 s.diagnostics[uri] = f
751 }
752 if f.orphanedAt > modID {
753 continue
754 }
755 f.orphanedAt = modID
756 f.orphanedFileDiagnostics = diags
757 // TODO(rfindley): the version of this file is potentially inaccurate;
758 // nevertheless, it should be eventually consistent, because all
759 // modifications are diagnosed.
760 fh, err := s.session.ReadFile(ctx, uri)
761 if err != nil {
762 return err
763 }
764 if err := s.publishFileDiagnosticsLocked(ctx, viewSet, uri, fh.Version(), f); err != nil {
765 return err
766 }
767 }
768
769 // Clear any stale orphaned file diagnostics.
770 for uri, f := range s.diagnostics {
771 if f.orphanedAt < modID {
772 f.orphanedFileDiagnostics = nil
773 }
774 fh, err := s.session.ReadFile(ctx, uri)
775 if err != nil {
776 return err
777 }
778 if err := s.publishFileDiagnosticsLocked(ctx, viewSet, uri, fh.Version(), f); err != nil {
779 return err
780 }
781 }
782 return nil
783 }
784
785 // publishFileDiagnosticsLocked publishes a fileDiagnostics value, while holding s.diagnosticsMu.
786 //
787 // If the publication succeeds, it updates f.publishedHash and f.mustPublish.
788 func (s *server) publishFileDiagnosticsLocked(ctx context.Context, views viewSet, uri protocol.DocumentURI, version int32, f *fileDiagnostics) error {
789 // We add a disambiguating suffix (e.g. " [darwin,arm64]") to
790 // each diagnostic that doesn't occur in the default view;
791 // see golang/go#65496.
792 type diagSuffix struct {
793 diag *cache.Diagnostic
794 suffix string // "" for default build (or orphans)
795 }
796
797 // diagSuffixes records the set of view suffixes for a given diagnostic.
798 diagSuffixes := make(map[file.Hash][]diagSuffix)
799 add := func(diag *cache.Diagnostic, suffix string) {
800 h := diag.Hash()
801 diagSuffixes[h] = append(diagSuffixes[h], diagSuffix{diag, suffix})
802 }
803
804 // Construct the inverse mapping, from diagnostic (hash) to its suffixes (views).
805 for _, diag := range f.orphanedFileDiagnostics {
806 add(diag, "")
807 }
808
809 var allViews []*cache.View
810 for view, viewDiags := range f.byView {
811 if _, ok := views[view]; !ok {
812 delete(f.byView, view) // view no longer exists
813 continue
814 }
815 if viewDiags.version != version {
816 continue // a payload of diagnostics applies to a specific file version
817 }
818 allViews = append(allViews, view)
819 }
820
821 // Only report diagnostics from relevant views for a file. This avoids
822 // spurious import errors when a view has only a partial set of dependencies
823 // for a package (golang/go#66425).
824 //
825 // It's ok to use the session to derive the eligible views, because we
826 // publish diagnostics following any state change, so the set of relevant
827 // views is eventually consistent.
828 relevantViews, err := cache.RelevantViews(ctx, s.session, uri, allViews)
829 if err != nil {
830 return err
831 }
832
833 if len(relevantViews) == 0 {
834 // If we have no preferred diagnostics for a given file (i.e., the file is
835 // not naturally nested within a view), then all diagnostics should be
836 // considered valid.
837 //
838 // This could arise if the user jumps to definition outside the workspace.
839 // There is no view that owns the file, so its diagnostics are valid from
840 // any view.
841 relevantViews = allViews
842 }
843
844 for _, view := range relevantViews {
845 viewDiags := f.byView[view]
846 // Compute the view's suffix (e.g. " [darwin,arm64]").
847 var suffix string
848 {
849 var words []string
850 if view.GOOS() != runtime.GOOS {
851 words = append(words, view.GOOS())
852 }
853 if view.GOARCH() != runtime.GOARCH {
854 words = append(words, view.GOARCH())
855 }
856 if len(words) > 0 {
857 suffix = fmt.Sprintf(" [%s]", strings.Join(words, ","))
858 }
859 }
860
861 for _, diag := range viewDiags.diagnostics {
862 add(diag, suffix)
863 }
864 }
865
866 // De-dup diagnostics across views by hash, and sort.
867 var (
868 hash file.Hash
869 unique []*cache.Diagnostic
870 )
871 for h, items := range diagSuffixes {
872 // Sort the items by ascending suffix, so that the
873 // default view (if present) is first.
874 // (The others are ordered arbitrarily.)
875 sort.Slice(items, func(i, j int) bool {
876 return items[i].suffix < items[j].suffix
877 })
878
879 // If the diagnostic was not present in
880 // the default view, add the view suffix.
881 first := items[0]
882 if first.suffix != "" {
883 diag2 := *first.diag // shallow copy
884 diag2.Message += first.suffix
885 first.diag = &diag2
886 h = diag2.Hash() // update the hash
887 }
888
889 hash.XORWith(h)
890 unique = append(unique, first.diag)
891 }
892 sortDiagnostics(unique)
893
894 // Publish, if necessary.
895 if hash != f.publishedHash || f.mustPublish {
896 if err := s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{
897 Diagnostics: cache.ToProtocolDiagnostics(unique...),
898 URI: uri,
899 Version: version, // 0 ("on disk") => omitted from JSON encoding
900 }); err != nil {
901 return err
902 }
903 f.publishedHash = hash
904 f.mustPublish = false
905 }
906 return nil
907 }
908
909 func (s *server) shouldIgnoreError(snapshot *cache.Snapshot, err error) bool {
910 if err == nil { // if there is no error at all
911 return false
912 }
913 if errors.Is(err, context.Canceled) {
914 return true
915 }
916 // If the folder has no Go code in it, we shouldn't spam the user with a warning.
917 // TODO(rfindley): surely it is not correct to walk the folder here just to
918 // suppress diagnostics, every time we compute diagnostics.
919 var hasGo bool
920 _ = filepath.Walk(snapshot.Folder().Path(), func(_ string, info os.FileInfo, err error) error {
921 if err != nil {
922 return err
923 }
924 if !strings.HasSuffix(info.Name(), ".go") {
925 return nil
926 }
927 hasGo = true
928 return errors.New("done")
929 })
930 return !hasGo
931 }