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. If arm bodies are the same on
42 /// purpose, you can factor them
43 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
45 /// **Known problems:** Hopefully none.
52 /// Baz => bar(), // <= oops
58 "`match` with identical arm bodies"
61 #[derive(Copy, Clone, Debug)]
62 pub struct CopyAndPaste;
64 impl LintPass for CopyAndPaste {
65 fn get_lints(&self) -> LintArray {
66 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
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.as_slice());
82 lint_same_cond(cx, conds.as_slice());
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 { SpanlessEq::new(cx).eq_block(lhs, rhs) };
98 if let Some((i, j)) = search_same(blocks, hash, eq) {
99 span_note_and_lint(cx,
102 "this `if` has identical blocks",
108 /// Implementation of `IFS_SAME_COND`.
109 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
110 let hash: &Fn(&&Expr) -> u64 = &|expr| -> u64 {
111 let mut h = SpanlessHash::new(cx);
116 let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
118 if let Some((i, j)) = search_same(conds, hash, eq) {
119 span_note_and_lint(cx,
122 "this `if` has the same condition as a previous if",
128 /// Implementation if `MATCH_SAME_ARMS`.
129 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
130 let hash = |arm: &Arm| -> u64 {
131 let mut h = SpanlessHash::new(cx);
132 h.hash_expr(&arm.body);
136 let eq = |lhs: &Arm, rhs: &Arm| -> bool {
137 // Arms with a guard are ignored, those can’t always be merged together
138 lhs.guard.is_none() && rhs.guard.is_none() &&
139 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
140 // all patterns should have the same bindings
141 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
144 if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
145 if let Some((i, j)) = search_same(&arms, hash, eq) {
146 span_note_and_lint(cx,
149 "this `match` has identical arm bodies",
156 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
157 /// Eg. would return `([a, b], [c, d, e])` for the expression
158 /// `if a { c } else if b { d } else { e }`.
159 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
160 let mut conds = SmallVector::zero();
161 let mut blocks = SmallVector::zero();
163 while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
165 blocks.push(&**then_block);
167 if let Some(ref else_expr) = *else_expr {
175 if !blocks.is_empty() {
176 if let ExprBlock(ref block) = expr.node {
177 blocks.push(&**block);
184 /// Return the list of bindings in a pattern.
185 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
186 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
188 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
189 PatKind::TupleStruct(_, Some(ref pats)) => {
191 bindings_impl(cx, pat, map);
194 PatKind::Ident(_, ref ident, ref as_pat) => {
195 if let Entry::Vacant(v) = map.entry(ident.node.name.as_str()) {
196 v.insert(cx.tcx.pat_ty(pat));
198 if let Some(ref as_pat) = *as_pat {
199 bindings_impl(cx, as_pat, map);
202 PatKind::Struct(_, ref fields, _) => {
204 bindings_impl(cx, &pat.node.pat, map);
207 PatKind::Tup(ref fields) => {
209 bindings_impl(cx, pat, map);
212 PatKind::Vec(ref lhs, ref mid, ref rhs) => {
214 bindings_impl(cx, pat, map);
216 if let Some(ref mid) = *mid {
217 bindings_impl(cx, mid, map);
220 bindings_impl(cx, pat, map);
223 PatKind::TupleStruct(..) |
228 PatKind::Path(..) => (),
232 let mut result = HashMap::new();
233 bindings_impl(cx, pat, &mut result);
237 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
238 where Hash: Fn(&T) -> u64,
239 Eq: Fn(&T, &T) -> bool
244 } else if exprs.len() == 2 {
245 return if eq(&exprs[0], &exprs[1]) {
246 Some((&exprs[0], &exprs[1]))
252 let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
255 match map.entry(hash(expr)) {
256 Entry::Occupied(o) => {
259 return Some((&o, expr));
263 Entry::Vacant(v) => {
264 v.insert(vec![expr]);