]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copies.rs
Rustup to rust-lang/rust#64813
[rust.git] / clippy_lints / src / copies.rs
1 use crate::utils::{get_parent_expr, higher, if_sequence, same_tys, 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_lint_pass, declare_tool_lint};
7 use rustc_data_structures::fx::FxHashMap;
8 use std::collections::hash_map::Entry;
9 use std::hash::BuildHasherDefault;
10 use syntax::symbol::Symbol;
11
12 declare_clippy_lint! {
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     /// ```ignore
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     /// ```ignore
32     /// if foo() {
33     ///     …
34     /// } else if foo() { // not linted
35     ///     …
36     /// }
37     /// ```
38     pub IFS_SAME_COND,
39     correctness,
40     "consecutive `ifs` with the same condition"
41 }
42
43 declare_clippy_lint! {
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     /// ```ignore
53     /// let foo = if … {
54     ///     42
55     /// } else {
56     ///     42
57     /// };
58     /// ```
59     pub IF_SAME_THEN_ELSE,
60     correctness,
61     "if with the same *then* and *else* blocks"
62 }
63
64 declare_clippy_lint! {
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     pub MATCH_SAME_ARMS,
101     pedantic,
102     "`match` with identical arm bodies"
103 }
104
105 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
106
107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
108     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
109         if !expr.span.from_expansion() {
110             // skip ifs directly in else, it will be checked in the parent if
111             if let Some(expr) = get_parent_expr(cx, expr) {
112                 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
113                     if else_expr.hir_id == expr.hir_id {
114                         return;
115                     }
116                 }
117             }
118
119             let (conds, blocks) = if_sequence(expr);
120             lint_same_then_else(cx, &blocks);
121             lint_same_cond(cx, &conds);
122             lint_match_arms(cx, expr);
123         }
124     }
125 }
126
127 /// Implementation of `IF_SAME_THEN_ELSE`.
128 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
129     let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
130
131     if let Some((i, j)) = search_same_sequenced(blocks, eq) {
132         span_note_and_lint(
133             cx,
134             IF_SAME_THEN_ELSE,
135             j.span,
136             "this `if` has identical blocks",
137             i.span,
138             "same as this",
139         );
140     }
141 }
142
143 /// Implementation of `IFS_SAME_COND`.
144 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
145     let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
146         let mut h = SpanlessHash::new(cx, cx.tables);
147         h.hash_expr(expr);
148         h.finish()
149     };
150
151     let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
152         &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
153
154     for (i, j) in search_same(conds, hash, eq) {
155         span_note_and_lint(
156             cx,
157             IFS_SAME_COND,
158             j.span,
159             "this `if` has the same condition as a previous if",
160             i.span,
161             "same as this",
162         );
163     }
164 }
165
166 /// Implementation of `MATCH_SAME_ARMS`.
167 fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr) {
168     fn same_bindings<'tcx>(
169         cx: &LateContext<'_, 'tcx>,
170         lhs: &FxHashMap<Symbol, Ty<'tcx>>,
171         rhs: &FxHashMap<Symbol, Ty<'tcx>>,
172     ) -> bool {
173         lhs.len() == rhs.len()
174             && lhs
175                 .iter()
176                 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| same_tys(cx, l_ty, r_ty)))
177     }
178
179     if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
180         let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
181             let mut h = SpanlessHash::new(cx, cx.tables);
182             h.hash_expr(&arm.body);
183             h.finish()
184         };
185
186         let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
187             let min_index = usize::min(lindex, rindex);
188             let max_index = usize::max(lindex, rindex);
189
190             // Arms with a guard are ignored, those can’t always be merged together
191             // This is also the case for arms in-between each there is an arm with a guard
192             (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
193                 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
194                 // all patterns should have the same bindings
195                 same_bindings(cx, &bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
196         };
197
198         let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
199         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
200             span_lint_and_then(
201                 cx,
202                 MATCH_SAME_ARMS,
203                 j.body.span,
204                 "this `match` has identical arm bodies",
205                 |db| {
206                     db.span_note(i.body.span, "same as this");
207
208                     // Note: this does not use `span_suggestion` on purpose:
209                     // there is no clean way
210                     // to remove the other arm. Building a span and suggest to replace it to ""
211                     // makes an even more confusing error message. Also in order not to make up a
212                     // span for the whole pattern, the suggestion is only shown when there is only
213                     // one pattern. The user should know about `|` if they are already using it…
214
215                     let lhs = snippet(cx, i.pat.span, "<pat1>");
216                     let rhs = snippet(cx, j.pat.span, "<pat2>");
217
218                     if let PatKind::Wild = j.pat.kind {
219                         // if the last arm is _, then i could be integrated into _
220                         // note that i.pat cannot be _, because that would mean that we're
221                         // hiding all the subsequent arms, and rust won't compile
222                         db.span_note(
223                             i.body.span,
224                             &format!(
225                                 "`{}` has the same arm body as the `_` wildcard, consider removing it`",
226                                 lhs
227                             ),
228                         );
229                     } else {
230                         db.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
231                     }
232                 },
233             );
234         }
235     }
236 }
237
238 /// Returns the list of bindings in a pattern.
239 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<Symbol, Ty<'tcx>> {
240     fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
241         match pat.kind {
242             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
243             PatKind::TupleStruct(_, ref pats, _) => {
244                 for pat in pats {
245                     bindings_impl(cx, pat, map);
246                 }
247             },
248             PatKind::Binding(.., ident, ref as_pat) => {
249                 if let Entry::Vacant(v) = map.entry(ident.name) {
250                     v.insert(cx.tables.pat_ty(pat));
251                 }
252                 if let Some(ref as_pat) = *as_pat {
253                     bindings_impl(cx, as_pat, map);
254                 }
255             },
256             PatKind::Or(ref fields) | PatKind::Tuple(ref fields, _) => {
257                 for pat in fields {
258                     bindings_impl(cx, pat, map);
259                 }
260             },
261             PatKind::Struct(_, ref fields, _) => {
262                 for pat in fields {
263                     bindings_impl(cx, &pat.pat, map);
264                 }
265             },
266             PatKind::Slice(ref lhs, ref mid, ref rhs) => {
267                 for pat in lhs {
268                     bindings_impl(cx, pat, map);
269                 }
270                 if let Some(ref mid) = *mid {
271                     bindings_impl(cx, mid, map);
272                 }
273                 for pat in rhs {
274                     bindings_impl(cx, pat, map);
275                 }
276             },
277             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
278         }
279     }
280
281     let mut result = FxHashMap::default();
282     bindings_impl(cx, pat, &mut result);
283     result
284 }
285
286 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
287 where
288     Eq: Fn(&T, &T) -> bool,
289 {
290     for win in exprs.windows(2) {
291         if eq(&win[0], &win[1]) {
292             return Some((&win[0], &win[1]));
293         }
294     }
295     None
296 }
297
298 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
299 where
300     Eq: Fn(&T, &T) -> bool,
301 {
302     if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
303         Some((&exprs[0], &exprs[1]))
304     } else {
305         None
306     }
307 }
308
309 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
310 where
311     Hash: Fn(&T) -> u64,
312     Eq: Fn(&T, &T) -> bool,
313 {
314     if let Some(expr) = search_common_cases(&exprs, &eq) {
315         return vec![expr];
316     }
317
318     let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
319
320     let mut map: FxHashMap<_, Vec<&_>> =
321         FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
322
323     for expr in exprs {
324         match map.entry(hash(expr)) {
325             Entry::Occupied(mut o) => {
326                 for o in o.get() {
327                     if eq(o, expr) {
328                         match_expr_list.push((o, expr));
329                     }
330                 }
331                 o.get_mut().push(expr);
332             },
333             Entry::Vacant(v) => {
334                 v.insert(vec![expr]);
335             },
336         }
337     }
338
339     match_expr_list
340 }