]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copies.rs
Auto merge of #3645 - phansch:remove_copyright_headers, 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
115 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
116     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
117         if !in_macro(expr.span) {
118             // skip ifs directly in else, it will be checked in the parent if
119             if let Some(&Expr {
120                 node: ExprKind::If(_, _, Some(ref else_expr)),
121                 ..
122             }) = get_parent_expr(cx, expr)
123             {
124                 if else_expr.id == expr.id {
125                     return;
126                 }
127             }
128
129             let (conds, blocks) = if_sequence(expr);
130             lint_same_then_else(cx, &blocks);
131             lint_same_cond(cx, &conds);
132             lint_match_arms(cx, expr);
133         }
134     }
135 }
136
137 /// Implementation of `IF_SAME_THEN_ELSE`.
138 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
139     let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
140
141     if let Some((i, j)) = search_same_sequenced(blocks, eq) {
142         span_note_and_lint(
143             cx,
144             IF_SAME_THEN_ELSE,
145             j.span,
146             "this `if` has identical blocks",
147             i.span,
148             "same as this",
149         );
150     }
151 }
152
153 /// Implementation of `IFS_SAME_COND`.
154 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
155     let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
156         let mut h = SpanlessHash::new(cx, cx.tables);
157         h.hash_expr(expr);
158         h.finish()
159     };
160
161     let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
162         &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
163
164     if let Some((i, j)) = search_same(conds, hash, eq) {
165         span_note_and_lint(
166             cx,
167             IFS_SAME_COND,
168             j.span,
169             "this `if` has the same condition as a previous if",
170             i.span,
171             "same as this",
172         );
173     }
174 }
175
176 /// Implementation of `MATCH_SAME_ARMS`.
177 fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
178     if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node {
179         let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
180             let mut h = SpanlessHash::new(cx, cx.tables);
181             h.hash_expr(&arm.body);
182             h.finish()
183         };
184
185         let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
186             let min_index = usize::min(lindex, rindex);
187             let max_index = usize::max(lindex, rindex);
188             // Arms with a guard are ignored, those can’t always be merged together
189             // This is also the case for arms in-between each there is an arm with a guard
190             (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
191                 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
192                 // all patterns should have the same bindings
193                 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
194         };
195
196         let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
197         if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
198             span_lint_and_then(
199                 cx,
200                 MATCH_SAME_ARMS,
201                 j.body.span,
202                 "this `match` has identical arm bodies",
203                 |db| {
204                     db.span_note(i.body.span, "same as this");
205
206                     // Note: this does not use `span_suggestion_with_applicability` on purpose:
207                     // there is no clean way
208                     // to remove the other arm. Building a span and suggest to replace it to ""
209                     // makes an even more confusing error message. Also in order not to make up a
210                     // span for the whole pattern, the suggestion is only shown when there is only
211                     // one pattern. The user should know about `|` if they are already using it…
212
213                     if i.pats.len() == 1 && j.pats.len() == 1 {
214                         let lhs = snippet(cx, i.pats[0].span, "<pat1>");
215                         let rhs = snippet(cx, j.pats[0].span, "<pat2>");
216
217                         if let PatKind::Wild = j.pats[0].node {
218                             // if the last arm is _, then i could be integrated into _
219                             // note that i.pats[0] cannot be _, because that would mean that we're
220                             // hiding all the subsequent arms, and rust won't compile
221                             db.span_note(
222                                 i.body.span,
223                                 &format!(
224                                     "`{}` has the same arm body as the `_` wildcard, consider removing it`",
225                                     lhs
226                                 ),
227                             );
228                         } else {
229                             db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
230                         }
231                     }
232                 },
233             );
234         }
235     }
236 }
237
238 /// Return the list of condition expressions and the list of blocks in a
239 /// sequence of `if/else`.
240 /// Eg. would return `([a, b], [c, d, e])` for the expression
241 /// `if a { c } else if b { d } else { e }`.
242 fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
243     let mut conds = SmallVec::new();
244     let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
245
246     while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.node {
247         conds.push(&**cond);
248         if let ExprKind::Block(ref block, _) = then_expr.node {
249             blocks.push(block);
250         } else {
251             panic!("ExprKind::If node is not an ExprKind::Block");
252         }
253
254         if let Some(ref else_expr) = *else_expr {
255             expr = else_expr;
256         } else {
257             break;
258         }
259     }
260
261     // final `else {..}`
262     if !blocks.is_empty() {
263         if let ExprKind::Block(ref block, _) = expr.node {
264             blocks.push(&**block);
265         }
266     }
267
268     (conds, blocks)
269 }
270
271 /// Return the list of bindings in a pattern.
272 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> {
273     fn bindings_impl<'a, 'tcx>(
274         cx: &LateContext<'a, 'tcx>,
275         pat: &Pat,
276         map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>,
277     ) {
278         match pat.node {
279             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
280             PatKind::TupleStruct(_, ref pats, _) => {
281                 for pat in pats {
282                     bindings_impl(cx, pat, map);
283                 }
284             },
285             PatKind::Binding(_, _, ident, ref as_pat) => {
286                 if let Entry::Vacant(v) = map.entry(ident.as_str()) {
287                     v.insert(cx.tables.pat_ty(pat));
288                 }
289                 if let Some(ref as_pat) = *as_pat {
290                     bindings_impl(cx, as_pat, map);
291                 }
292             },
293             PatKind::Struct(_, ref fields, _) => {
294                 for pat in fields {
295                     bindings_impl(cx, &pat.node.pat, map);
296                 }
297             },
298             PatKind::Tuple(ref fields, _) => {
299                 for pat in fields {
300                     bindings_impl(cx, pat, map);
301                 }
302             },
303             PatKind::Slice(ref lhs, ref mid, ref rhs) => {
304                 for pat in lhs {
305                     bindings_impl(cx, pat, map);
306                 }
307                 if let Some(ref mid) = *mid {
308                     bindings_impl(cx, mid, map);
309                 }
310                 for pat in rhs {
311                     bindings_impl(cx, pat, map);
312                 }
313             },
314             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
315         }
316     }
317
318     let mut result = FxHashMap::default();
319     bindings_impl(cx, pat, &mut result);
320     result
321 }
322
323 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
324 where
325     Eq: Fn(&T, &T) -> bool,
326 {
327     for win in exprs.windows(2) {
328         if eq(&win[0], &win[1]) {
329             return Some((&win[0], &win[1]));
330         }
331     }
332     None
333 }
334
335 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
336 where
337     Hash: Fn(&T) -> u64,
338     Eq: Fn(&T, &T) -> bool,
339 {
340     // common cases
341     if exprs.len() < 2 {
342         return None;
343     } else if exprs.len() == 2 {
344         return if eq(&exprs[0], &exprs[1]) {
345             Some((&exprs[0], &exprs[1]))
346         } else {
347             None
348         };
349     }
350
351     let mut map: FxHashMap<_, Vec<&_>> =
352         FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
353
354     for expr in exprs {
355         match map.entry(hash(expr)) {
356             Entry::Occupied(mut o) => {
357                 for o in o.get() {
358                     if eq(o, expr) {
359                         return Some((o, expr));
360                     }
361                 }
362                 o.get_mut().push(expr);
363             },
364             Entry::Vacant(v) => {
365                 v.insert(vec![expr]);
366             },
367         }
368     }
369
370     None
371 }