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