github.com/likebike/go--@v0.0.0-20190911215757-0bd925d16e96/go/src/cmd/vet/nilfunc.go (about)

     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.
     4  
     5  /*
     6  This file contains the code to check for useless function comparisons.
     7  A useless comparison is one like f == nil as opposed to f() == nil.
     8  */
     9  
    10  package main
    11  
    12  import (
    13  	"go/ast"
    14  	"go/token"
    15  	"go/types"
    16  )
    17  
    18  func init() {
    19  	register("nilfunc",
    20  		"check for comparisons between functions and nil",
    21  		checkNilFuncComparison,
    22  		binaryExpr)
    23  }
    24  
    25  func checkNilFuncComparison(f *File, node ast.Node) {
    26  	e := node.(*ast.BinaryExpr)
    27  
    28  	// Only want == or != comparisons.
    29  	if e.Op != token.EQL && e.Op != token.NEQ {
    30  		return
    31  	}
    32  
    33  	// Only want comparisons with a nil identifier on one side.
    34  	var e2 ast.Expr
    35  	switch {
    36  	case f.isNil(e.X):
    37  		e2 = e.Y
    38  	case f.isNil(e.Y):
    39  		e2 = e.X
    40  	default:
    41  		return
    42  	}
    43  
    44  	// Only want identifiers or selector expressions.
    45  	var obj types.Object
    46  	switch v := e2.(type) {
    47  	case *ast.Ident:
    48  		obj = f.pkg.uses[v]
    49  	case *ast.SelectorExpr:
    50  		obj = f.pkg.uses[v.Sel]
    51  	default:
    52  		return
    53  	}
    54  
    55  	// Only want functions.
    56  	if _, ok := obj.(*types.Func); !ok {
    57  		return
    58  	}
    59  
    60  	f.Badf(e.Pos(), "comparison of function %v %v nil is always %v", obj.Name(), e.Op, e.Op == token.NEQ)
    61  }
    62  
    63  // isNil reports whether the provided expression is the built-in nil
    64  // identifier.
    65  func (f *File) isNil(e ast.Expr) bool {
    66  	return f.pkg.types[e].Type == types.Typ[types.UntypedNil]
    67  }