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