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