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.
5 // Package shift defines an Analyzer that checks for shifts that exceed
6 // the width of an integer.
9 // TODO(adonovan): integrate with ctrflow (CFG-based) dead code analysis. May
10 // have impedance mismatch due to its (non-)treatment of constant
11 // expressions (such as runtime.GOARCH=="386").
18 "golang.org/x/tools/go/analysis"
19 "golang.org/x/tools/go/analysis/passes/inspect"
20 "golang.org/x/tools/go/analysis/passes/internal/analysisutil"
21 "golang.org/x/tools/go/ast/inspector"
24 const Doc = "check for shifts that equal or exceed the width of the integer"
26 var Analyzer = &analysis.Analyzer{
29 Requires: []*analysis.Analyzer{inspect.Analyzer},
33 func run(pass *analysis.Pass) (interface{}, error) {
34 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
36 // Do a complete pass to compute dead nodes.
37 dead := make(map[ast.Node]bool)
38 nodeFilter := []ast.Node{
40 (*ast.SwitchStmt)(nil),
42 inspect.Preorder(nodeFilter, func(n ast.Node) {
43 // TODO(adonovan): move updateDead into this file.
44 updateDead(pass.TypesInfo, dead, n)
47 nodeFilter = []ast.Node{
48 (*ast.AssignStmt)(nil),
49 (*ast.BinaryExpr)(nil),
51 inspect.Preorder(nodeFilter, func(node ast.Node) {
53 // Skip shift checks on unreachable nodes.
57 switch node := node.(type) {
59 if node.Op == token.SHL || node.Op == token.SHR {
60 checkLongShift(pass, node, node.X, node.Y)
63 if len(node.Lhs) != 1 || len(node.Rhs) != 1 {
66 if node.Tok == token.SHL_ASSIGN || node.Tok == token.SHR_ASSIGN {
67 checkLongShift(pass, node, node.Lhs[0], node.Rhs[0])
74 // checkLongShift checks if shift or shift-assign operations shift by more than
75 // the length of the underlying variable.
76 func checkLongShift(pass *analysis.Pass, node ast.Node, x, y ast.Expr) {
77 if pass.TypesInfo.Types[x].Value != nil {
78 // Ignore shifts of constants.
79 // These are frequently used for bit-twiddling tricks
80 // like ^uint(0) >> 63 for 32/64 bit detection and compatibility.
84 v := pass.TypesInfo.Types[y].Value
88 amt, ok := constant.Int64Val(v)
92 t := pass.TypesInfo.Types[x].Type
96 size := 8 * pass.TypesSizes.Sizeof(t)
98 ident := analysisutil.Format(pass.Fset, x)
99 pass.ReportRangef(node, "%s (%d bits) too small for shift of %d", ident, size, amt)