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