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