]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/precedence.rs
split clippy into lints, plugin and cargo-clippy
[rust.git] / clippy_lints / src / precedence.rs
1 use rustc::lint::*;
2 use syntax::ast::*;
3 use syntax::codemap::Spanned;
4 use utils::{span_lint, snippet};
5
6 /// **What it does:** This lint checks for operations where precedence may be unclear and suggests to add parentheses. Currently it catches the following:
7 /// * mixed usage of arithmetic and bit shifting/combining operators without parentheses
8 /// * a "negative" numeric literal (which is really a unary `-` followed by a numeric literal) followed by a method call
9 ///
10 /// **Why is this bad?** Because not everyone knows the precedence of those operators by heart, so expressions like these may trip others trying to reason about the code.
11 ///
12 /// **Known problems:** None
13 ///
14 /// **Examples:**
15 /// * `1 << 2 + 3` equals 32, while `(1 << 2) + 3` equals 7
16 /// * `-1i32.abs()` equals -1, while `(-1i32).abs()` equals 1
17 declare_lint! {
18     pub PRECEDENCE, Warn,
19     "catches operations where precedence may be unclear. See the wiki for a \
20      list of cases caught"
21 }
22
23 #[derive(Copy,Clone)]
24 pub struct Precedence;
25
26 impl LintPass for Precedence {
27     fn get_lints(&self) -> LintArray {
28         lint_array!(PRECEDENCE)
29     }
30 }
31
32 impl EarlyLintPass for Precedence {
33     fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
34         if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
35             if !is_bit_op(op) {
36                 return;
37             }
38             match (is_arith_expr(left), is_arith_expr(right)) {
39                 (true, true) => {
40                     span_lint(cx,
41                               PRECEDENCE,
42                               expr.span,
43                               &format!("operator precedence can trip the unwary. Consider parenthesizing your \
44                                         expression:`({}) {} ({})`",
45                                        snippet(cx, left.span, ".."),
46                                        op.to_string(),
47                                        snippet(cx, right.span, "..")));
48                 }
49                 (true, false) => {
50                     span_lint(cx,
51                               PRECEDENCE,
52                               expr.span,
53                               &format!("operator precedence can trip the unwary. Consider parenthesizing your \
54                                         expression:`({}) {} {}`",
55                                        snippet(cx, left.span, ".."),
56                                        op.to_string(),
57                                        snippet(cx, right.span, "..")));
58                 }
59                 (false, true) => {
60                     span_lint(cx,
61                               PRECEDENCE,
62                               expr.span,
63                               &format!("operator precedence can trip the unwary. Consider parenthesizing your \
64                                         expression:`{} {} ({})`",
65                                        snippet(cx, left.span, ".."),
66                                        op.to_string(),
67                                        snippet(cx, right.span, "..")));
68                 }
69                 _ => (),
70             }
71         }
72
73         if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.node {
74             if let ExprKind::MethodCall(_, _, ref args) = rhs.node {
75                 if let Some(slf) = args.first() {
76                     if let ExprKind::Lit(ref lit) = slf.node {
77                         match lit.node {
78                             LitKind::Int(..) |
79                             LitKind::Float(..) |
80                             LitKind::FloatUnsuffixed(..) => {
81                                 span_lint(cx,
82                                           PRECEDENCE,
83                                           expr.span,
84                                           &format!("unary minus has lower precedence than method call. Consider \
85                                                     adding parentheses to clarify your intent: -({})",
86                                                    snippet(cx, rhs.span, "..")));
87                             }
88                             _ => (),
89                         }
90                     }
91                 }
92             }
93         }
94     }
95 }
96
97 fn is_arith_expr(expr: &Expr) -> bool {
98     match expr.node {
99         ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
100         _ => false,
101     }
102 }
103
104 fn is_bit_op(op: BinOpKind) -> bool {
105     use syntax::ast::BinOpKind::*;
106     match op {
107         BitXor | BitAnd | BitOr | Shl | Shr => true,
108         _ => false,
109     }
110 }
111
112 fn is_arith_op(op: BinOpKind) -> bool {
113     use syntax::ast::BinOpKind::*;
114     match op {
115         Add | Sub | Mul | Div | Rem => true,
116         _ => false,
117     }
118 }