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