Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(257)

Side by Side Diff: cmd/vet/nilfunc.go

Issue 13102043: code review 13102043: go.tools/cmd/vet: detect useless function comparisons (Closed)
Patch Set: diff -r d47ca4bb6e48 https://code.google.com/p/go.tools Created 10 years, 7 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « cmd/vet/main.go ('k') | cmd/vet/testdata/nilfunc.go » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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 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.idents[v]
45 case *ast.SelectorExpr:
46 obj = f.pkg.idents[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.Nam e(), 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] == types.Typ[types.UntypedNil]
63 }
OLDNEW
« no previous file with comments | « cmd/vet/main.go ('k') | cmd/vet/testdata/nilfunc.go » ('j') | no next file with comments »

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b