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