Debian Codegraph @

gopls/internal/cache/errors.go

raw symbols SCIP
1 // Copyright 2019 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 cache
6
7 // This file defines routines to convert diagnostics from go list, go
8 // get, go/packages, parsing, type checking, and analysis into
9 // golang.Diagnostic form, and suggesting quick fixes.
10
11 import (
12 "context"
13 "fmt"
14 "go/parser"
15 "go/scanner"
16 "go/token"
17 "path/filepath"
18 "regexp"
19 "strconv"
20 "strings"
21
22 "golang.org/x/tools/go/packages"
23 "golang.org/x/tools/gopls/internal/cache/metadata"
24 "golang.org/x/tools/gopls/internal/cache/parsego"
25 "golang.org/x/tools/gopls/internal/file"
26 "golang.org/x/tools/gopls/internal/protocol"
27 "golang.org/x/tools/gopls/internal/protocol/command"
28 "golang.org/x/tools/gopls/internal/settings"
29 "golang.org/x/tools/gopls/internal/util/bug"
30 "golang.org/x/tools/internal/typesinternal"
31 )
32
33 // goPackagesErrorDiagnostics translates the given go/packages Error into a
34 // diagnostic, using the provided metadata and filesource.
35 //
36 // The slice of diagnostics may be empty.
37 func goPackagesErrorDiagnostics(ctx context.Context, e packages.Error, mp *metadata.Package, fs file.Source) ([]*Diagnostic, error) {
38 if diag, err := parseGoListImportCycleError(ctx, e, mp, fs); err != nil {
39 return nil, err
40 } else if diag != nil {
41 return []*Diagnostic{diag}, nil
42 }
43
44 // Parse error location and attempt to convert to protocol form.
45 loc, err := func() (protocol.Location, error) {
46 filename, line, col8 := parseGoListError(e, mp.LoadDir)
47 uri := protocol.URIFromPath(filename)
48
49 fh, err := fs.ReadFile(ctx, uri)
50 if err != nil {
51 return protocol.Location{}, err
52 }
53 content, err := fh.Content()
54 if err != nil {
55 return protocol.Location{}, err
56 }
57 mapper := protocol.NewMapper(uri, content)
58 posn, err := mapper.LineCol8Position(line, col8)
59 if err != nil {
60 return protocol.Location{}, err
61 }
62 return protocol.Location{
63 URI: uri,
64 Range: protocol.Range{
65 Start: posn,
66 End: posn,
67 },
68 }, nil
69 }()
70
71 // TODO(rfindley): in some cases the go command outputs invalid spans, for
72 // example (from TestGoListErrors):
73 //
74 // package a
75 // import
76 //
77 // In this case, the go command will complain about a.go:2:8, which is after
78 // the trailing newline but still considered to be on the second line, most
79 // likely because *token.File lacks information about newline termination.
80 //
81 // We could do better here by handling that case.
82 if err != nil {
83 // Unable to parse a valid position.
84 // Apply the error to all files to be safe.
85 var diags []*Diagnostic
86 for _, uri := range mp.CompiledGoFiles {
87 diags = append(diags, &Diagnostic{
88 URI: uri,
89 Severity: protocol.SeverityError,
90 Source: ListError,
91 Message: e.Msg,
92 })
93 }
94 return diags, nil
95 }
96 return []*Diagnostic{{
97 URI: loc.URI,
98 Range: loc.Range,
99 Severity: protocol.SeverityError,
100 Source: ListError,
101 Message: e.Msg,
102 }}, nil
103 }
104
105 func parseErrorDiagnostics(pkg *syntaxPackage, errList scanner.ErrorList) ([]*Diagnostic, error) {
106 // The first parser error is likely the root cause of the problem.
107 if errList.Len() <= 0 {
108 return nil, fmt.Errorf("no errors in %v", errList)
109 }
110 e := errList[0]
111 pgf, err := pkg.File(protocol.URIFromPath(e.Pos.Filename))
112 if err != nil {
113 return nil, err
114 }
115 rng, err := pgf.Mapper.OffsetRange(e.Pos.Offset, e.Pos.Offset)
116 if err != nil {
117 return nil, err
118 }
119 return []*Diagnostic{{
120 URI: pgf.URI,
121 Range: rng,
122 Severity: protocol.SeverityError,
123 Source: ParseError,
124 Message: e.Msg,
125 }}, nil
126 }
127
128 var importErrorRe = regexp.MustCompile(`could not import ([^\s]+)`)
129 var unsupportedFeatureRe = regexp.MustCompile(`.*require.* go(\d+\.\d+) or later`)
130
131 func goGetQuickFixes(haveModule bool, uri protocol.DocumentURI, pkg string) []SuggestedFix {
132 // Go get only supports module mode for now.
133 if !haveModule {
134 return nil
135 }
136 title := fmt.Sprintf("go get package %v", pkg)
137 cmd := command.NewGoGetPackageCommand(title, command.GoGetPackageArgs{
138 URI: uri,
139 AddRequire: true,
140 Pkg: pkg,
141 })
142 return []SuggestedFix{SuggestedFixFromCommand(cmd, protocol.QuickFix)}
143 }
144
145 func editGoDirectiveQuickFix(haveModule bool, uri protocol.DocumentURI, version string) []SuggestedFix {
146 // Go mod edit only supports module mode.
147 if !haveModule {
148 return nil
149 }
150 title := fmt.Sprintf("go mod edit -go=%s", version)
151 cmd := command.NewEditGoDirectiveCommand(title, command.EditGoDirectiveArgs{
152 URI: uri,
153 Version: version,
154 })
155 return []SuggestedFix{SuggestedFixFromCommand(cmd, protocol.QuickFix)}
156 }
157
158 // encodeDiagnostics gob-encodes the given diagnostics.
159 func encodeDiagnostics(srcDiags []*Diagnostic) []byte {
160 var gobDiags []gobDiagnostic
161 for _, srcDiag := range srcDiags {
162 var gobFixes []gobSuggestedFix
163 for _, srcFix := range srcDiag.SuggestedFixes {
164 gobFix := gobSuggestedFix{
165 Message: srcFix.Title,
166 ActionKind: srcFix.ActionKind,
167 }
168 for uri, srcEdits := range srcFix.Edits {
169 for _, srcEdit := range srcEdits {
170 gobFix.TextEdits = append(gobFix.TextEdits, gobTextEdit{
171 Location: uri.Location(srcEdit.Range),
172 NewText: []byte(srcEdit.NewText),
173 })
174 }
175 }
176 if srcCmd := srcFix.Command; srcCmd != nil {
177 gobFix.Command = &gobCommand{
178 Title: srcCmd.Title,
179 Command: srcCmd.Command,
180 Arguments: srcCmd.Arguments,
181 }
182 }
183 gobFixes = append(gobFixes, gobFix)
184 }
185 var gobRelated []gobRelatedInformation
186 for _, srcRel := range srcDiag.Related {
187 gobRel := gobRelatedInformation(srcRel)
188 gobRelated = append(gobRelated, gobRel)
189 }
190 gobDiag := gobDiagnostic{
191 Location: srcDiag.URI.Location(srcDiag.Range),
192 Severity: srcDiag.Severity,
193 Code: srcDiag.Code,
194 CodeHref: srcDiag.CodeHref,
195 Source: string(srcDiag.Source),
196 Message: srcDiag.Message,
197 SuggestedFixes: gobFixes,
198 Related: gobRelated,
199 Tags: srcDiag.Tags,
200 }
201 gobDiags = append(gobDiags, gobDiag)
202 }
203 return diagnosticsCodec.Encode(gobDiags)
204 }
205
206 // decodeDiagnostics decodes the given gob-encoded diagnostics.
207 func decodeDiagnostics(data []byte) []*Diagnostic {
208 gobDiags := diagnosticsCodec.Decode(data)
209 var srcDiags []*Diagnostic
210 for _, gobDiag := range gobDiags {
211 var srcFixes []SuggestedFix
212 for _, gobFix := range gobDiag.SuggestedFixes {
213 srcFix := SuggestedFix{
214 Title: gobFix.Message,
215 ActionKind: gobFix.ActionKind,
216 }
217 for _, gobEdit := range gobFix.TextEdits {
218 if srcFix.Edits == nil {
219 srcFix.Edits = make(map[protocol.DocumentURI][]protocol.TextEdit)
220 }
221 srcEdit := protocol.TextEdit{
222 Range: gobEdit.Location.Range,
223 NewText: string(gobEdit.NewText),
224 }
225 uri := gobEdit.Location.URI
226 srcFix.Edits[uri] = append(srcFix.Edits[uri], srcEdit)
227 }
228 if gobCmd := gobFix.Command; gobCmd != nil {
229 srcFix.Command = &protocol.Command{
230 Title: gobCmd.Title,
231 Command: gobCmd.Command,
232 Arguments: gobCmd.Arguments,
233 }
234 }
235 srcFixes = append(srcFixes, srcFix)
236 }
237 var srcRelated []protocol.DiagnosticRelatedInformation
238 for _, gobRel := range gobDiag.Related {
239 srcRel := protocol.DiagnosticRelatedInformation(gobRel)
240 srcRelated = append(srcRelated, srcRel)
241 }
242 srcDiag := &Diagnostic{
243 URI: gobDiag.Location.URI,
244 Range: gobDiag.Location.Range,
245 Severity: gobDiag.Severity,
246 Code: gobDiag.Code,
247 CodeHref: gobDiag.CodeHref,
248 Source: DiagnosticSource(gobDiag.Source),
249 Message: gobDiag.Message,
250 Tags: gobDiag.Tags,
251 Related: srcRelated,
252 SuggestedFixes: srcFixes,
253 }
254 srcDiags = append(srcDiags, srcDiag)
255 }
256 return srcDiags
257 }
258
259 // toSourceDiagnostic converts a gobDiagnostic to "source" form.
260 func toSourceDiagnostic(srcAnalyzer *settings.Analyzer, gobDiag *gobDiagnostic) *Diagnostic {
261 var related []protocol.DiagnosticRelatedInformation
262 for _, gobRelated := range gobDiag.Related {
263 related = append(related, protocol.DiagnosticRelatedInformation(gobRelated))
264 }
265
266 diag := &Diagnostic{
267 URI: gobDiag.Location.URI,
268 Range: gobDiag.Location.Range,
269 Severity: srcAnalyzer.Severity(),
270 Code: gobDiag.Code,
271 CodeHref: gobDiag.CodeHref,
272 Source: DiagnosticSource(gobDiag.Source),
273 Message: gobDiag.Message,
274 Related: related,
275 Tags: srcAnalyzer.Tags(),
276 }
277
278 // We cross the set of fixes (whether edit- or command-based)
279 // with the set of kinds, as a single fix may represent more
280 // than one kind of action (e.g. refactor, quickfix, fixall),
281 // each corresponding to a distinct client UI element
282 // or operation.
283 kinds := srcAnalyzer.ActionKinds()
284 if len(kinds) == 0 {
285 kinds = []protocol.CodeActionKind{protocol.QuickFix}
286 }
287
288 var fixes []SuggestedFix
289 for _, fix := range gobDiag.SuggestedFixes {
290 if len(fix.TextEdits) > 0 {
291 // Accumulate edit-based fixes supplied by the diagnostic itself.
292 edits := make(map[protocol.DocumentURI][]protocol.TextEdit)
293 for _, e := range fix.TextEdits {
294 uri := e.Location.URI
295 edits[uri] = append(edits[uri], protocol.TextEdit{
296 Range: e.Location.Range,
297 NewText: string(e.NewText),
298 })
299 }
300 for _, kind := range kinds {
301 fixes = append(fixes, SuggestedFix{
302 Title: fix.Message,
303 Edits: edits,
304 ActionKind: kind,
305 })
306 }
307
308 } else {
309 // Accumulate command-based fixes, whose edits
310 // are not provided by the analyzer but are computed on demand
311 // by logic "adjacent to" the analyzer.
312 //
313 // The analysis.Diagnostic.Category is used as the fix name.
314 cmd := command.NewApplyFixCommand(fix.Message, command.ApplyFixArgs{
315 Fix: diag.Code,
316 Location: gobDiag.Location,
317 })
318 for _, kind := range kinds {
319 fixes = append(fixes, SuggestedFixFromCommand(cmd, kind))
320 }
321
322 // Ensure that the analyzer specifies a category for all its no-edit fixes.
323 // This is asserted by analysistest.RunWithSuggestedFixes, but there
324 // may be gaps in test coverage.
325 if diag.Code == "" || diag.Code == "default" {
326 bug.Reportf("missing Diagnostic.Code: %#v", *diag)
327 }
328 }
329 }
330 diag.SuggestedFixes = fixes
331
332 // If the fixes only delete code, assume that the diagnostic is reporting dead code.
333 if onlyDeletions(diag.SuggestedFixes) {
334 diag.Tags = append(diag.Tags, protocol.Unnecessary)
335 }
336 return diag
337 }
338
339 // onlyDeletions returns true if fixes is non-empty and all of the suggested
340 // fixes are deletions.
341 func onlyDeletions(fixes []SuggestedFix) bool {
342 for _, fix := range fixes {
343 if fix.Command != nil {
344 return false
345 }
346 for _, edits := range fix.Edits {
347 for _, edit := range edits {
348 if edit.NewText != "" {
349 return false
350 }
351 if protocol.ComparePosition(edit.Range.Start, edit.Range.End) == 0 {
352 return false
353 }
354 }
355 }
356 }
357 return len(fixes) > 0
358 }
359
360 func typesCodeHref(linkTarget string, code typesinternal.ErrorCode) string {
361 return BuildLink(linkTarget, "golang.org/x/tools/internal/typesinternal", code.String())
362 }
363
364 // BuildLink constructs a URL with the given target, path, and anchor.
365 func BuildLink(target, path, anchor string) protocol.URI {
366 link := fmt.Sprintf("https://%s/%s", target, path)
367 if anchor == "" {
368 return link
369 }
370 return link + "#" + anchor
371 }
372
373 func parseGoListError(e packages.Error, dir string) (filename string, line, col8 int) {
374 input := e.Pos
375 if input == "" {
376 // No position. Attempt to parse one out of a
377 // go list error of the form "file:line:col:
378 // message" by stripping off the message.
379 input = strings.TrimSpace(e.Msg)
380 if i := strings.Index(input, ": "); i >= 0 {
381 input = input[:i]
382 }
383 }
384
385 filename, line, col8 = splitFileLineCol(input)
386 if !filepath.IsAbs(filename) {
387 filename = filepath.Join(dir, filename)
388 }
389 return filename, line, col8
390 }
391
392 // splitFileLineCol splits s into "filename:line:col",
393 // where line and col consist of decimal digits.
394 func splitFileLineCol(s string) (file string, line, col8 int) {
395 // Beware that the filename may contain colon on Windows.
396
397 // stripColonDigits removes a ":%d" suffix, if any.
398 stripColonDigits := func(s string) (rest string, num int) {
399 if i := strings.LastIndex(s, ":"); i >= 0 {
400 if v, err := strconv.ParseInt(s[i+1:], 10, 32); err == nil {
401 return s[:i], int(v)
402 }
403 }
404 return s, -1
405 }
406
407 // strip col ":%d"
408 s, n1 := stripColonDigits(s)
409 if n1 < 0 {
410 return s, 1, 1 // "filename"
411 }
412
413 // strip line ":%d"
414 s, n2 := stripColonDigits(s)
415 if n2 < 0 {
416 return s, n1, 1 // "filename:line"
417 }
418
419 return s, n2, n1 // "filename:line:col"
420 }
421
422 // parseGoListImportCycleError attempts to parse the given go/packages error as
423 // an import cycle, returning a diagnostic if successful.
424 //
425 // If the error is not detected as an import cycle error, it returns nil, nil.
426 func parseGoListImportCycleError(ctx context.Context, e packages.Error, mp *metadata.Package, fs file.Source) (*Diagnostic, error) {
427 re := regexp.MustCompile(`(.*): import stack: \[(.+)\]`)
428 matches := re.FindStringSubmatch(strings.TrimSpace(e.Msg))
429 if len(matches) < 3 {
430 return nil, nil
431 }
432 msg := matches[1]
433 importList := strings.Split(matches[2], " ")
434 // Since the error is relative to the current package. The import that is causing
435 // the import cycle error is the second one in the list.
436 if len(importList) < 2 {
437 return nil, nil
438 }
439 // Imports have quotation marks around them.
440 circImp := strconv.Quote(importList[1])
441 for _, uri := range mp.CompiledGoFiles {
442 pgf, err := parseGoURI(ctx, fs, uri, parsego.Header)
443 if err != nil {
444 return nil, err
445 }
446 // Search file imports for the import that is causing the import cycle.
447 for _, imp := range pgf.File.Imports {
448 if imp.Path.Value == circImp {
449 rng, err := pgf.NodeRange(imp)
450 if err != nil {
451 return nil, nil
452 }
453
454 return &Diagnostic{
455 URI: pgf.URI,
456 Range: rng,
457 Severity: protocol.SeverityError,
458 Source: ListError,
459 Message: msg,
460 }, nil
461 }
462 }
463 }
464 return nil, nil
465 }
466
467 // parseGoURI is a helper to parse the Go file at the given URI from the file
468 // source fs. The resulting syntax and token.File belong to an ephemeral,
469 // encapsulated FileSet, so this file stands only on its own: it's not suitable
470 // to use in a list of file of a package, for example.
471 //
472 // It returns an error if the file could not be read.
473 //
474 // TODO(rfindley): eliminate this helper.
475 func parseGoURI(ctx context.Context, fs file.Source, uri protocol.DocumentURI, mode parser.Mode) (*parsego.File, error) {
476 fh, err := fs.ReadFile(ctx, uri)
477 if err != nil {
478 return nil, err
479 }
480 return parseGoImpl(ctx, token.NewFileSet(), fh, mode, false)
481 }
482
483 // parseModURI is a helper to parse the Mod file at the given URI from the file
484 // source fs.
485 //
486 // It returns an error if the file could not be read.
487 func parseModURI(ctx context.Context, fs file.Source, uri protocol.DocumentURI) (*ParsedModule, error) {
488 fh, err := fs.ReadFile(ctx, uri)
489 if err != nil {
490 return nil, err
491 }
492 return parseModImpl(ctx, fh)
493 }