]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/precedence.rs
Auto merge of #3845 - euclio:unused-comments, r=phansch
[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 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 #[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     fn name(&self) -> &'static str {
40         "Precedence"
41     }
42 }
43
44 impl EarlyLintPass for Precedence {
45     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
46         if in_macro(expr.span) {
47             return;
48         }
49
50         if let ExprKind::Binary(Spanned { node: op, .. }, ref left, ref right) = expr.node {
51             let span_sugg = |expr: &Expr, sugg, appl| {
52                 span_lint_and_sugg(
53                     cx,
54                     PRECEDENCE,
55                     expr.span,
56                     "operator precedence can trip the unwary",
57                     "consider parenthesizing your expression",
58                     sugg,
59                     appl,
60                 );
61             };
62
63             if !is_bit_op(op) {
64                 return;
65             }
66             let mut applicability = Applicability::MachineApplicable;
67             match (is_arith_expr(left), is_arith_expr(right)) {
68                 (true, true) => {
69                     let sugg = format!(
70                         "({}) {} ({})",
71                         snippet_with_applicability(cx, left.span, "..", &mut applicability),
72                         op.to_string(),
73                         snippet_with_applicability(cx, right.span, "..", &mut applicability)
74                     );
75                     span_sugg(expr, sugg, applicability);
76                 },
77                 (true, false) => {
78                     let sugg = format!(
79                         "({}) {} {}",
80                         snippet_with_applicability(cx, left.span, "..", &mut applicability),
81                         op.to_string(),
82                         snippet_with_applicability(cx, right.span, "..", &mut applicability)
83                     );
84                     span_sugg(expr, sugg, applicability);
85                 },
86                 (false, true) => {
87                     let sugg = format!(
88                         "{} {} ({})",
89                         snippet_with_applicability(cx, left.span, "..", &mut applicability),
90                         op.to_string(),
91                         snippet_with_applicability(cx, right.span, "..", &mut applicability)
92                     );
93                     span_sugg(expr, sugg, applicability);
94                 },
95                 (false, false) => (),
96             }
97         }
98
99         if let ExprKind::Unary(UnOp::Neg, ref rhs) = expr.node {
100             if let ExprKind::MethodCall(_, ref args) = rhs.node {
101                 if let Some(slf) = args.first() {
102                     if let ExprKind::Lit(ref lit) = slf.node {
103                         match lit.node {
104                             LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => {
105                                 let mut applicability = Applicability::MachineApplicable;
106                                 span_lint_and_sugg(
107                                     cx,
108                                     PRECEDENCE,
109                                     expr.span,
110                                     "unary minus has lower precedence than method call",
111                                     "consider adding parentheses to clarify your intent",
112                                     format!(
113                                         "-({})",
114                                         snippet_with_applicability(cx, rhs.span, "..", &mut applicability)
115                                     ),
116                                     applicability,
117                                 );
118                             },
119                             _ => (),
120                         }
121                     }
122                 }
123             }
124         }
125     }
126 }
127
128 fn is_arith_expr(expr: &Expr) -> bool {
129     match expr.node {
130         ExprKind::Binary(Spanned { node: op, .. }, _, _) => is_arith_op(op),
131         _ => false,
132     }
133 }
134
135 fn is_bit_op(op: BinOpKind) -> bool {
136     use syntax::ast::BinOpKind::*;
137     match op {
138         BitXor | BitAnd | BitOr | Shl | Shr => true,
139         _ => false,
140     }
141 }
142
143 fn is_arith_op(op: BinOpKind) -> bool {
144     use syntax::ast::BinOpKind::*;
145     match op {
146         Add | Sub | Mul | Div | Rem => true,
147         _ => false,
148     }
149 }