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};
10 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
11 /// `Warn` by default.
13 /// **Why is this bad?** This is probably a copy & paste error.
15 /// **Known problems:** Hopefully none.
17 /// **Example:** `if a == b { .. } else if a == b { .. }`
21 "consecutive `ifs` with the same condition"
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.
27 /// **Why is this bad?** This is probably a copy & paste error.
29 /// **Known problems:** Hopefully none.
31 /// **Example:** `if .. { 42 } else { 42 }`
33 pub IF_SAME_THEN_ELSE,
35 "if with the same *then* and *else* blocks"
38 /// **What it does:** This lint checks for `match` with identical arm bodies.
40 /// **Why is this bad?** This is probably a copy & paste error.
42 /// **Known problems:** Hopefully none.
49 /// Baz => bar(), // <= oups
54 "`match` with identical arm bodies"
57 #[derive(Copy, Clone, Debug)]
58 pub struct CopyAndPaste;
60 impl LintPass for CopyAndPaste {
61 fn get_lints(&self) -> LintArray {
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 {
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);
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);
96 let eq : &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool {
97 SpanlessEq::new(cx).eq_block(lhs, rhs)
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");
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);
113 let eq : &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool {
114 SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs)
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");
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);
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])
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");
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![];
150 while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
152 blocks.push(&**then_block);
154 if let Some(ref else_expr) = *else_expr {
163 if !blocks.is_empty() {
164 if let ExprBlock(ref block) = expr.node {
165 blocks.push(&**block);
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>>) {
176 PatBox(ref pat) | PatRegion(ref pat, _) => bindings_impl(cx, pat, map),
177 PatEnum(_, Some(ref pats)) => {
179 bindings_impl(cx, pat, map);
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));
186 if let Some(ref as_pat) = *as_pat {
187 bindings_impl(cx, as_pat, map);
190 PatStruct(_, ref fields, _) => {
192 bindings_impl(cx, &pat.node.pat, map);
195 PatTup(ref fields) => {
197 bindings_impl(cx, pat, map);
200 PatVec(ref lhs, ref mid, ref rhs) => {
202 bindings_impl(cx, pat, map);
204 if let Some(ref mid) = *mid {
205 bindings_impl(cx, mid, map);
208 bindings_impl(cx, pat, map);
211 PatEnum(..) | PatLit(..) | PatQPath(..) | PatRange(..) | PatWild => (),
215 let mut result = HashMap::new();
216 bindings_impl(cx, pat, &mut result);
220 fn search_same<T, Hash, Eq>(exprs: &[T],
222 eq: Eq) -> Option<(&T, &T)>
223 where Hash: Fn(&T) -> u64,
224 Eq: Fn(&T, &T) -> bool {
229 else if exprs.len() == 2 {
230 return if eq(&exprs[0], &exprs[1]) {
231 Some((&exprs[0], &exprs[1]))
238 let mut map : HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
241 match map.entry(hash(expr)) {
242 Entry::Occupied(o) => {
245 return Some((&o, expr))
249 Entry::Vacant(v) => { v.insert(vec![expr]); }