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