]> git.lizzy.rs Git - rust.git/blob - src/copies.rs
Extend IF_SAME_THEN_ELSE to ifs sequences
[rust.git] / src / copies.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use std::collections::HashMap;
4 use std::collections::hash_map::Entry;
5 use utils::{SpanlessEq, SpanlessHash};
6 use utils::{get_parent_expr, in_macro, span_note_and_lint};
7
8 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
9 /// `Warn` by default.
10 ///
11 /// **Why is this bad?** This is probably a copy & paste error.
12 ///
13 /// **Known problems:** Hopefully none.
14 ///
15 /// **Example:** `if a == b { .. } else if a == b { .. }`
16 declare_lint! {
17     pub IFS_SAME_COND,
18     Warn,
19     "consecutive `ifs` with the same condition"
20 }
21
22 /// **What it does:** This lint checks for `if/else` with the same body as the *then* part and the
23 /// *else* part. This lint is `Warn` by default.
24 ///
25 /// **Why is this bad?** This is probably a copy & paste error.
26 ///
27 /// **Known problems:** Hopefully none.
28 ///
29 /// **Example:** `if .. { 42 } else { 42 }`
30 declare_lint! {
31     pub IF_SAME_THEN_ELSE,
32     Warn,
33     "if with the same *then* and *else* blocks"
34 }
35
36 #[derive(Copy, Clone, Debug)]
37 pub struct CopyAndPaste;
38
39 impl LintPass for CopyAndPaste {
40     fn get_lints(&self) -> LintArray {
41         lint_array![
42             IFS_SAME_COND,
43             IF_SAME_THEN_ELSE
44         ]
45     }
46 }
47
48 impl LateLintPass for CopyAndPaste {
49     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
50         if !in_macro(cx, expr.span) {
51             // skip ifs directly in else, it will be checked in the parent if
52             if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
53                 if else_expr.id == expr.id {
54                     return;
55                 }
56             }
57
58             let (conds, blocks) = if_sequence(expr);
59             lint_same_then_else(cx, &blocks);
60             lint_same_cond(cx, &conds);
61         }
62     }
63 }
64
65 /// Implementation of `IF_SAME_THEN_ELSE`.
66 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
67     let hash = |block| -> u64 {
68         let mut h = SpanlessHash::new(cx);
69         h.hash_block(block);
70         h.finish()
71     };
72     let eq = |lhs, rhs| -> bool {
73         SpanlessEq::new(cx).eq_block(lhs, rhs)
74     };
75
76     if let Some((i, j)) = search_same(blocks, hash, eq) {
77         span_note_and_lint(cx, IF_SAME_THEN_ELSE, j.span, "this if has identical blocks", i.span, "same as this");
78     }
79 }
80
81 /// Implementation of `IFS_SAME_COND`.
82 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
83     let hash = |expr| -> u64 {
84         let mut h = SpanlessHash::new(cx);
85         h.hash_expr(expr);
86         h.finish()
87     };
88     let eq = |lhs, rhs| -> bool {
89         SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs)
90     };
91
92     if let Some((i, j)) = search_same(conds, hash, eq) {
93         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");
94     }
95 }
96
97 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
98 /// Eg. would return `([a, b], [c, d, e])` for the expression
99 /// `if a { c } else if b { d } else { e }`.
100 fn if_sequence(mut expr: &Expr) -> (Vec<&Expr>, Vec<&Block>) {
101     let mut conds = vec![];
102     let mut blocks = vec![];
103
104     while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
105         conds.push(&**cond);
106         blocks.push(&**then_block);
107
108         if let Some(ref else_expr) = *else_expr {
109             expr = else_expr;
110         }
111         else {
112             break;
113         }
114     }
115
116     // final `else {..}`
117     if !blocks.is_empty() {
118         if let ExprBlock(ref block) = expr.node {
119             blocks.push(&**block);
120         }
121     }
122
123     (conds, blocks)
124 }
125
126 fn search_same<'a, T, Hash, Eq>(exprs: &[&'a T],
127                                 hash: Hash,
128                                 eq: Eq) -> Option<(&'a T, &'a T)>
129 where Hash: Fn(&'a T) -> u64,
130       Eq: Fn(&'a T, &'a T) -> bool {
131     // common cases
132     if exprs.len() < 2 {
133         return None;
134     }
135     else if exprs.len() == 2 {
136         return if eq(&exprs[0], &exprs[1]) {
137             Some((&exprs[0], &exprs[1]))
138         }
139         else {
140             None
141         }
142     }
143
144     let mut map : HashMap<_, Vec<&'a _>> = HashMap::with_capacity(exprs.len());
145
146     for &expr in exprs {
147         match map.entry(hash(expr)) {
148             Entry::Occupied(o) => {
149                 for o in o.get() {
150                     if eq(o, expr) {
151                         return Some((o, expr))
152                     }
153                 }
154             }
155             Entry::Vacant(v) => { v.insert(vec![expr]); }
156         }
157     }
158
159     None
160 }