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