]> git.lizzy.rs Git - rust.git/blob - src/copies.rs
Add the MATCH_SAME_ARMS lint
[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 utils::{SpanlessEq, SpanlessHash};
8 use utils::{get_parent_expr, in_macro, span_note_and_lint};
9
10 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
11 /// `Warn` by default.
12 ///
13 /// **Why is this bad?** This is probably a copy & paste error.
14 ///
15 /// **Known problems:** Hopefully none.
16 ///
17 /// **Example:** `if a == b { .. } else if a == b { .. }`
18 declare_lint! {
19     pub IFS_SAME_COND,
20     Warn,
21     "consecutive `ifs` with the same condition"
22 }
23
24 /// **What it does:** This lint checks for `if/else` with the same body as the *then* part and the
25 /// *else* part. This lint is `Warn` by default.
26 ///
27 /// **Why is this bad?** This is probably a copy & paste error.
28 ///
29 /// **Known problems:** Hopefully none.
30 ///
31 /// **Example:** `if .. { 42 } else { 42 }`
32 declare_lint! {
33     pub IF_SAME_THEN_ELSE,
34     Warn,
35     "if with the same *then* and *else* blocks"
36 }
37
38 /// **What it does:** This lint checks for `match` with identical arm bodies.
39 ///
40 /// **Why is this bad?** This is probably a copy & paste error.
41 ///
42 /// **Known problems:** Hopefully none.
43 ///
44 /// **Example:**
45 /// ```rust,ignore
46 /// match foo {
47 ///     Bar => bar(),
48 ///     Quz => quz(),
49 ///     Baz => bar(), // <= oups
50 /// ```
51 declare_lint! {
52     pub MATCH_SAME_ARMS,
53     Warn,
54     "`match` with identical arm bodies"
55 }
56
57 #[derive(Copy, Clone, Debug)]
58 pub struct CopyAndPaste;
59
60 impl LintPass for CopyAndPaste {
61     fn get_lints(&self) -> LintArray {
62         lint_array![
63             IFS_SAME_COND,
64             IF_SAME_THEN_ELSE,
65             MATCH_SAME_ARMS
66         ]
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);
82             lint_same_cond(cx, &conds);
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 {
97         SpanlessEq::new(cx).eq_block(lhs, rhs)
98     };
99
100     if let Some((i, j)) = search_same(blocks, hash, eq) {
101         span_note_and_lint(cx, IF_SAME_THEN_ELSE, j.span, "this `if` has identical blocks", i.span, "same as this");
102     }
103 }
104
105 /// Implementation of `IFS_SAME_COND`.
106 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
107     let hash : &Fn(&&Expr) -> u64 = &|expr| -> u64 {
108         let mut h = SpanlessHash::new(cx);
109         h.hash_expr(expr);
110         h.finish()
111     };
112
113     let eq : &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool {
114         SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs)
115     };
116
117     if let Some((i, j)) = search_same(conds, hash, eq) {
118         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");
119     }
120 }
121
122 /// Implementation if `MATCH_SAME_ARMS`.
123 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
124     let hash = |arm: &Arm| -> u64 {
125         let mut h = SpanlessHash::new(cx);
126         h.hash_expr(&arm.body);
127         h.finish()
128     };
129
130     let eq = |lhs: &Arm, rhs: &Arm| -> bool {
131         SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
132             // all patterns should have the same bindings
133             bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
134     };
135
136     if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
137         if let Some((i, j)) = search_same(&**arms, hash, eq) {
138             span_note_and_lint(cx, MATCH_SAME_ARMS, j.body.span, "this `match` has identical arm bodies", i.body.span, "same as this");
139         }
140     }
141 }
142
143 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
144 /// Eg. would return `([a, b], [c, d, e])` for the expression
145 /// `if a { c } else if b { d } else { e }`.
146 fn if_sequence(mut expr: &Expr) -> (Vec<&Expr>, Vec<&Block>) {
147     let mut conds = vec![];
148     let mut blocks = vec![];
149
150     while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
151         conds.push(&**cond);
152         blocks.push(&**then_block);
153
154         if let Some(ref else_expr) = *else_expr {
155             expr = else_expr;
156         }
157         else {
158             break;
159         }
160     }
161
162     // final `else {..}`
163     if !blocks.is_empty() {
164         if let ExprBlock(ref block) = expr.node {
165             blocks.push(&**block);
166         }
167     }
168
169     (conds, blocks)
170 }
171
172 /// Return the list of bindings in a pattern.
173 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
174     fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
175         match pat.node {
176             PatBox(ref pat) | PatRegion(ref pat, _) => bindings_impl(cx, pat, map),
177             PatEnum(_, Some(ref pats)) => {
178                 for pat in pats {
179                     bindings_impl(cx, pat, map);
180                 }
181             }
182             PatIdent(_, ref ident, ref as_pat) => {
183                 if let Entry::Vacant(v) = map.entry(ident.node.name.as_str()) {
184                     v.insert(cx.tcx.pat_ty(pat));
185                 }
186                 if let Some(ref as_pat) = *as_pat {
187                     bindings_impl(cx, as_pat, map);
188                 }
189             },
190             PatStruct(_, ref fields, _) => {
191                 for pat in fields {
192                     bindings_impl(cx, &pat.node.pat, map);
193                 }
194             }
195             PatTup(ref fields) => {
196                 for pat in fields {
197                     bindings_impl(cx, pat, map);
198                 }
199             }
200             PatVec(ref lhs, ref mid, ref rhs) => {
201                 for pat in lhs {
202                     bindings_impl(cx, pat, map);
203                 }
204                 if let Some(ref mid) = *mid {
205                     bindings_impl(cx, mid, map);
206                 }
207                 for pat in rhs {
208                     bindings_impl(cx, pat, map);
209                 }
210             }
211             PatEnum(..) | PatLit(..) | PatQPath(..) | PatRange(..) | PatWild => (),
212         }
213     }
214
215     let mut result = HashMap::new();
216     bindings_impl(cx, pat, &mut result);
217     result
218 }
219
220 fn search_same<T, Hash, Eq>(exprs: &[T],
221                             hash: Hash,
222                             eq: Eq) -> Option<(&T, &T)>
223 where Hash: Fn(&T) -> u64,
224       Eq: Fn(&T, &T) -> bool {
225     // common cases
226     if exprs.len() < 2 {
227         return None;
228     }
229     else if exprs.len() == 2 {
230         return if eq(&exprs[0], &exprs[1]) {
231             Some((&exprs[0], &exprs[1]))
232         }
233         else {
234             None
235         }
236     }
237
238     let mut map : HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
239
240     for expr in exprs {
241         match map.entry(hash(expr)) {
242             Entry::Occupied(o) => {
243                 for o in o.get() {
244                     if eq(&o, expr) {
245                         return Some((&o, expr))
246                     }
247                 }
248             }
249             Entry::Vacant(v) => { v.insert(vec![expr]); }
250         }
251     }
252
253     None
254 }