Debian Codegraph @

staticcheck/sa4017/sa4017.go

raw
1 package sa4017
2
3 import (
4 "fmt"
5 "go/types"
6
7 "honnef.co/go/tools/analysis/code"
8 "honnef.co/go/tools/analysis/facts/purity"
9 "honnef.co/go/tools/analysis/lint"
10 "honnef.co/go/tools/analysis/report"
11 "honnef.co/go/tools/go/ir"
12 "honnef.co/go/tools/go/ir/irutil"
13 "honnef.co/go/tools/go/types/typeutil"
14 "honnef.co/go/tools/internal/passes/buildir"
15
16 "golang.org/x/tools/go/analysis"
17 )
18
19 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
20 Analyzer: &analysis.Analyzer{
21 Name: "SA4017",
22 Run: run,
23 Requires: []*analysis.Analyzer{buildir.Analyzer, purity.Analyzer},
24 },
25 Doc: &lint.RawDocumentation{
26 Title: `Discarding the return values of a function without side effects, making the call pointless`,
27 Since: "2017.1",
28 Severity: lint.SeverityWarning,
29 MergeIf: lint.MergeIfAll,
30 },
31 })
32
33 var Analyzer = SCAnalyzer.Analyzer
34
35 func run(pass *analysis.Pass) (any, error) {
36 pure := pass.ResultOf[purity.Analyzer].(purity.Result)
37
38 fnLoop:
39 for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs {
40 if code.IsInTest(pass, fn) {
41 params := fn.Signature.Params()
42 for param := range params.Variables() {
43 if typeutil.IsPointerToTypeWithName(param.Type(), "testing.B") {
44 // Ignore discarded pure functions in code related
45 // to benchmarks. Instead of matching BenchmarkFoo
46 // functions, we match any function accepting a
47 // *testing.B. Benchmarks sometimes call generic
48 // functions for doing the actual work, and
49 // checking for the parameter is a lot easier and
50 // faster than analyzing call trees.
51 continue fnLoop
52 }
53 }
54 }
55
56 for _, b := range fn.Blocks {
57 for _, ins := range b.Instrs {
58 ins, ok := ins.(*ir.Call)
59 if !ok {
60 continue
61 }
62 refs := ins.Referrers()
63 if refs == nil || len(irutil.FilterDebug(*refs)) > 0 {
64 continue
65 }
66
67 callee := ins.Common().StaticCallee()
68 if callee == nil {
69 continue
70 }
71 if callee.Object() == nil {
72 // TODO(dh): support anonymous functions
73 continue
74 }
75 if _, ok := pure[callee.Object().(*types.Func)]; ok {
76 if pass.Pkg.Path() == "fmt_test" && callee.Object().(*types.Func).FullName() == "fmt.Sprintf" {
77 // special case for benchmarks in the fmt package
78 continue
79 }
80 report.Report(pass, ins, fmt.Sprintf("%s doesn't have side effects and its return value is ignored", callee.Object().Name()))
81 }
82 }
83 }
84 }
85 return nil, nil
86 }