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