Debian Codegraph @

gopls/internal/analysis/noresultvalues/noresultvalues.go

raw symbols SCIP
1 // Copyright 2020 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 noresultvalues
6
7 import (
8 "go/ast"
9 "go/token"
10 "strings"
11
12 _ "embed"
13
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/go/analysis/passes/inspect"
16 "golang.org/x/tools/go/ast/inspector"
17 "golang.org/x/tools/gopls/internal/util/cursorutil"
18 "golang.org/x/tools/internal/analysis/analyzerutil"
19 "golang.org/x/tools/internal/typesinternal"
20 )
21
22 //go:embed doc.go
23 var doc string
24
25 var Analyzer = &analysis.Analyzer{
26 Name: "noresultvalues",
27 Doc: analyzerutil.MustExtractDoc(doc, "noresultvalues"),
28 Requires: []*analysis.Analyzer{inspect.Analyzer},
29 Run: run,
30 RunDespiteErrors: true,
31 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/noresultvalues",
32 }
33
34 func run(pass *analysis.Pass) (any, error) {
35 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
36
37 for _, typErr := range pass.TypeErrors {
38 if !fixesError(typErr.Msg) {
39 continue // irrelevant error
40 }
41 _, start, end, ok := typesinternal.ErrorCodeStartEnd(typErr)
42 if !ok {
43 continue // can't get position info
44 }
45 curErr, ok := inspect.Root().FindByPos(start, end)
46 if !ok {
47 continue // can't find errant node
48 }
49 // Find first enclosing return statement, if any.
50 ret, _ := cursorutil.FirstEnclosing[*ast.ReturnStmt](curErr)
51 if ret != nil {
52 pass.Report(analysis.Diagnostic{
53 Pos: start,
54 End: end,
55 Message: typErr.Msg,
56 SuggestedFixes: []analysis.SuggestedFix{{
57 Message: "Delete return values",
58 TextEdits: []analysis.TextEdit{{
59 Pos: ret.Pos() + token.Pos(len("return")),
60 End: ret.End(),
61 }},
62 }},
63 })
64 }
65 }
66 return nil, nil
67 }
68
69 func fixesError(msg string) bool {
70 return msg == "no result values expected" ||
71 strings.HasPrefix(msg, "too many return values") && strings.Contains(msg, "want ()")
72 }