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_lint_and_then, span_note_and_lint, snippet};
11 /// **What it does:** This lint checks for consecutive `ifs` with the same condition.
13 /// **Why is this bad?** This is probably a copy & paste error.
15 /// **Known problems:** Hopefully none.
21 /// } else if a == b {
26 /// Note that this lint ignores all conditions with a function call as it could have side effects:
31 /// } else if foo() { // not linted
38 "consecutive `ifs` with the same condition"
41 /// **What it does:** This lint checks for `if/else` with the same body as the *then* part and the
44 /// **Why is this bad?** This is probably a copy & paste error.
46 /// **Known problems:** Hopefully none.
57 pub IF_SAME_THEN_ELSE,
59 "if with the same *then* and *else* blocks"
62 /// **What it does:** This lint checks for `match` with identical arm bodies.
64 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies are the same on
65 /// purpose, you can factor them
66 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
68 /// **Known problems:** False positive possible with order dependent `match`
69 /// (see issue [#860](https://github.com/Manishearth/rust-clippy/issues/860)).
76 /// Baz => bar(), // <= oops
80 /// This should probably be
85 /// Baz => baz(), // <= fixed
89 /// or if the original code was not a typo:
92 /// Bar | Baz => bar(), // <= shows the intent better
99 "`match` with identical arm bodies"
102 #[derive(Copy, Clone, Debug)]
103 pub struct CopyAndPaste;
105 impl LintPass for CopyAndPaste {
106 fn get_lints(&self) -> LintArray {
107 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
111 impl LateLintPass for CopyAndPaste {
112 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
113 if !in_macro(cx, expr.span) {
114 // skip ifs directly in else, it will be checked in the parent if
115 if let Some(&Expr { node: ExprIf(_, _, Some(ref else_expr)), .. }) = get_parent_expr(cx, expr) {
116 if else_expr.id == expr.id {
121 let (conds, blocks) = if_sequence(expr);
122 lint_same_then_else(cx, blocks.as_slice());
123 lint_same_cond(cx, conds.as_slice());
124 lint_match_arms(cx, expr);
129 /// Implementation of `IF_SAME_THEN_ELSE`.
130 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
131 let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
132 let mut h = SpanlessHash::new(cx);
137 let eq: &Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
139 if let Some((i, j)) = search_same(blocks, hash, eq) {
140 span_note_and_lint(cx,
143 "this `if` has identical blocks",
149 /// Implementation of `IFS_SAME_COND`.
150 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
151 let hash: &Fn(&&Expr) -> u64 = &|expr| -> u64 {
152 let mut h = SpanlessHash::new(cx);
157 let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
159 if let Some((i, j)) = search_same(conds, hash, eq) {
160 span_note_and_lint(cx,
163 "this `if` has the same condition as a previous if",
169 /// Implementation if `MATCH_SAME_ARMS`.
170 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
171 let hash = |arm: &Arm| -> u64 {
172 let mut h = SpanlessHash::new(cx);
173 h.hash_expr(&arm.body);
177 let eq = |lhs: &Arm, rhs: &Arm| -> bool {
178 // Arms with a guard are ignored, those can’t always be merged together
179 lhs.guard.is_none() && rhs.guard.is_none() &&
180 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
181 // all patterns should have the same bindings
182 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
185 if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
186 if let Some((i, j)) = search_same(arms, hash, eq) {
187 span_lint_and_then(cx,
190 "this `match` has identical arm bodies",
192 db.span_note(i.body.span, "same as this");
194 // Note: this does not use `span_suggestion` on purpose: there is no clean way to
195 // remove the other arm. Building a span and suggest to replace it to "" makes an
196 // even more confusing error message. Also in order not to make up a span for the
197 // whole pattern, the suggestion is only shown when there is only one pattern. The
198 // user should know about `|` if they are already using it…
200 if i.pats.len() == 1 && j.pats.len() == 1 {
201 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
202 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
203 db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
210 /// Return the list of condition expressions and the list of blocks in a sequence of `if/else`.
211 /// Eg. would return `([a, b], [c, d, e])` for the expression
212 /// `if a { c } else if b { d } else { e }`.
213 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
214 let mut conds = SmallVector::zero();
215 let mut blocks = SmallVector::zero();
217 while let ExprIf(ref cond, ref then_block, ref else_expr) = expr.node {
219 blocks.push(&**then_block);
221 if let Some(ref else_expr) = *else_expr {
229 if !blocks.is_empty() {
230 if let ExprBlock(ref block) = expr.node {
231 blocks.push(&**block);
238 /// Return the list of bindings in a pattern.
239 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, ty::Ty<'tcx>> {
240 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, ty::Ty<'tcx>>) {
242 PatKind::Box(ref pat) |
243 PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
244 PatKind::TupleStruct(_, ref pats, _) => {
246 bindings_impl(cx, pat, map);
249 PatKind::Binding(_, ref ident, ref as_pat) => {
250 if let Entry::Vacant(v) = map.entry(ident.node.as_str()) {
251 v.insert(cx.tcx.pat_ty(pat));
253 if let Some(ref as_pat) = *as_pat {
254 bindings_impl(cx, as_pat, map);
257 PatKind::Struct(_, ref fields, _) => {
259 bindings_impl(cx, &pat.node.pat, map);
262 PatKind::Tuple(ref fields, _) => {
264 bindings_impl(cx, pat, map);
267 PatKind::Vec(ref lhs, ref mid, ref rhs) => {
269 bindings_impl(cx, pat, map);
271 if let Some(ref mid) = *mid {
272 bindings_impl(cx, mid, map);
275 bindings_impl(cx, pat, map);
281 PatKind::Path(..) => (),
285 let mut result = HashMap::new();
286 bindings_impl(cx, pat, &mut result);
290 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
291 where Hash: Fn(&T) -> u64,
292 Eq: Fn(&T, &T) -> bool
297 } else if exprs.len() == 2 {
298 return if eq(&exprs[0], &exprs[1]) {
299 Some((&exprs[0], &exprs[1]))
305 let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
308 match map.entry(hash(expr)) {
309 Entry::Occupied(o) => {
312 return Some((o, expr));
316 Entry::Vacant(v) => {
317 v.insert(vec![expr]);