github.com/v2fly/tools@v0.100.0/internal/lsp/analysis/noresultvalues/noresultvalues.go (about) 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 defines an Analyzer that applies suggested fixes 6 // to errors of the type "no result values expected". 7 package noresultvalues 8 9 import ( 10 "bytes" 11 "go/ast" 12 "go/format" 13 14 "github.com/v2fly/tools/go/analysis" 15 "github.com/v2fly/tools/go/analysis/passes/inspect" 16 "github.com/v2fly/tools/go/ast/inspector" 17 "github.com/v2fly/tools/internal/analysisinternal" 18 ) 19 20 const Doc = `suggested fixes for "no result values expected" 21 22 This checker provides suggested fixes for type errors of the 23 type "no result values expected". For example: 24 func z() { return nil } 25 will turn into 26 func z() { return } 27 ` 28 29 var Analyzer = &analysis.Analyzer{ 30 Name: string(analysisinternal.NoResultValues), 31 Doc: Doc, 32 Requires: []*analysis.Analyzer{inspect.Analyzer}, 33 Run: run, 34 RunDespiteErrors: true, 35 } 36 37 func run(pass *analysis.Pass) (interface{}, error) { 38 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) 39 errors := analysisinternal.GetTypeErrors(pass) 40 41 nodeFilter := []ast.Node{(*ast.ReturnStmt)(nil)} 42 inspect.Preorder(nodeFilter, func(n ast.Node) { 43 retStmt, _ := n.(*ast.ReturnStmt) 44 45 var file *ast.File 46 for _, f := range pass.Files { 47 if f.Pos() <= retStmt.Pos() && retStmt.Pos() < f.End() { 48 file = f 49 break 50 } 51 } 52 if file == nil { 53 return 54 } 55 56 for _, err := range errors { 57 if !FixesError(err.Msg) { 58 continue 59 } 60 if retStmt.Pos() >= err.Pos || err.Pos >= retStmt.End() { 61 continue 62 } 63 var buf bytes.Buffer 64 if err := format.Node(&buf, pass.Fset, file); err != nil { 65 continue 66 } 67 pass.Report(analysis.Diagnostic{ 68 Pos: err.Pos, 69 End: analysisinternal.TypeErrorEndPos(pass.Fset, buf.Bytes(), err.Pos), 70 Message: err.Msg, 71 SuggestedFixes: []analysis.SuggestedFix{{ 72 Message: "Delete return values", 73 TextEdits: []analysis.TextEdit{{ 74 Pos: retStmt.Pos(), 75 End: retStmt.End(), 76 NewText: []byte("return"), 77 }}, 78 }}, 79 }) 80 } 81 }) 82 return nil, nil 83 } 84 85 func FixesError(msg string) bool { 86 return msg == "no result values expected" 87 }