]> git.lizzy.rs Git - rust.git/blob - src/copies.rs
Implement Expr spanless-hashing
[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_lint, 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, expr);
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, expr: &Expr) {
67     if let ExprIf(_, ref then_block, Some(ref else_expr)) = expr.node {
68         if let ExprBlock(ref else_block) = else_expr.node {
69             if SpanlessEq::new(cx).eq_block(&then_block, &else_block) {
70                 span_lint(cx, IF_SAME_THEN_ELSE, expr.span, "this if has the same then and else blocks");
71             }
72         }
73     }
74 }
75
76 /// Implementation of `IFS_SAME_COND`.
77 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
78     if let Some((i, j)) = search_same(cx, conds) {
79         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");
80     }
81 }
82
83 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
84 /// Eg. would return `([a, b], [c, d, e])` for the expression
85 /// `if a { c } else if b { d } else { e }`.
86 fn if_sequence(mut expr: &Expr) -> (Vec<&Expr>, Vec<&Block>) {
87     let mut conds = vec![];
88     let mut blocks = vec![];
89
90     while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
91         conds.push(&**cond);
92         blocks.push(&**then_block);
93
94         if let Some(ref else_expr) = *else_expr {
95             expr = else_expr;
96         }
97         else {
98             break;
99         }
100     }
101
102     // final `else {..}`
103     if !blocks.is_empty() {
104         if let ExprBlock(ref block) = expr.node {
105             blocks.push(&**block);
106         }
107     }
108
109     (conds, blocks)
110 }
111
112 fn search_same<'a>(cx: &LateContext, exprs: &[&'a Expr]) -> Option<(&'a Expr, &'a Expr)> {
113     // common cases
114     if exprs.len() < 2 {
115         return None;
116     }
117     else if exprs.len() == 2 {
118         return if SpanlessEq::new(cx).ignore_fn().eq_expr(&exprs[0], &exprs[1]) {
119             Some((&exprs[0], &exprs[1]))
120         }
121         else {
122             None
123         }
124     }
125
126     let mut map : HashMap<_, Vec<&'a _>> = HashMap::with_capacity(exprs.len());
127
128     for &expr in exprs {
129         let mut h = SpanlessHash::new(cx);
130         h.hash_expr(expr);
131         let h = h.finish();
132
133         match map.entry(h) {
134             Entry::Occupied(o) => {
135                 for o in o.get() {
136                     if SpanlessEq::new(cx).ignore_fn().eq_expr(o, expr) {
137                         return Some((o, expr))
138                     }
139                 }
140             }
141             Entry::Vacant(v) => { v.insert(vec![expr]); }
142         }
143     }
144
145     None
146 }