1 // Copyright 2013 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.
5 // Package nilfunc defines an Analyzer that checks for useless
6 // comparisons against nil.
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/go/analysis/passes/inspect"
16 "golang.org/x/tools/go/ast/inspector"
19 const Doc = `check for useless comparisons between functions and nil
21 A useless comparison is one like f == nil as opposed to f() == nil.`
23 var Analyzer = &analysis.Analyzer{
26 Requires: []*analysis.Analyzer{inspect.Analyzer},
30 func run(pass *analysis.Pass) (interface{}, error) {
31 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
33 nodeFilter := []ast.Node{
34 (*ast.BinaryExpr)(nil),
36 inspect.Preorder(nodeFilter, func(n ast.Node) {
37 e := n.(*ast.BinaryExpr)
39 // Only want == or != comparisons.
40 if e.Op != token.EQL && e.Op != token.NEQ {
44 // Only want comparisons with a nil identifier on one side.
47 case pass.TypesInfo.Types[e.X].IsNil():
49 case pass.TypesInfo.Types[e.Y].IsNil():
55 // Only want identifiers or selector expressions.
57 switch v := e2.(type) {
59 obj = pass.TypesInfo.Uses[v]
60 case *ast.SelectorExpr:
61 obj = pass.TypesInfo.Uses[v.Sel]
66 // Only want functions.
67 if _, ok := obj.(*types.Func); !ok {
71 pass.ReportRangef(e, "comparison of function %v %v nil is always %v", obj.Name(), e.Op, e.Op == token.NEQ)