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