]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copies.rs
Merge pull request #2763 from phansch/tasty_ice_cream
[rust.git] / clippy_lints / src / copies.rs
1 use rustc::lint::*;
2 use rustc::ty::Ty;
3 use rustc::hir::*;
4 use std::collections::HashMap;
5 use std::collections::hash_map::Entry;
6 use syntax::symbol::LocalInternedString;
7 use syntax::util::small_vector::SmallVector;
8 use utils::{SpanlessEq, SpanlessHash};
9 use utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
10
11 /// **What it does:** Checks for consecutive `if`s with the same condition.
12 ///
13 /// **Why is this bad?** This is probably a copy & paste error.
14 ///
15 /// **Known problems:** Hopefully none.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// if a == b {
20 ///     …
21 /// } else if a == b {
22 ///     …
23 /// }
24 /// ```
25 ///
26 /// Note that this lint ignores all conditions with a function call as it could
27 /// have side effects:
28 ///
29 /// ```rust
30 /// if foo() {
31 ///     …
32 /// } else if foo() { // not linted
33 ///     …
34 /// }
35 /// ```
36 declare_clippy_lint! {
37     pub IFS_SAME_COND,
38     correctness,
39     "consecutive `ifs` with the same condition"
40 }
41
42 /// **What it does:** Checks for `if/else` with the same body as the *then* part
43 /// and the *else* part.
44 ///
45 /// **Why is this bad?** This is probably a copy & paste error.
46 ///
47 /// **Known problems:** Hopefully none.
48 ///
49 /// **Example:**
50 /// ```rust
51 /// let foo = if … {
52 ///     42
53 /// } else {
54 ///     42
55 /// };
56 /// ```
57 declare_clippy_lint! {
58     pub IF_SAME_THEN_ELSE,
59     correctness,
60     "if with the same *then* and *else* blocks"
61 }
62
63 /// **What it does:** Checks for `match` with identical arm bodies.
64 ///
65 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
66 /// are the same on purpose, you can factor them
67 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
68 ///
69 /// **Known problems:** False positive possible with order dependent `match`
70 /// (see issue
71 /// [#860](https://github.com/rust-lang-nursery/rust-clippy/issues/860)).
72 ///
73 /// **Example:**
74 /// ```rust,ignore
75 /// match foo {
76 ///     Bar => bar(),
77 ///     Quz => quz(),
78 ///     Baz => bar(), // <= oops
79 /// }
80 /// ```
81 ///
82 /// This should probably be
83 /// ```rust,ignore
84 /// match foo {
85 ///     Bar => bar(),
86 ///     Quz => quz(),
87 ///     Baz => baz(), // <= fixed
88 /// }
89 /// ```
90 ///
91 /// or if the original code was not a typo:
92 /// ```rust,ignore
93 /// match foo {
94 ///     Bar | Baz => bar(), // <= shows the intent better
95 ///     Quz => quz(),
96 /// }
97 /// ```
98 declare_clippy_lint! {
99     pub MATCH_SAME_ARMS,
100     pedantic,
101     "`match` with identical arm bodies"
102 }
103
104 #[derive(Copy, Clone, Debug)]
105 pub struct CopyAndPaste;
106
107 impl LintPass for CopyAndPaste {
108     fn get_lints(&self) -> LintArray {
109         lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
110     }
111 }
112
113 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
114     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
115         if !in_macro(expr.span) {
116             // skip ifs directly in else, it will be checked in the parent if
117             if let Some(&Expr {
118                 node: ExprIf(_, _, Some(ref else_expr)),
119                 ..
120             }) = get_parent_expr(cx, expr)
121             {
122                 if else_expr.id == expr.id {
123                     return;
124                 }
125             }
126
127             let (conds, blocks) = if_sequence(expr);
128             lint_same_then_else(cx, &blocks);
129             lint_same_cond(cx, &conds);
130             lint_match_arms(cx, expr);
131         }
132     }
133 }
134
135 /// Implementation of `IF_SAME_THEN_ELSE`.
136 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
137     let eq: &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
138
139     if let Some((i, j)) = search_same_sequenced(blocks, eq) {
140         span_note_and_lint(
141             cx,
142             IF_SAME_THEN_ELSE,
143             j.span,
144             "this `if` has identical blocks",
145             i.span,
146             "same as this",
147         );
148     }
149 }
150
151 /// Implementation of `IFS_SAME_COND`.
152 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
153     let hash: &Fn(&&Expr) -> u64 = &|expr| -> u64 {
154         let mut h = SpanlessHash::new(cx, cx.tables);
155         h.hash_expr(expr);
156         h.finish()
157     };
158
159     let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
160
161     if let Some((i, j)) = search_same(conds, hash, eq) {
162         span_note_and_lint(
163             cx,
164             IFS_SAME_COND,
165             j.span,
166             "this `if` has the same condition as a previous if",
167             i.span,
168             "same as this",
169         );
170     }
171 }
172
173 /// Implementation of `MATCH_SAME_ARMS`.
174 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
175     if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
176         let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
177             let mut h = SpanlessHash::new(cx, cx.tables);
178             h.hash_expr(&arm.body);
179             h.finish()
180         };
181
182         let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
183             let min_index = usize::min(lindex, rindex);
184             let max_index = usize::max(lindex, rindex);
185             // Arms with a guard are ignored, those can’t always be merged together
186             // This is also the case for arms in-between each there is an arm with a guard
187             (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
188                 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
189                 // all patterns should have the same bindings
190                 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
191         };
192
193         let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
194         if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
195             span_lint_and_then(
196                 cx,
197                 MATCH_SAME_ARMS,
198                 j.body.span,
199                 "this `match` has identical arm bodies",
200                 |db| {
201                     db.span_note(i.body.span, "same as this");
202
203                     // Note: this does not use `span_suggestion` on purpose: there is no clean way
204                     // to remove the other arm. Building a span and suggest to replace it to ""
205                     // makes an even more confusing error message. Also in order not to make up a
206                     // span for the whole pattern, the suggestion is only shown when there is only
207                     // one pattern. The user should know about `|` if they are already using it…
208
209                     if i.pats.len() == 1 && j.pats.len() == 1 {
210                         let lhs = snippet(cx, i.pats[0].span, "<pat1>");
211                         let rhs = snippet(cx, j.pats[0].span, "<pat2>");
212
213                         if let PatKind::Wild = j.pats[0].node {
214                             // if the last arm is _, then i could be integrated into _
215                             // note that i.pats[0] cannot be _, because that would mean that we're
216                             // hiding all the subsequent arms, and rust won't compile
217                             db.span_note(
218                                 i.body.span,
219                                 &format!("`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs),
220                             );
221                         } else {
222                             db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
223                         }
224                     }
225                 },
226             );
227         }
228     }
229 }
230
231 /// Return the list of condition expressions and the list of blocks in a
232 /// sequence of `if/else`.
233 /// Eg. would return `([a, b], [c, d, e])` for the expression
234 /// `if a { c } else if b { d } else { e }`.
235 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
236     let mut conds = SmallVector::new();
237     let mut blocks: SmallVector<&Block> = SmallVector::new();
238
239     while let ExprIf(ref cond, ref then_expr, ref else_expr) = expr.node {
240         conds.push(&**cond);
241         if let ExprBlock(ref block, _) = then_expr.node {
242             blocks.push(block);
243         } else {
244             panic!("ExprIf node is not an ExprBlock");
245         }
246
247         if let Some(ref else_expr) = *else_expr {
248             expr = else_expr;
249         } else {
250             break;
251         }
252     }
253
254     // final `else {..}`
255     if !blocks.is_empty() {
256         if let ExprBlock(ref block, _) = expr.node {
257             blocks.push(&**block);
258         }
259     }
260
261     (conds, blocks)
262 }
263
264 /// Return the list of bindings in a pattern.
265 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<LocalInternedString, Ty<'tcx>> {
266     fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<LocalInternedString, Ty<'tcx>>) {
267         match pat.node {
268             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
269             PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
270                 bindings_impl(cx, pat, map);
271             },
272             PatKind::Binding(_, _, ref ident, ref as_pat) => {
273                 if let Entry::Vacant(v) = map.entry(ident.node.as_str()) {
274                     v.insert(cx.tables.pat_ty(pat));
275                 }
276                 if let Some(ref as_pat) = *as_pat {
277                     bindings_impl(cx, as_pat, map);
278                 }
279             },
280             PatKind::Struct(_, ref fields, _) => for pat in fields {
281                 bindings_impl(cx, &pat.node.pat, map);
282             },
283             PatKind::Tuple(ref fields, _) => for pat in fields {
284                 bindings_impl(cx, pat, map);
285             },
286             PatKind::Slice(ref lhs, ref mid, ref rhs) => {
287                 for pat in lhs {
288                     bindings_impl(cx, pat, map);
289                 }
290                 if let Some(ref mid) = *mid {
291                     bindings_impl(cx, mid, map);
292                 }
293                 for pat in rhs {
294                     bindings_impl(cx, pat, map);
295                 }
296             },
297             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
298         }
299     }
300
301     let mut result = HashMap::new();
302     bindings_impl(cx, pat, &mut result);
303     result
304 }
305
306
307 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
308 where
309     Eq: Fn(&T, &T) -> bool,
310 {
311     for win in exprs.windows(2) {
312         if eq(&win[0], &win[1]) {
313             return Some((&win[0], &win[1]));
314         }
315     }
316     None
317 }
318
319 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
320 where
321     Hash: Fn(&T) -> u64,
322     Eq: Fn(&T, &T) -> bool,
323 {
324     // common cases
325     if exprs.len() < 2 {
326         return None;
327     } else if exprs.len() == 2 {
328         return if eq(&exprs[0], &exprs[1]) {
329             Some((&exprs[0], &exprs[1]))
330         } else {
331             None
332         };
333     }
334
335     let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
336
337     for expr in exprs {
338         match map.entry(hash(expr)) {
339             Entry::Occupied(mut o) => {
340                 for o in o.get() {
341                     if eq(o, expr) {
342                         return Some((o, expr));
343                     }
344                 }
345                 o.get_mut().push(expr);
346             },
347             Entry::Vacant(v) => {
348                 v.insert(vec![expr]);
349             },
350         }
351     }
352
353     None
354 }