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

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

Issue 134780043: code review 134780043: go.tools/cmd/vet: detect suspicious shifts
Patch Set: diff -r 067839d7eb9b000c390a79f2f24a5b0e6975f574 https://code.google.com/p/go.tools Created 9 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
OLDNEW
(Empty)
1 // Copyright 2014 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 suspicious shifts.
7 */
8
9 package main
10
11 import (
12 "go/ast"
13 "go/token"
14
15 "code.google.com/p/go.tools/go/exact"
16 "code.google.com/p/go.tools/go/types"
17 )
18
19 func init() {
20 register("shift",
21 "check for suspicious shifts",
22 checkShift,
23 binaryExpr, assignStmt)
24 }
25
26 func checkShift(f *File, node ast.Node) {
27 switch node := node.(type) {
28 case *ast.BinaryExpr:
29 if node.Op == token.SHL || node.Op == token.SHR {
30 checkSuspiciousShift(f, node, node.X, node.Y)
31 }
32 case *ast.AssignStmt:
33 if len(node.Lhs) != 1 || len(node.Rhs) != 1 {
34 return
35 }
36 if node.Tok == token.SHL_ASSIGN || node.Tok == token.SHR_ASSIGN {
37 checkSuspiciousShift(f, node, node.Lhs[0], node.Rhs[0])
38 }
39 }
40 }
41
42 // checkSuspiciousShift checks if shift or shift-assign operations shift by more
43 // than the length of the underlying variable.
44 func checkSuspiciousShift(f *File, node ast.Node, x, y ast.Expr) {
dsymonds 2014/08/27 23:56:39 checkLongShift?
45 v := f.pkg.types[y].Value
46 if v == nil {
47 return
48 }
49 amt, ok := exact.Int64Val(v)
50 if !ok {
51 return
52 }
53 t := f.pkg.types[x].Type
54 if t == nil {
55 return
56 }
57 b, ok := t.Underlying().(*types.Basic)
58 if !ok {
59 return
60 }
61 var size int64
62 switch b.Kind() {
63 case types.Uint8, types.Int8:
64 size = 8
65 case types.Uint16, types.Int16:
66 size = 16
67 case types.Uint32, types.Int32:
68 size = 32
69 case types.Uint64, types.Int64:
70 size = 64
71 default:
72 return
73 }
74 if amt >= size {
75 ident := f.gofmt(x)
76 f.Badf(node.Pos(), "%s has size %d but is shifted by %d", ident, size, amt)
77 }
78 }
OLDNEW
« no previous file with comments | « cmd/vet/doc.go ('k') | cmd/vet/testdata/shift.go » ('j') | cmd/vet/testdata/shift.go » ('J')

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