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