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