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