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