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