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};
11 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
12 /// `Warn` by default.
14 /// **Why is this bad?** This is probably a copy & paste error.
16 /// **Known problems:** Hopefully none.
18 /// **Example:** `if a == b { .. } else if a == b { .. }`
22 "consecutive `ifs` with the same condition"
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.
28 /// **Why is this bad?** This is probably a copy & paste error.
30 /// **Known problems:** Hopefully none.
32 /// **Example:** `if .. { 42 } else { 42 }`
34 pub IF_SAME_THEN_ELSE,
36 "if with the same *then* and *else* blocks"
39 /// **What it does:** This lint checks for `match` with identical arm bodies.
41 /// **Why is this bad?** This is probably a copy & paste error.
43 /// **Known problems:** Hopefully none.
50 /// Baz => bar(), // <= oups
56 "`match` with identical arm bodies"
59 #[derive(Copy, Clone, Debug)]
60 pub struct CopyAndPaste;
62 impl LintPass for CopyAndPaste {
63 fn get_lints(&self) -> LintArray {
64 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
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 {
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);
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);
94 let eq: &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
96 if let Some((i, j)) = search_same(blocks, hash, eq) {
97 span_note_and_lint(cx,
100 "this `if` has identical blocks",
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);
114 let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
116 if let Some((i, j)) = search_same(conds, hash, eq) {
117 span_note_and_lint(cx,
120 "this `if` has the same condition as a previous if",
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);
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])
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,
145 "this `match` has identical arm bodies",
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();
159 while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
161 blocks.push(&**then_block);
163 if let Some(ref else_expr) = *else_expr {
171 if !blocks.is_empty() {
172 if let ExprBlock(ref block) = expr.node {
173 blocks.push(&**block);
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>>) {
184 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
185 PatKind::TupleStruct(_, Some(ref pats)) => {
187 bindings_impl(cx, pat, map);
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));
194 if let Some(ref as_pat) = *as_pat {
195 bindings_impl(cx, as_pat, map);
198 PatKind::Struct(_, ref fields, _) => {
200 bindings_impl(cx, &pat.node.pat, map);
203 PatKind::Tup(ref fields) => {
205 bindings_impl(cx, pat, map);
208 PatKind::Vec(ref lhs, ref mid, ref rhs) => {
210 bindings_impl(cx, pat, map);
212 if let Some(ref mid) = *mid {
213 bindings_impl(cx, mid, map);
216 bindings_impl(cx, pat, map);
219 PatKind::TupleStruct(..) |
224 PatKind::Path(..) => (),
228 let mut result = HashMap::new();
229 bindings_impl(cx, pat, &mut result);
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
240 } else if exprs.len() == 2 {
241 return if eq(&exprs[0], &exprs[1]) {
242 Some((&exprs[0], &exprs[1]))
248 let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
251 match map.entry(hash(expr)) {
252 Entry::Occupied(o) => {
255 return Some((&o, expr));
259 Entry::Vacant(v) => {
260 v.insert(vec![expr]);