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