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 {
72 impl LateLintPass for CopyAndPaste {
73 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
74 if !in_macro(cx, expr.span) {
75 // skip ifs directly in else, it will be checked in the parent if
76 if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
77 if else_expr.id == expr.id {
82 let (conds, blocks) = if_sequence(expr);
83 lint_same_then_else(cx, blocks.as_slice());
84 lint_same_cond(cx, conds.as_slice());
85 lint_match_arms(cx, expr);
90 /// Implementation of `IF_SAME_THEN_ELSE`.
91 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
92 let hash : &Fn(&&Block) -> u64 = &|block| -> u64 {
93 let mut h = SpanlessHash::new(cx);
98 let eq : &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool {
99 SpanlessEq::new(cx).eq_block(lhs, rhs)
102 if let Some((i, j)) = search_same(blocks, hash, eq) {
103 span_note_and_lint(cx, IF_SAME_THEN_ELSE, j.span, "this `if` has identical blocks", i.span, "same as this");
107 /// Implementation of `IFS_SAME_COND`.
108 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
109 let hash : &Fn(&&Expr) -> u64 = &|expr| -> u64 {
110 let mut h = SpanlessHash::new(cx);
115 let eq : &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool {
116 SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs)
119 if let Some((i, j)) = search_same(conds, hash, eq) {
120 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");
124 /// Implementation if `MATCH_SAME_ARMS`.
125 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
126 let hash = |arm: &Arm| -> u64 {
127 let mut h = SpanlessHash::new(cx);
128 h.hash_expr(&arm.body);
132 let eq = |lhs: &Arm, rhs: &Arm| -> bool {
133 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
134 // all patterns should have the same bindings
135 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
138 if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
139 if let Some((i, j)) = search_same(&**arms, hash, eq) {
140 span_note_and_lint(cx, MATCH_SAME_ARMS, j.body.span, "this `match` has identical arm bodies", i.body.span, "same as this");
145 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
146 /// Eg. would return `([a, b], [c, d, e])` for the expression
147 /// `if a { c } else if b { d } else { e }`.
148 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
149 let mut conds = SmallVector::zero();
150 let mut blocks = SmallVector::zero();
152 while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
154 blocks.push(&**then_block);
156 if let Some(ref else_expr) = *else_expr {
165 if !blocks.is_empty() {
166 if let ExprBlock(ref block) = expr.node {
167 blocks.push(&**block);
174 /// Return the list of bindings in a pattern.
175 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
176 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
178 PatBox(ref pat) | PatRegion(ref pat, _) => bindings_impl(cx, pat, map),
179 PatEnum(_, Some(ref pats)) => {
181 bindings_impl(cx, pat, map);
184 PatIdent(_, ref ident, ref as_pat) => {
185 if let Entry::Vacant(v) = map.entry(ident.node.name.as_str()) {
186 v.insert(cx.tcx.pat_ty(pat));
188 if let Some(ref as_pat) = *as_pat {
189 bindings_impl(cx, as_pat, map);
192 PatStruct(_, ref fields, _) => {
194 bindings_impl(cx, &pat.node.pat, map);
197 PatTup(ref fields) => {
199 bindings_impl(cx, pat, map);
202 PatVec(ref lhs, ref mid, ref rhs) => {
204 bindings_impl(cx, pat, map);
206 if let Some(ref mid) = *mid {
207 bindings_impl(cx, mid, map);
210 bindings_impl(cx, pat, map);
213 PatEnum(..) | PatLit(..) | PatQPath(..) | PatRange(..) | PatWild => (),
217 let mut result = HashMap::new();
218 bindings_impl(cx, pat, &mut result);
222 fn search_same<T, Hash, Eq>(exprs: &[T],
224 eq: Eq) -> Option<(&T, &T)>
225 where Hash: Fn(&T) -> u64,
226 Eq: Fn(&T, &T) -> bool {
231 else if exprs.len() == 2 {
232 return if eq(&exprs[0], &exprs[1]) {
233 Some((&exprs[0], &exprs[1]))
240 let mut map : HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
243 match map.entry(hash(expr)) {
244 Entry::Occupied(o) => {
247 return Some((&o, expr))
251 Entry::Vacant(v) => { v.insert(vec![expr]); }