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