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