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