1 use crate::utils::{get_parent_expr, higher, same_tys, snippet, span_lint_and_then, span_note_and_lint};
2 use crate::utils::{SpanlessEq, SpanlessHash};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_data_structures::fx::FxHashMap;
8 use smallvec::SmallVec;
9 use std::collections::hash_map::Entry;
10 use std::hash::BuildHasherDefault;
11 use syntax::symbol::Symbol;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for consecutive `if`s with the same condition.
16 /// **Why is this bad?** This is probably a copy & paste error.
18 /// **Known problems:** Hopefully none.
24 /// } else if a == b {
29 /// Note that this lint ignores all conditions with a function call as it could
30 /// have side effects:
35 /// } else if foo() { // not linted
41 "consecutive `ifs` with the same condition"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for `if/else` with the same body as the *then* part
46 /// and the *else* part.
48 /// **Why is this bad?** This is probably a copy & paste error.
50 /// **Known problems:** Hopefully none.
60 pub IF_SAME_THEN_ELSE,
62 "if with the same *then* and *else* blocks"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for `match` with identical arm bodies.
68 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
69 /// are the same on purpose, you can factor them
70 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
72 /// **Known problems:** False positive possible with order dependent `match`
74 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
81 /// Baz => bar(), // <= oops
85 /// This should probably be
90 /// Baz => baz(), // <= fixed
94 /// or if the original code was not a typo:
97 /// Bar | Baz => bar(), // <= shows the intent better
103 "`match` with identical arm bodies"
106 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
108 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
109 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
110 if !expr.span.from_expansion() {
111 // skip ifs directly in else, it will be checked in the parent if
112 if let Some(expr) = get_parent_expr(cx, expr) {
113 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
114 if else_expr.hir_id == expr.hir_id {
120 let (conds, blocks) = if_sequence(expr);
121 lint_same_then_else(cx, &blocks);
122 lint_same_cond(cx, &conds);
123 lint_match_arms(cx, expr);
128 /// Implementation of `IF_SAME_THEN_ELSE`.
129 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
130 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
132 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
137 "this `if` has identical blocks",
144 /// Implementation of `IFS_SAME_COND`.
145 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
146 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
147 let mut h = SpanlessHash::new(cx, cx.tables);
152 let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
153 &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
155 for (i, j) in search_same(conds, hash, eq) {
160 "this `if` has the same condition as a previous if",
167 /// Implementation of `MATCH_SAME_ARMS`.
168 fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr) {
169 fn same_bindings<'tcx>(
170 cx: &LateContext<'_, 'tcx>,
171 lhs: &FxHashMap<Symbol, Ty<'tcx>>,
172 rhs: &FxHashMap<Symbol, Ty<'tcx>>,
174 lhs.len() == rhs.len()
177 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| same_tys(cx, l_ty, r_ty)))
180 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node {
181 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
182 let mut h = SpanlessHash::new(cx, cx.tables);
183 h.hash_expr(&arm.body);
187 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
188 let min_index = usize::min(lindex, rindex);
189 let max_index = usize::max(lindex, rindex);
191 // Arms with a guard are ignored, those can’t always be merged together
192 // This is also the case for arms in-between each there is an arm with a guard
193 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
194 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
195 // all patterns should have the same bindings
196 same_bindings(cx, &bindings(cx, &lhs.pats[0]), &bindings(cx, &rhs.pats[0]))
199 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
200 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
205 "this `match` has identical arm bodies",
207 db.span_note(i.body.span, "same as this");
209 // Note: this does not use `span_suggestion` on purpose:
210 // there is no clean way
211 // to remove the other arm. Building a span and suggest to replace it to ""
212 // makes an even more confusing error message. Also in order not to make up a
213 // span for the whole pattern, the suggestion is only shown when there is only
214 // one pattern. The user should know about `|` if they are already using it…
216 if i.pats.len() == 1 && j.pats.len() == 1 {
217 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
218 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
220 if let PatKind::Wild = j.pats[0].node {
221 // if the last arm is _, then i could be integrated into _
222 // note that i.pats[0] cannot be _, because that would mean that we're
223 // hiding all the subsequent arms, and rust won't compile
227 "`{}` has the same arm body as the `_` wildcard, consider removing it`",
234 &format!("consider refactoring into `{} | {}`", lhs, rhs),
244 /// Returns the list of condition expressions and the list of blocks in a
245 /// sequence of `if/else`.
246 /// E.g., this returns `([a, b], [c, d, e])` for the expression
247 /// `if a { c } else if b { d } else { e }`.
248 fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
249 let mut conds = SmallVec::new();
250 let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
252 while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
254 if let ExprKind::Block(ref block, _) = then_expr.node {
257 panic!("ExprKind::If node is not an ExprKind::Block");
260 if let Some(ref else_expr) = *else_expr {
268 if !blocks.is_empty() {
269 if let ExprKind::Block(ref block, _) = expr.node {
270 blocks.push(&**block);
277 /// Returns the list of bindings in a pattern.
278 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<Symbol, Ty<'tcx>> {
279 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
281 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
282 PatKind::TupleStruct(_, ref pats, _) => {
284 bindings_impl(cx, pat, map);
287 PatKind::Binding(.., ident, ref as_pat) => {
288 if let Entry::Vacant(v) = map.entry(ident.name) {
289 v.insert(cx.tables.pat_ty(pat));
291 if let Some(ref as_pat) = *as_pat {
292 bindings_impl(cx, as_pat, map);
295 PatKind::Or(ref fields) | PatKind::Tuple(ref fields, _) => {
297 bindings_impl(cx, pat, map);
300 PatKind::Struct(_, ref fields, _) => {
302 bindings_impl(cx, &pat.pat, map);
305 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
307 bindings_impl(cx, pat, map);
309 if let Some(ref mid) = *mid {
310 bindings_impl(cx, mid, map);
313 bindings_impl(cx, pat, map);
316 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
320 let mut result = FxHashMap::default();
321 bindings_impl(cx, pat, &mut result);
325 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
327 Eq: Fn(&T, &T) -> bool,
329 for win in exprs.windows(2) {
330 if eq(&win[0], &win[1]) {
331 return Some((&win[0], &win[1]));
337 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
339 Eq: Fn(&T, &T) -> bool,
343 } else if exprs.len() == 2 {
344 if eq(&exprs[0], &exprs[1]) {
345 Some((&exprs[0], &exprs[1]))
354 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
357 Eq: Fn(&T, &T) -> bool,
359 if let Some(expr) = search_common_cases(&exprs, &eq) {
363 let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
365 let mut map: FxHashMap<_, Vec<&_>> =
366 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
369 match map.entry(hash(expr)) {
370 Entry::Occupied(mut o) => {
373 match_expr_list.push((o, expr));
376 o.get_mut().push(expr);
378 Entry::Vacant(v) => {
379 v.insert(vec![expr]);