]> git.lizzy.rs Git - rust.git/blob - src/copies.rs
Fix false positive in `MATCH_SAME_ARMS` and guards
[rust.git] / src / copies.rs
1 use rustc::lint::*;
2 use rustc::ty;
3 use rustc_front::hir::*;
4 use std::collections::HashMap;
5 use std::collections::hash_map::Entry;
6 use syntax::parse::token::InternedString;
7 use syntax::util::small_vector::SmallVector;
8 use utils::{SpanlessEq, SpanlessHash};
9 use utils::{get_parent_expr, in_macro, span_note_and_lint};
10
11 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
12 /// `Warn` by default.
13 ///
14 /// **Why is this bad?** This is probably a copy & paste error.
15 ///
16 /// **Known problems:** Hopefully none.
17 ///
18 /// **Example:** `if a == b { .. } else if a == b { .. }`
19 declare_lint! {
20     pub IFS_SAME_COND,
21     Warn,
22     "consecutive `ifs` with the same condition"
23 }
24
25 /// **What it does:** This lint checks for `if/else` with the same body as the *then* part and the
26 /// *else* part. This lint is `Warn` by default.
27 ///
28 /// **Why is this bad?** This is probably a copy & paste error.
29 ///
30 /// **Known problems:** Hopefully none.
31 ///
32 /// **Example:** `if .. { 42 } else { 42 }`
33 declare_lint! {
34     pub IF_SAME_THEN_ELSE,
35     Warn,
36     "if with the same *then* and *else* blocks"
37 }
38
39 /// **What it does:** This lint checks for `match` with identical arm bodies.
40 ///
41 /// **Why is this bad?** This is probably a copy & paste error.
42 ///
43 /// **Known problems:** Hopefully none.
44 ///
45 /// **Example:**
46 /// ```rust,ignore
47 /// match foo {
48 ///     Bar => bar(),
49 ///     Quz => quz(),
50 ///     Baz => bar(), // <= oops
51 /// }
52 /// ```
53 declare_lint! {
54     pub MATCH_SAME_ARMS,
55     Warn,
56     "`match` with identical arm bodies"
57 }
58
59 #[derive(Copy, Clone, Debug)]
60 pub struct CopyAndPaste;
61
62 impl LintPass for CopyAndPaste {
63     fn get_lints(&self) -> LintArray {
64         lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
65     }
66 }
67
68 impl LateLintPass for CopyAndPaste {
69     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
70         if !in_macro(cx, expr.span) {
71             // skip ifs directly in else, it will be checked in the parent if
72             if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
73                 if else_expr.id == expr.id {
74                     return;
75                 }
76             }
77
78             let (conds, blocks) = if_sequence(expr);
79             lint_same_then_else(cx, blocks.as_slice());
80             lint_same_cond(cx, conds.as_slice());
81             lint_match_arms(cx, expr);
82         }
83     }
84 }
85
86 /// Implementation of `IF_SAME_THEN_ELSE`.
87 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
88     let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
89         let mut h = SpanlessHash::new(cx);
90         h.hash_block(block);
91         h.finish()
92     };
93
94     let eq: &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
95
96     if let Some((i, j)) = search_same(blocks, hash, eq) {
97         span_note_and_lint(cx,
98                            IF_SAME_THEN_ELSE,
99                            j.span,
100                            "this `if` has identical blocks",
101                            i.span,
102                            "same as this");
103     }
104 }
105
106 /// Implementation of `IFS_SAME_COND`.
107 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
108     let hash: &Fn(&&Expr) -> u64 = &|expr| -> u64 {
109         let mut h = SpanlessHash::new(cx);
110         h.hash_expr(expr);
111         h.finish()
112     };
113
114     let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
115
116     if let Some((i, j)) = search_same(conds, hash, eq) {
117         span_note_and_lint(cx,
118                            IFS_SAME_COND,
119                            j.span,
120                            "this `if` has the same condition as a previous if",
121                            i.span,
122                            "same as this");
123     }
124 }
125
126 /// Implementation if `MATCH_SAME_ARMS`.
127 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
128     let hash = |arm: &Arm| -> u64 {
129         let mut h = SpanlessHash::new(cx);
130         h.hash_expr(&arm.body);
131         h.finish()
132     };
133
134     let eq = |lhs: &Arm, rhs: &Arm| -> bool {
135         // Arms with a guard are ignored, those can’t always be merged together
136         lhs.guard.is_none() && rhs.guard.is_none() &&
137             SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
138             // all patterns should have the same bindings
139             bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
140     };
141
142     if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
143         if let Some((i, j)) = search_same(&arms, hash, eq) {
144             span_note_and_lint(cx,
145                                MATCH_SAME_ARMS,
146                                j.body.span,
147                                "this `match` has identical arm bodies",
148                                i.body.span,
149                                "same as this");
150         }
151     }
152 }
153
154 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
155 /// Eg. would return `([a, b], [c, d, e])` for the expression
156 /// `if a { c } else if b { d } else { e }`.
157 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
158     let mut conds = SmallVector::zero();
159     let mut blocks = SmallVector::zero();
160
161     while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
162         conds.push(&**cond);
163         blocks.push(&**then_block);
164
165         if let Some(ref else_expr) = *else_expr {
166             expr = else_expr;
167         } else {
168             break;
169         }
170     }
171
172     // final `else {..}`
173     if !blocks.is_empty() {
174         if let ExprBlock(ref block) = expr.node {
175             blocks.push(&**block);
176         }
177     }
178
179     (conds, blocks)
180 }
181
182 /// Return the list of bindings in a pattern.
183 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
184     fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
185         match pat.node {
186             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
187             PatKind::TupleStruct(_, Some(ref pats)) => {
188                 for pat in pats {
189                     bindings_impl(cx, pat, map);
190                 }
191             }
192             PatKind::Ident(_, ref ident, ref as_pat) => {
193                 if let Entry::Vacant(v) = map.entry(ident.node.name.as_str()) {
194                     v.insert(cx.tcx.pat_ty(pat));
195                 }
196                 if let Some(ref as_pat) = *as_pat {
197                     bindings_impl(cx, as_pat, map);
198                 }
199             }
200             PatKind::Struct(_, ref fields, _) => {
201                 for pat in fields {
202                     bindings_impl(cx, &pat.node.pat, map);
203                 }
204             }
205             PatKind::Tup(ref fields) => {
206                 for pat in fields {
207                     bindings_impl(cx, pat, map);
208                 }
209             }
210             PatKind::Vec(ref lhs, ref mid, ref rhs) => {
211                 for pat in lhs {
212                     bindings_impl(cx, pat, map);
213                 }
214                 if let Some(ref mid) = *mid {
215                     bindings_impl(cx, mid, map);
216                 }
217                 for pat in rhs {
218                     bindings_impl(cx, pat, map);
219                 }
220             }
221             PatKind::TupleStruct(..) |
222             PatKind::Lit(..) |
223             PatKind::QPath(..) |
224             PatKind::Range(..) |
225             PatKind::Wild |
226             PatKind::Path(..) => (),
227         }
228     }
229
230     let mut result = HashMap::new();
231     bindings_impl(cx, pat, &mut result);
232     result
233 }
234
235 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
236     where Hash: Fn(&T) -> u64,
237           Eq: Fn(&T, &T) -> bool
238 {
239     // common cases
240     if exprs.len() < 2 {
241         return None;
242     } else if exprs.len() == 2 {
243         return if eq(&exprs[0], &exprs[1]) {
244             Some((&exprs[0], &exprs[1]))
245         } else {
246             None
247         };
248     }
249
250     let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
251
252     for expr in exprs {
253         match map.entry(hash(expr)) {
254             Entry::Occupied(o) => {
255                 for o in o.get() {
256                     if eq(&o, expr) {
257                         return Some((&o, expr));
258                     }
259                 }
260             }
261             Entry::Vacant(v) => {
262                 v.insert(vec![expr]);
263             }
264         }
265     }
266
267     None
268 }