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