1 use crate::utils::{get_parent_expr, higher, if_sequence, 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 std::collections::hash_map::Entry;
9 use std::hash::BuildHasherDefault;
10 use syntax::symbol::Symbol;
12 declare_clippy_lint! {
13 /// **What it does:** Checks for consecutive `if`s with the same condition.
15 /// **Why is this bad?** This is probably a copy & paste error.
17 /// **Known problems:** Hopefully none.
23 /// } else if a == b {
28 /// Note that this lint ignores all conditions with a function call as it could
29 /// have side effects:
34 /// } else if foo() { // not linted
40 "consecutive `ifs` with the same condition"
43 declare_clippy_lint! {
44 /// **What it does:** Checks for `if/else` with the same body as the *then* part
45 /// and the *else* part.
47 /// **Why is this bad?** This is probably a copy & paste error.
49 /// **Known problems:** Hopefully none.
59 pub IF_SAME_THEN_ELSE,
61 "if with the same *then* and *else* blocks"
64 declare_clippy_lint! {
65 /// **What it does:** Checks for `match` with identical arm bodies.
67 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
68 /// are the same on purpose, you can factor them
69 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
71 /// **Known problems:** False positive possible with order dependent `match`
73 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
80 /// Baz => bar(), // <= oops
84 /// This should probably be
89 /// Baz => baz(), // <= fixed
93 /// or if the original code was not a typo:
96 /// Bar | Baz => bar(), // <= shows the intent better
102 "`match` with identical arm bodies"
105 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
108 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
109 if !expr.span.from_expansion() {
110 // skip ifs directly in else, it will be checked in the parent if
111 if let Some(expr) = get_parent_expr(cx, expr) {
112 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
113 if else_expr.hir_id == expr.hir_id {
119 let (conds, blocks) = if_sequence(expr);
120 lint_same_then_else(cx, &blocks);
121 lint_same_cond(cx, &conds);
122 lint_match_arms(cx, expr);
127 /// Implementation of `IF_SAME_THEN_ELSE`.
128 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
129 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
131 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
136 "this `if` has identical blocks",
143 /// Implementation of `IFS_SAME_COND`.
144 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
145 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
146 let mut h = SpanlessHash::new(cx, cx.tables);
151 let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
152 &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
154 for (i, j) in search_same(conds, hash, eq) {
159 "this `if` has the same condition as a previous if",
166 /// Implementation of `MATCH_SAME_ARMS`.
167 fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr) {
168 fn same_bindings<'tcx>(
169 cx: &LateContext<'_, 'tcx>,
170 lhs: &FxHashMap<Symbol, Ty<'tcx>>,
171 rhs: &FxHashMap<Symbol, Ty<'tcx>>,
173 lhs.len() == rhs.len()
176 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| same_tys(cx, l_ty, r_ty)))
179 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
180 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
181 let mut h = SpanlessHash::new(cx, cx.tables);
182 h.hash_expr(&arm.body);
186 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
187 let min_index = usize::min(lindex, rindex);
188 let max_index = usize::max(lindex, rindex);
190 // Arms with a guard are ignored, those can’t always be merged together
191 // This is also the case for arms in-between each there is an arm with a guard
192 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
193 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
194 // all patterns should have the same bindings
195 same_bindings(cx, &bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
198 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
199 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
204 "this `match` has identical arm bodies",
206 db.span_note(i.body.span, "same as this");
208 // Note: this does not use `span_suggestion` on purpose:
209 // there is no clean way
210 // to remove the other arm. Building a span and suggest to replace it to ""
211 // makes an even more confusing error message. Also in order not to make up a
212 // span for the whole pattern, the suggestion is only shown when there is only
213 // one pattern. The user should know about `|` if they are already using it…
215 let lhs = snippet(cx, i.pat.span, "<pat1>");
216 let rhs = snippet(cx, j.pat.span, "<pat2>");
218 if let PatKind::Wild = j.pat.kind {
219 // if the last arm is _, then i could be integrated into _
220 // note that i.pat cannot be _, because that would mean that we're
221 // hiding all the subsequent arms, and rust won't compile
225 "`{}` has the same arm body as the `_` wildcard, consider removing it`",
230 db.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
238 /// Returns the list of bindings in a pattern.
239 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<Symbol, Ty<'tcx>> {
240 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
242 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
243 PatKind::TupleStruct(_, ref pats, _) => {
245 bindings_impl(cx, pat, map);
248 PatKind::Binding(.., ident, ref as_pat) => {
249 if let Entry::Vacant(v) = map.entry(ident.name) {
250 v.insert(cx.tables.pat_ty(pat));
252 if let Some(ref as_pat) = *as_pat {
253 bindings_impl(cx, as_pat, map);
256 PatKind::Or(ref fields) | PatKind::Tuple(ref fields, _) => {
258 bindings_impl(cx, pat, map);
261 PatKind::Struct(_, ref fields, _) => {
263 bindings_impl(cx, &pat.pat, map);
266 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
268 bindings_impl(cx, pat, map);
270 if let Some(ref mid) = *mid {
271 bindings_impl(cx, mid, map);
274 bindings_impl(cx, pat, map);
277 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
281 let mut result = FxHashMap::default();
282 bindings_impl(cx, pat, &mut result);
286 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
288 Eq: Fn(&T, &T) -> bool,
290 for win in exprs.windows(2) {
291 if eq(&win[0], &win[1]) {
292 return Some((&win[0], &win[1]));
298 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
300 Eq: Fn(&T, &T) -> bool,
302 if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
303 Some((&exprs[0], &exprs[1]))
309 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
312 Eq: Fn(&T, &T) -> bool,
314 if let Some(expr) = search_common_cases(&exprs, &eq) {
318 let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
320 let mut map: FxHashMap<_, Vec<&_>> =
321 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
324 match map.entry(hash(expr)) {
325 Entry::Occupied(mut o) => {
328 match_expr_list.push((o, expr));
331 o.get_mut().push(expr);
333 Entry::Vacant(v) => {
334 v.insert(vec![expr]);