]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eq_op.rs
Merge pull request #3303 from shssoichiro/3069-unnecessary-fold-pattern-guard
[rust.git] / clippy_lints / src / eq_op.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
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::utils::{in_macro, implements_trait, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then, SpanlessEq};
15 use crate::rustc_errors::Applicability;
16
17 /// **What it does:** Checks for equal operands to comparison, logical and
18 /// bitwise, difference and division binary operators (`==`, `>`, etc., `&&`,
19 /// `||`, `&`, `|`, `^`, `-` and `/`).
20 ///
21 /// **Why is this bad?** This is usually just a typo or a copy and paste error.
22 ///
23 /// **Known problems:** False negatives: We had some false positives regarding
24 /// calls (notably [racer](https://github.com/phildawes/racer) had one instance
25 /// of `x.pop() && x.pop()`), so we removed matching any function or method
26 /// calls. We may introduce a whitelist of known pure functions in the future.
27 ///
28 /// **Example:**
29 /// ```rust
30 /// x + 1 == x + 1
31 /// ```
32 declare_clippy_lint! {
33     pub EQ_OP,
34     correctness,
35     "equal operands on both sides of a comparison or bitwise combination (e.g. `x == x`)"
36 }
37
38 /// **What it does:** Checks for arguments to `==` which have their address
39 /// taken to satisfy a bound
40 /// and suggests to dereference the other argument instead
41 ///
42 /// **Why is this bad?** It is more idiomatic to dereference the other argument.
43 ///
44 /// **Known problems:** None
45 ///
46 /// **Example:**
47 /// ```rust
48 /// &x == y
49 /// ```
50 declare_clippy_lint! {
51     pub OP_REF,
52     style,
53     "taking a reference to satisfy the type constraints on `==`"
54 }
55
56 #[derive(Copy, Clone)]
57 pub struct EqOp;
58
59 impl LintPass for EqOp {
60     fn get_lints(&self) -> LintArray {
61         lint_array!(EQ_OP, OP_REF)
62     }
63 }
64
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp {
66     #[allow(clippy::similar_names)]
67     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
68         if let ExprKind::Binary(op, ref left, ref right) = e.node {
69             if in_macro(e.span) {
70                 return;
71             }
72             if is_valid_operator(op) && SpanlessEq::new(cx).ignore_fn().eq_expr(left, right) {
73                 span_lint(
74                     cx,
75                     EQ_OP,
76                     e.span,
77                     &format!("equal expressions as operands to `{}`", op.node.as_str()),
78                 );
79                 return;
80             }
81             let (trait_id, requires_ref) = match op.node {
82                 BinOpKind::Add => (cx.tcx.lang_items().add_trait(), false),
83                 BinOpKind::Sub => (cx.tcx.lang_items().sub_trait(), false),
84                 BinOpKind::Mul => (cx.tcx.lang_items().mul_trait(), false),
85                 BinOpKind::Div => (cx.tcx.lang_items().div_trait(), false),
86                 BinOpKind::Rem => (cx.tcx.lang_items().rem_trait(), false),
87                 // don't lint short circuiting ops
88                 BinOpKind::And | BinOpKind::Or => return,
89                 BinOpKind::BitXor => (cx.tcx.lang_items().bitxor_trait(), false),
90                 BinOpKind::BitAnd => (cx.tcx.lang_items().bitand_trait(), false),
91                 BinOpKind::BitOr => (cx.tcx.lang_items().bitor_trait(), false),
92                 BinOpKind::Shl => (cx.tcx.lang_items().shl_trait(), false),
93                 BinOpKind::Shr => (cx.tcx.lang_items().shr_trait(), false),
94                 BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true),
95                 BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => (cx.tcx.lang_items().ord_trait(), true),
96             };
97             if let Some(trait_id) = trait_id {
98                 #[allow(clippy::match_same_arms)]
99                 match (&left.node, &right.node) {
100                     // do not suggest to dereference literals
101                     (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {},
102                     // &foo == &bar
103                     (&ExprKind::AddrOf(_, ref l), &ExprKind::AddrOf(_, ref r)) => {
104                         let lty = cx.tables.expr_ty(l);
105                         let rty = cx.tables.expr_ty(r);
106                         let lcpy = is_copy(cx, lty);
107                         let rcpy = is_copy(cx, rty);
108                         // either operator autorefs or both args are copyable
109                         if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) {
110                             span_lint_and_then(
111                                 cx,
112                                 OP_REF,
113                                 e.span,
114                                 "needlessly taken reference of both operands",
115                                 |db| {
116                                     let lsnip = snippet(cx, l.span, "...").to_string();
117                                     let rsnip = snippet(cx, r.span, "...").to_string();
118                                     multispan_sugg(
119                                         db,
120                                         "use the values directly".to_string(),
121                                         vec![(left.span, lsnip), (right.span, rsnip)],
122                                     );
123                                 },
124                             )
125                         } else if lcpy && !rcpy && implements_trait(cx, lty, trait_id, &[cx.tables.expr_ty(right).into()]) {
126                             span_lint_and_then(cx, OP_REF, e.span, "needlessly taken reference of left operand", |db| {
127                                 let lsnip = snippet(cx, l.span, "...").to_string();
128                                 db.span_suggestion_with_applicability(
129                                     left.span,
130                                     "use the left value directly",
131                                     lsnip,
132                                     Applicability::MachineApplicable, // snippet
133                                 );
134                             })
135                         } else if !lcpy && rcpy && implements_trait(cx, cx.tables.expr_ty(left), trait_id, &[rty.into()]) {
136                             span_lint_and_then(
137                                 cx,
138                                 OP_REF,
139                                 e.span,
140                                 "needlessly taken reference of right operand",
141                                 |db| {
142                                     let rsnip = snippet(cx, r.span, "...").to_string();
143                                     db.span_suggestion_with_applicability(
144                                         right.span,
145                                         "use the right value directly",
146                                         rsnip,
147                                         Applicability::MachineApplicable, // snippet
148                                     );
149                                 },
150                             )
151                         }
152                     },
153                     // &foo == bar
154                     (&ExprKind::AddrOf(_, ref l), _) => {
155                         let lty = cx.tables.expr_ty(l);
156                         let lcpy = is_copy(cx, lty);
157                         if (requires_ref || lcpy) && implements_trait(cx, lty, trait_id, &[cx.tables.expr_ty(right).into()]) {
158                             span_lint_and_then(cx, OP_REF, e.span, "needlessly taken reference of left operand", |db| {
159                                 let lsnip = snippet(cx, l.span, "...").to_string();
160                                 db.span_suggestion_with_applicability(
161                                     left.span,
162                                     "use the left value directly",
163                                     lsnip,
164                                     Applicability::MachineApplicable, // snippet
165                                 );
166                             })
167                         }
168                     },
169                     // foo == &bar
170                     (_, &ExprKind::AddrOf(_, ref r)) => {
171                         let rty = cx.tables.expr_ty(r);
172                         let rcpy = is_copy(cx, rty);
173                         if (requires_ref || rcpy) && implements_trait(cx, cx.tables.expr_ty(left), trait_id, &[rty.into()]) {
174                             span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |db| {
175                                 let rsnip = snippet(cx, r.span, "...").to_string();
176                                 db.span_suggestion_with_applicability(
177                                     right.span,
178                                     "use the right value directly",
179                                     rsnip,
180                                     Applicability::MachineApplicable, // snippet
181                                 );
182                             })
183                         }
184                     },
185                     _ => {},
186                 }
187             }
188         }
189     }
190 }
191
192
193 fn is_valid_operator(op: BinOp) -> bool {
194     match op.node {
195         BinOpKind::Sub | BinOpKind::Div | BinOpKind::Eq | BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge | BinOpKind::Ne | BinOpKind::And | BinOpKind::Or | BinOpKind::BitXor | BinOpKind::BitAnd | BinOpKind::BitOr => true,
196         _ => false,
197     }
198 }