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