Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / internal / lsp / source / 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 source
6
7 import (
8         "context"
9         "fmt"
10         "strings"
11
12         "golang.org/x/tools/go/analysis"
13         "golang.org/x/tools/internal/event"
14         "golang.org/x/tools/internal/lsp/debug/tag"
15         "golang.org/x/tools/internal/lsp/protocol"
16         "golang.org/x/tools/internal/span"
17         errors "golang.org/x/xerrors"
18 )
19
20 type Diagnostic struct {
21         Range    protocol.Range
22         Message  string
23         Source   string
24         Severity protocol.DiagnosticSeverity
25         Tags     []protocol.DiagnosticTag
26
27         Related []RelatedInformation
28 }
29
30 type SuggestedFix struct {
31         Title string
32         Edits map[span.URI][]protocol.TextEdit
33 }
34
35 type RelatedInformation struct {
36         URI     span.URI
37         Range   protocol.Range
38         Message string
39 }
40
41 func Diagnostics(ctx context.Context, snapshot Snapshot, pkg Package, withAnalysis bool) (map[VersionedFileIdentity][]*Diagnostic, bool, error) {
42         onlyIgnoredFiles := true
43         for _, pgf := range pkg.CompiledGoFiles() {
44                 onlyIgnoredFiles = onlyIgnoredFiles && snapshot.IgnoredFile(pgf.URI)
45         }
46         if onlyIgnoredFiles {
47                 return nil, false, nil
48         }
49
50         // If we are missing dependencies, it may because the user's workspace is
51         // not correctly configured. Report errors, if possible.
52         var warn bool
53         if len(pkg.MissingDependencies()) > 0 {
54                 warn = true
55         }
56         // If we have a package with a single file and errors about "undeclared" symbols,
57         // we may have an ad-hoc package with multiple files. Show a warning message.
58         // TODO(golang/go#36416): Remove this when golang.org/cl/202277 is merged.
59         if len(pkg.CompiledGoFiles()) == 1 && hasUndeclaredErrors(pkg) {
60                 warn = true
61         }
62         // Prepare the reports we will send for the files in this package.
63         reports := make(map[VersionedFileIdentity][]*Diagnostic)
64         for _, pgf := range pkg.CompiledGoFiles() {
65                 clearReports(snapshot, reports, pgf.URI)
66         }
67         // Prepare any additional reports for the errors in this package.
68         for _, e := range pkg.GetErrors() {
69                 // We only need to handle lower-level errors.
70                 if e.Kind != ListError {
71                         continue
72                 }
73                 // If no file is associated with the error, pick an open file from the package.
74                 if e.URI.Filename() == "" {
75                         for _, pgf := range pkg.CompiledGoFiles() {
76                                 if snapshot.IsOpen(pgf.URI) {
77                                         e.URI = pgf.URI
78                                 }
79                         }
80                 }
81                 clearReports(snapshot, reports, e.URI)
82         }
83         // Run diagnostics for the package that this URI belongs to.
84         hadDiagnostics, hadTypeErrors, err := diagnostics(ctx, snapshot, reports, pkg, len(pkg.MissingDependencies()) > 0)
85         if err != nil {
86                 return nil, warn, err
87         }
88         if hadDiagnostics || !withAnalysis {
89                 return reports, warn, nil
90         }
91         // Exit early if the context has been canceled. This also protects us
92         // from a race on Options, see golang/go#36699.
93         if ctx.Err() != nil {
94                 return nil, warn, ctx.Err()
95         }
96         // If we don't have any list or parse errors, run analyses.
97         analyzers := pickAnalyzers(snapshot, hadTypeErrors)
98         if err := analyses(ctx, snapshot, reports, pkg, analyzers); err != nil {
99                 event.Error(ctx, "analyses failed", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
100                 if ctx.Err() != nil {
101                         return nil, warn, ctx.Err()
102                 }
103         }
104         return reports, warn, nil
105 }
106
107 func pickAnalyzers(snapshot Snapshot, hadTypeErrors bool) map[string]Analyzer {
108         analyzers := make(map[string]Analyzer)
109
110         // Always run convenience analyzers.
111         for k, v := range snapshot.View().Options().ConvenienceAnalyzers {
112                 analyzers[k] = v
113         }
114         // If we had type errors, only run type error analyzers.
115         if hadTypeErrors {
116                 for k, v := range snapshot.View().Options().TypeErrorAnalyzers {
117                         analyzers[k] = v
118                 }
119                 return analyzers
120         }
121         for k, v := range snapshot.View().Options().DefaultAnalyzers {
122                 analyzers[k] = v
123         }
124         for k, v := range snapshot.View().Options().StaticcheckAnalyzers {
125                 analyzers[k] = v
126         }
127         return analyzers
128 }
129
130 func FileDiagnostics(ctx context.Context, snapshot Snapshot, uri span.URI) (VersionedFileIdentity, []*Diagnostic, error) {
131         fh, err := snapshot.GetVersionedFile(ctx, uri)
132         if err != nil {
133                 return VersionedFileIdentity{}, nil, err
134         }
135         pkg, _, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage)
136         if err != nil {
137                 return VersionedFileIdentity{}, nil, err
138         }
139         reports, _, err := Diagnostics(ctx, snapshot, pkg, true)
140         if err != nil {
141                 return VersionedFileIdentity{}, nil, err
142         }
143         diagnostics, ok := reports[fh.VersionedFileIdentity()]
144         if !ok {
145                 return VersionedFileIdentity{}, nil, errors.Errorf("no diagnostics for %s", uri)
146         }
147         return fh.VersionedFileIdentity(), diagnostics, nil
148 }
149
150 type diagnosticSet struct {
151         listErrors, parseErrors, typeErrors []*Diagnostic
152 }
153
154 func diagnostics(ctx context.Context, snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, pkg Package, hasMissingDeps bool) (bool, bool, error) {
155         ctx, done := event.Start(ctx, "source.diagnostics", tag.Package.Of(pkg.ID()))
156         _ = ctx // circumvent SA4006
157         defer done()
158
159         diagSets := make(map[span.URI]*diagnosticSet)
160         for _, e := range pkg.GetErrors() {
161                 diag := &Diagnostic{
162                         Message:  e.Message,
163                         Range:    e.Range,
164                         Severity: protocol.SeverityError,
165                         Related:  e.Related,
166                 }
167                 set, ok := diagSets[e.URI]
168                 if !ok {
169                         set = &diagnosticSet{}
170                         diagSets[e.URI] = set
171                 }
172                 switch e.Kind {
173                 case ParseError:
174                         set.parseErrors = append(set.parseErrors, diag)
175                         diag.Source = "syntax"
176                 case TypeError:
177                         set.typeErrors = append(set.typeErrors, diag)
178                         diag.Source = "compiler"
179                 case ListError:
180                         set.listErrors = append(set.listErrors, diag)
181                         diag.Source = "go list"
182                 }
183         }
184         var nonEmptyDiagnostics, hasTypeErrors bool // track if we actually send non-empty diagnostics
185         for uri, set := range diagSets {
186                 // Don't report type errors if there are parse errors or list errors.
187                 diags := set.typeErrors
188                 if len(set.parseErrors) > 0 {
189                         diags, nonEmptyDiagnostics = set.parseErrors, true
190                 } else if len(set.listErrors) > 0 {
191                         // Only show list errors if the package has missing dependencies.
192                         if hasMissingDeps {
193                                 diags, nonEmptyDiagnostics = set.listErrors, true
194                         }
195                 } else if len(set.typeErrors) > 0 {
196                         hasTypeErrors = true
197                 }
198                 if err := addReports(snapshot, reports, uri, diags...); err != nil {
199                         return false, false, err
200                 }
201         }
202         return nonEmptyDiagnostics, hasTypeErrors, nil
203 }
204
205 func analyses(ctx context.Context, snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, pkg Package, analyses map[string]Analyzer) error {
206         var analyzers []*analysis.Analyzer
207         for _, a := range analyses {
208                 if !a.IsEnabled(snapshot.View()) {
209                         continue
210                 }
211                 analyzers = append(analyzers, a.Analyzer)
212         }
213         analysisErrors, err := snapshot.Analyze(ctx, pkg.ID(), analyzers...)
214         if err != nil {
215                 return err
216         }
217
218         // Report diagnostics and errors from root analyzers.
219         for _, e := range analysisErrors {
220                 // If the diagnostic comes from a "convenience" analyzer, it is not
221                 // meant to provide diagnostics, but rather only suggested fixes.
222                 // Skip these types of errors in diagnostics; we will use their
223                 // suggested fixes when providing code actions.
224                 if isConvenienceAnalyzer(e.Category) {
225                         continue
226                 }
227                 // This is a bit of a hack, but clients > 3.15 will be able to grey out unnecessary code.
228                 // If we are deleting code as part of all of our suggested fixes, assume that this is dead code.
229                 // TODO(golang/go#34508): Return these codes from the diagnostics themselves.
230                 var tags []protocol.DiagnosticTag
231                 if onlyDeletions(e.SuggestedFixes) {
232                         tags = append(tags, protocol.Unnecessary)
233                 }
234                 if err := addReports(snapshot, reports, e.URI, &Diagnostic{
235                         Range:    e.Range,
236                         Message:  e.Message,
237                         Source:   e.Category,
238                         Severity: protocol.SeverityWarning,
239                         Tags:     tags,
240                         Related:  e.Related,
241                 }); err != nil {
242                         return err
243                 }
244         }
245         return nil
246 }
247
248 func clearReports(snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, uri span.URI) {
249         fh := snapshot.FindFile(uri)
250         if fh == nil {
251                 return
252         }
253         reports[fh.VersionedFileIdentity()] = []*Diagnostic{}
254 }
255
256 func addReports(snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, uri span.URI, diagnostics ...*Diagnostic) error {
257         fh := snapshot.FindFile(uri)
258         if fh == nil {
259                 return nil
260         }
261         existingDiagnostics, ok := reports[fh.VersionedFileIdentity()]
262         if !ok {
263                 return fmt.Errorf("diagnostics for unexpected file %s", uri)
264         }
265         if len(diagnostics) == 1 {
266                 d1 := diagnostics[0]
267                 if _, ok := snapshot.View().Options().TypeErrorAnalyzers[d1.Source]; ok {
268                         for i, d2 := range existingDiagnostics {
269                                 if r := protocol.CompareRange(d1.Range, d2.Range); r != 0 {
270                                         continue
271                                 }
272                                 if d1.Message != d2.Message {
273                                         continue
274                                 }
275                                 reports[fh.VersionedFileIdentity()][i].Tags = append(reports[fh.VersionedFileIdentity()][i].Tags, d1.Tags...)
276                         }
277                         return nil
278                 }
279         }
280         reports[fh.VersionedFileIdentity()] = append(reports[fh.VersionedFileIdentity()], diagnostics...)
281         return nil
282 }
283
284 // onlyDeletions returns true if all of the suggested fixes are deletions.
285 func onlyDeletions(fixes []SuggestedFix) bool {
286         for _, fix := range fixes {
287                 for _, edits := range fix.Edits {
288                         for _, edit := range edits {
289                                 if edit.NewText != "" {
290                                         return false
291                                 }
292                                 if protocol.ComparePosition(edit.Range.Start, edit.Range.End) == 0 {
293                                         return false
294                                 }
295                         }
296                 }
297         }
298         return len(fixes) > 0
299 }
300
301 // hasUndeclaredErrors returns true if a package has a type error
302 // about an undeclared symbol.
303 func hasUndeclaredErrors(pkg Package) bool {
304         for _, err := range pkg.GetErrors() {
305                 if err.Kind != TypeError {
306                         continue
307                 }
308                 if strings.Contains(err.Message, "undeclared name:") {
309                         return true
310                 }
311         }
312         return false
313 }
314
315 func isConvenienceAnalyzer(category string) bool {
316         for _, a := range DefaultOptions().ConvenienceAnalyzers {
317                 if category == a.Analyzer.Name {
318                         return true
319                 }
320         }
321         return false
322 }