4 use std::collections::HashMap;
5 use std::collections::hash_map::Entry;
6 use syntax::symbol::InternedString;
7 use syntax::util::small_vector::SmallVector;
8 use utils::{SpanlessEq, SpanlessHash};
9 use utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
11 /// **What it does:** Checks for consecutive `if`s 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
27 /// have side effects:
32 /// } else if foo() { // not linted
36 declare_clippy_lint! {
39 "consecutive `ifs` with the same condition"
42 /// **What it does:** Checks for `if/else` with the same body as the *then* part
43 /// and the *else* part.
45 /// **Why is this bad?** This is probably a copy & paste error.
47 /// **Known problems:** Hopefully none.
57 declare_clippy_lint! {
58 pub IF_SAME_THEN_ELSE,
60 "if with the same *then* and *else* blocks"
63 /// **What it does:** Checks for `match` with identical arm bodies.
65 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
66 /// are the same on purpose, you can factor them
67 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
69 /// **Known problems:** False positive possible with order dependent `match`
71 /// [#860](https://github.com/rust-lang-nursery/rust-clippy/issues/860)).
78 /// Baz => bar(), // <= oops
82 /// This should probably be
87 /// Baz => baz(), // <= fixed
91 /// or if the original code was not a typo:
94 /// Bar | Baz => bar(), // <= shows the intent better
98 declare_clippy_lint! {
101 "`match` with identical arm bodies"
104 #[derive(Copy, Clone, Debug)]
105 pub struct CopyAndPaste;
107 impl LintPass for CopyAndPaste {
108 fn get_lints(&self) -> LintArray {
109 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
113 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
114 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
115 if !in_macro(expr.span) {
116 // skip ifs directly in else, it will be checked in the parent if
118 node: ExprIf(_, _, Some(ref else_expr)),
120 }) = get_parent_expr(cx, expr)
122 if else_expr.id == expr.id {
127 let (conds, blocks) = if_sequence(expr);
128 lint_same_then_else(cx, &blocks);
129 lint_same_cond(cx, &conds);
130 lint_match_arms(cx, expr);
135 /// Implementation of `IF_SAME_THEN_ELSE`.
136 fn lint_same_then_else(cx: &LateContext, blocks: &[&Block]) {
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_sequenced(blocks, eq) {
144 "this `if` has identical blocks",
151 /// Implementation of `IFS_SAME_COND`.
152 fn lint_same_cond(cx: &LateContext, conds: &[&Expr]) {
153 let hash: &Fn(&&Expr) -> u64 = &|expr| -> u64 {
154 let mut h = SpanlessHash::new(cx);
159 let eq: &Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
161 if let Some((i, j)) = search_same(conds, hash, eq) {
166 "this `if` has the same condition as a previous if",
173 /// Implementation if `MATCH_SAME_ARMS`.
174 fn lint_match_arms(cx: &LateContext, expr: &Expr) {
175 if let ExprMatch(_, ref arms, MatchSource::Normal) = expr.node {
176 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
177 let mut h = SpanlessHash::new(cx);
178 h.hash_expr(&arm.body);
182 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
183 let min_index = usize::min(lindex, rindex);
184 let max_index = usize::max(lindex, rindex);
185 // Arms with a guard are ignored, those can’t always be merged together
186 // This is also the case for arms in-between each there is an arm with a guard
187 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
188 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
189 // all patterns should have the same bindings
190 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
193 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
194 if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
199 "this `match` has identical arm bodies",
201 db.span_note(i.body.span, "same as this");
203 // Note: this does not use `span_suggestion` on purpose: there is no clean way
204 // to remove the other arm. Building a span and suggest to replace it to ""
205 // makes an even more confusing error message. Also in order not to make up a
206 // span for the whole pattern, the suggestion is only shown when there is only
207 // one pattern. The user should know about `|` if they are already using it…
209 if i.pats.len() == 1 && j.pats.len() == 1 {
210 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
211 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
213 if let PatKind::Wild = j.pats[0].node {
214 // if the last arm is _, then i could be integrated into _
215 // note that i.pats[0] cannot be _, because that would mean that we're
216 // hiding all the subsequent arms, and rust won't compile
219 &format!("`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs),
222 db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
231 /// Return the list of condition expressions and the list of blocks in a
232 /// sequence of `if/else`.
233 /// Eg. would return `([a, b], [c, d, e])` for the expression
234 /// `if a { c } else if b { d } else { e }`.
235 fn if_sequence(mut expr: &Expr) -> (SmallVector<&Expr>, SmallVector<&Block>) {
236 let mut conds = SmallVector::new();
237 let mut blocks: SmallVector<&Block> = SmallVector::new();
239 while let ExprIf(ref cond, ref then_expr, ref else_expr) = expr.node {
241 if let ExprBlock(ref block) = then_expr.node {
244 panic!("ExprIf node is not an ExprBlock");
247 if let Some(ref else_expr) = *else_expr {
255 if !blocks.is_empty() {
256 if let ExprBlock(ref block) = expr.node {
257 blocks.push(&**block);
264 /// Return the list of bindings in a pattern.
265 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<InternedString, Ty<'tcx>> {
266 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<InternedString, Ty<'tcx>>) {
268 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
269 PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
270 bindings_impl(cx, pat, map);
272 PatKind::Binding(_, _, ref ident, ref as_pat) => {
273 if let Entry::Vacant(v) = map.entry(ident.node.as_str()) {
274 v.insert(cx.tables.pat_ty(pat));
276 if let Some(ref as_pat) = *as_pat {
277 bindings_impl(cx, as_pat, map);
280 PatKind::Struct(_, ref fields, _) => for pat in fields {
281 bindings_impl(cx, &pat.node.pat, map);
283 PatKind::Tuple(ref fields, _) => for pat in fields {
284 bindings_impl(cx, pat, map);
286 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
288 bindings_impl(cx, pat, map);
290 if let Some(ref mid) = *mid {
291 bindings_impl(cx, mid, map);
294 bindings_impl(cx, pat, map);
297 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
301 let mut result = HashMap::new();
302 bindings_impl(cx, pat, &mut result);
307 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
309 Eq: Fn(&T, &T) -> bool,
311 for win in exprs.windows(2) {
312 if eq(&win[0], &win[1]) {
313 return Some((&win[0], &win[1]));
319 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
322 Eq: Fn(&T, &T) -> bool,
327 } else if exprs.len() == 2 {
328 return if eq(&exprs[0], &exprs[1]) {
329 Some((&exprs[0], &exprs[1]))
335 let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
338 match map.entry(hash(expr)) {
339 Entry::Occupied(mut o) => {
342 return Some((o, expr));
345 o.get_mut().push(expr);
347 Entry::Vacant(v) => {
348 v.insert(vec![expr]);