| 1 |
package sa1012 |
| 2 |
|
| 3 |
import ( |
| 4 |
"go/ast" |
| 5 |
"go/types" |
| 6 |
|
| 7 |
"honnef.co/go/tools/analysis/code" |
| 8 |
"honnef.co/go/tools/analysis/edit" |
| 9 |
"honnef.co/go/tools/analysis/lint" |
| 10 |
"honnef.co/go/tools/analysis/report" |
| 11 |
"honnef.co/go/tools/go/types/typeutil" |
| 12 |
"honnef.co/go/tools/pattern" |
| 13 |
|
| 14 |
"golang.org/x/tools/go/analysis" |
| 15 |
) |
| 16 |
|
| 17 |
var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ |
| 18 |
Analyzer: &analysis.Analyzer{ |
| 19 |
Name: "SA1012", |
| 20 |
Run: run, |
| 21 |
Requires: code.RequiredAnalyzers, |
| 22 |
}, |
| 23 |
Doc: &lint.RawDocumentation{ |
| 24 |
Title: `A nil \'context.Context\' is being passed to a function, consider using \'context.TODO\' instead`, |
| 25 |
Since: "2017.1", |
| 26 |
Severity: lint.SeverityWarning, |
| 27 |
MergeIf: lint.MergeIfAny, |
| 28 |
}, |
| 29 |
}) |
| 30 |
|
| 31 |
var Analyzer = SCAnalyzer.Analyzer |
| 32 |
|
| 33 |
var checkNilContextQ = pattern.MustParse(`(CallExpr fun@(Symbol _) (Builtin "nil"):_)`) |
| 34 |
|
| 35 |
func run(pass *analysis.Pass) (any, error) { |
| 36 |
todo := &ast.CallExpr{ |
| 37 |
Fun: edit.Selector("context", "TODO"), |
| 38 |
} |
| 39 |
bg := &ast.CallExpr{ |
| 40 |
Fun: edit.Selector("context", "Background"), |
| 41 |
} |
| 42 |
for node, m := range code.Matches(pass, checkNilContextQ) { |
| 43 |
call := node.(*ast.CallExpr) |
| 44 |
fun, ok := m.State["fun"].(*types.Func) |
| 45 |
if !ok { |
| 46 |
// it might also be a builtin |
| 47 |
continue |
| 48 |
} |
| 49 |
sig := fun.Type().(*types.Signature) |
| 50 |
if sig.Params().Len() == 0 { |
| 51 |
// Our CallExpr might've matched a method expression, like |
| 52 |
// (*T).Foo(nil) – here, nil isn't the first argument of |
| 53 |
// the Foo method, but the method receiver. |
| 54 |
continue |
| 55 |
} |
| 56 |
if !typeutil.IsTypeWithName(sig.Params().At(0).Type(), "context.Context") { |
| 57 |
continue |
| 58 |
} |
| 59 |
report.Report(pass, call.Args[0], |
| 60 |
"do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use", report.Fixes( |
| 61 |
edit.Fix("Use context.TODO", edit.ReplaceWithNode(pass.Fset, call.Args[0], todo)), |
| 62 |
edit.Fix("Use context.Background", edit.ReplaceWithNode(pass.Fset, call.Args[0], bg)))) |
| 63 |
} |
| 64 |
return nil, nil |
| 65 |
} |