~vtuson/scopecreator/twitter-template

« back to all changes in this revision

Viewing changes to src/go/src/code.google.com/p/go.tools/cmd/vet/nilfunc.go

  • Committer: Victor Palau
  • Date: 2015-03-11 14:24:42 UTC
  • Revision ID: vtuson@gmail.com-20150311142442-f2pxp111c8ynv232
public release

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
16
        "code.google.com/p/go.tools/go/types"
 
17
)
 
18
 
 
19
func (f *File) checkNilFuncComparison(e *ast.BinaryExpr) {
 
20
        if !vet("nilfunc") {
 
21
                return
 
22
        }
 
23
 
 
24
        // Only want == or != comparisons.
 
25
        if e.Op != token.EQL && e.Op != token.NEQ {
 
26
                return
 
27
        }
 
28
 
 
29
        // Only want comparisons with a nil identifier on one side.
 
30
        var e2 ast.Expr
 
31
        switch {
 
32
        case f.isNil(e.X):
 
33
                e2 = e.Y
 
34
        case f.isNil(e.Y):
 
35
                e2 = e.X
 
36
        default:
 
37
                return
 
38
        }
 
39
 
 
40
        // Only want identifiers or selector expressions.
 
41
        var obj types.Object
 
42
        switch v := e2.(type) {
 
43
        case *ast.Ident:
 
44
                obj = f.pkg.uses[v]
 
45
        case *ast.SelectorExpr:
 
46
                obj = f.pkg.uses[v.Sel]
 
47
        default:
 
48
                return
 
49
        }
 
50
 
 
51
        // Only want functions.
 
52
        if _, ok := obj.(*types.Func); !ok {
 
53
                return
 
54
        }
 
55
 
 
56
        f.Badf(e.Pos(), "comparison of function %v %v nil is always %v", obj.Name(), e.Op, e.Op == token.NEQ)
 
57
}
 
58
 
 
59
// isNil reports whether the provided expression is the built-in nil
 
60
// identifier.
 
61
func (f *File) isNil(e ast.Expr) bool {
 
62
        return f.pkg.types[e].Type == types.Typ[types.UntypedNil]
 
63
}