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