]> git.lizzy.rs Git - rust.git/blob - src/copies.rs
Improve the `match_same_arms` doc
[rust.git] / src / copies.rs
1 use rustc::lint::*;
2 use rustc::ty;
3 use rustc_front::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_note_and_lint};
10
11 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
12 /// `Warn` by default.
13 ///
14 /// **Why is this bad?** This is probably a copy & paste error.
15 ///
16 /// **Known problems:** Hopefully none.
17 ///
18 /// **Example:** `if a == b { .. } else if a == b { .. }`
19 declare_lint! {
20     pub IFS_SAME_COND,
21     Warn,
22     "consecutive `ifs` with the same condition"
23 }
24
25 /// **What it does:** This lint checks for `if/else` with the same body as the *then* part and the
26 /// *else* part. This lint is `Warn` by default.
27 ///
28 /// **Why is this bad?** This is probably a copy & paste error.
29 ///
30 /// **Known problems:** Hopefully none.
31 ///
32 /// **Example:** `if .. { 42 } else { 42 }`
33 declare_lint! {
34     pub IF_SAME_THEN_ELSE,
35     Warn,
36     "if with the same *then* and *else* blocks"
37 }
38
39 /// **What it does:** This lint checks for `match` with identical arm bodies.
40 ///
41 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies are the same on
42 /// purpose, you can factor them
43 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
44 ///
45 /// **Known problems:** Hopefully none.
46 ///
47 /// **Example:**
48 /// ```rust,ignore
49 /// match foo {
50 ///     Bar => bar(),
51 ///     Quz => quz(),
52 ///     Baz => bar(), // <= oops
53 /// }
54 /// ```
55 declare_lint! {
56     pub MATCH_SAME_ARMS,
57     Warn,
58     "`match` with identical arm bodies"
59 }
60
61 #[derive(Copy, Clone, Debug)]
62 pub struct CopyAndPaste;
63
64 impl LintPass for CopyAndPaste {
65     fn get_lints(&self) -> LintArray {
66         lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
67     }
68 }
69
70 impl LateLintPass for CopyAndPaste {
71     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
72         if !in_macro(cx, expr.span) {
73             // skip ifs directly in else, it will be checked in the parent if
74             if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
75                 if else_expr.id == expr.id {
76                     return;
77                 }
78             }
79
80             let (conds, blocks) = if_sequence(expr);
81             lint_same_then_else(cx, blocks.as_slice());
82             lint_same_cond(cx, conds.as_slice());
83             lint_match_arms(cx, expr);
84         }
85     }
86 }
87
88 /// Implementation of `IF_SAME_THEN_ELSE`.
89 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
90     let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
91         let mut h = SpanlessHash::new(cx);
92         h.hash_block(block);
93         h.finish()
94     };
95
96     let eq: &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
97
98     if let Some((i, j)) = search_same(blocks, hash, eq) {
99         span_note_and_lint(cx,
100                            IF_SAME_THEN_ELSE,
101                            j.span,
102                            "this `if` has identical blocks",
103                            i.span,
104                            "same as this");
105     }
106 }
107
108 /// Implementation of `IFS_SAME_COND`.
109 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
110     let hash: &Fn(&&Expr) -> u64 = &|expr| -> u64 {
111         let mut h = SpanlessHash::new(cx);
112         h.hash_expr(expr);
113         h.finish()
114     };
115
116     let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
117
118     if let Some((i, j)) = search_same(conds, hash, eq) {
119         span_note_and_lint(cx,
120                            IFS_SAME_COND,
121                            j.span,
122                            "this `if` has the same condition as a previous if",
123                            i.span,
124                            "same as this");
125     }
126 }
127
128 /// Implementation if `MATCH_SAME_ARMS`.
129 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
130     let hash = |arm: &Arm| -> u64 {
131         let mut h = SpanlessHash::new(cx);
132         h.hash_expr(&arm.body);
133         h.finish()
134     };
135
136     let eq = |lhs: &Arm, rhs: &Arm| -> bool {
137         // Arms with a guard are ignored, those can’t always be merged together
138         lhs.guard.is_none() && rhs.guard.is_none() &&
139             SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
140             // all patterns should have the same bindings
141             bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
142     };
143
144     if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
145         if let Some((i, j)) = search_same(&arms, hash, eq) {
146             span_note_and_lint(cx,
147                                MATCH_SAME_ARMS,
148                                j.body.span,
149                                "this `match` has identical arm bodies",
150                                i.body.span,
151                                "same as this");
152         }
153     }
154 }
155
156 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
157 /// Eg. would return `([a, b], [c, d, e])` for the expression
158 /// `if a { c } else if b { d } else { e }`.
159 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
160     let mut conds = SmallVector::zero();
161     let mut blocks = SmallVector::zero();
162
163     while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
164         conds.push(&**cond);
165         blocks.push(&**then_block);
166
167         if let Some(ref else_expr) = *else_expr {
168             expr = else_expr;
169         } else {
170             break;
171         }
172     }
173
174     // final `else {..}`
175     if !blocks.is_empty() {
176         if let ExprBlock(ref block) = expr.node {
177             blocks.push(&**block);
178         }
179     }
180
181     (conds, blocks)
182 }
183
184 /// Return the list of bindings in a pattern.
185 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
186     fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
187         match pat.node {
188             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
189             PatKind::TupleStruct(_, Some(ref pats)) => {
190                 for pat in pats {
191                     bindings_impl(cx, pat, map);
192                 }
193             }
194             PatKind::Ident(_, ref ident, ref as_pat) => {
195                 if let Entry::Vacant(v) = map.entry(ident.node.name.as_str()) {
196                     v.insert(cx.tcx.pat_ty(pat));
197                 }
198                 if let Some(ref as_pat) = *as_pat {
199                     bindings_impl(cx, as_pat, map);
200                 }
201             }
202             PatKind::Struct(_, ref fields, _) => {
203                 for pat in fields {
204                     bindings_impl(cx, &pat.node.pat, map);
205                 }
206             }
207             PatKind::Tup(ref fields) => {
208                 for pat in fields {
209                     bindings_impl(cx, pat, map);
210                 }
211             }
212             PatKind::Vec(ref lhs, ref mid, ref rhs) => {
213                 for pat in lhs {
214                     bindings_impl(cx, pat, map);
215                 }
216                 if let Some(ref mid) = *mid {
217                     bindings_impl(cx, mid, map);
218                 }
219                 for pat in rhs {
220                     bindings_impl(cx, pat, map);
221                 }
222             }
223             PatKind::TupleStruct(..) |
224             PatKind::Lit(..) |
225             PatKind::QPath(..) |
226             PatKind::Range(..) |
227             PatKind::Wild |
228             PatKind::Path(..) => (),
229         }
230     }
231
232     let mut result = HashMap::new();
233     bindings_impl(cx, pat, &mut result);
234     result
235 }
236
237 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
238     where Hash: Fn(&T) -> u64,
239           Eq: Fn(&T, &T) -> bool
240 {
241     // common cases
242     if exprs.len() < 2 {
243         return None;
244     } else if exprs.len() == 2 {
245         return if eq(&exprs[0], &exprs[1]) {
246             Some((&exprs[0], &exprs[1]))
247         } else {
248             None
249         };
250     }
251
252     let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
253
254     for expr in exprs {
255         match map.entry(hash(expr)) {
256             Entry::Occupied(o) => {
257                 for o in o.get() {
258                     if eq(&o, expr) {
259                         return Some((&o, expr));
260                     }
261                 }
262             }
263             Entry::Vacant(v) => {
264                 v.insert(vec![expr]);
265             }
266         }
267     }
268
269     None
270 }