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};
3 use rustc::declare_lint_pass;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_session::declare_tool_lint;
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 consecutive `if`s with the same function call.
47 /// **Why is this bad?** This is probably a copy & paste error.
48 /// Despite the fact that function can have side effects and `if` works as
49 /// intended, such an approach is implicit and can be considered a "code smell".
51 /// **Known problems:** Hopefully none.
57 /// } else if foo() == bar {
62 /// This probably should be:
66 /// } else if foo() == baz {
71 /// or if the original code was not a typo and called function mutates a state,
72 /// consider move the mutation out of the `if` condition to avoid similarity to
73 /// a copy & paste error:
76 /// let first = foo();
80 /// let second = foo();
81 /// if second == bar {
86 pub SAME_FUNCTIONS_IN_IF_CONDITION,
88 "consecutive `ifs` with the same function call"
91 declare_clippy_lint! {
92 /// **What it does:** Checks for `if/else` with the same body as the *then* part
93 /// and the *else* part.
95 /// **Why is this bad?** This is probably a copy & paste error.
97 /// **Known problems:** Hopefully none.
107 pub IF_SAME_THEN_ELSE,
109 "if with the same *then* and *else* blocks"
112 declare_clippy_lint! {
113 /// **What it does:** Checks for `match` with identical arm bodies.
115 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
116 /// are the same on purpose, you can factor them
117 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
119 /// **Known problems:** False positive possible with order dependent `match`
121 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
128 /// Baz => bar(), // <= oops
132 /// This should probably be
137 /// Baz => baz(), // <= fixed
141 /// or if the original code was not a typo:
144 /// Bar | Baz => bar(), // <= shows the intent better
150 "`match` with identical arm bodies"
153 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, SAME_FUNCTIONS_IN_IF_CONDITION, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
155 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
156 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
157 if !expr.span.from_expansion() {
158 // skip ifs directly in else, it will be checked in the parent if
159 if let Some(expr) = get_parent_expr(cx, expr) {
160 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
161 if else_expr.hir_id == expr.hir_id {
167 let (conds, blocks) = if_sequence(expr);
168 lint_same_then_else(cx, &blocks);
169 lint_same_cond(cx, &conds);
170 lint_same_fns_in_if_cond(cx, &conds);
171 lint_match_arms(cx, expr);
176 /// Implementation of `IF_SAME_THEN_ELSE`.
177 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
178 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
180 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
185 "this `if` has identical blocks",
192 /// Implementation of `IFS_SAME_COND`.
193 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
194 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
195 let mut h = SpanlessHash::new(cx, cx.tables);
200 let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
201 &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
203 for (i, j) in search_same(conds, hash, eq) {
208 "this `if` has the same condition as a previous if",
215 /// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`.
216 fn lint_same_fns_in_if_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
217 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
218 let mut h = SpanlessHash::new(cx, cx.tables);
223 let eq: &dyn Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool {
224 // Do not spawn warning if `IFS_SAME_COND` already produced it.
225 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) {
228 SpanlessEq::new(cx).eq_expr(lhs, rhs)
231 for (i, j) in search_same(conds, hash, eq) {
234 SAME_FUNCTIONS_IN_IF_CONDITION,
236 "this `if` has the same function call as a previous if",
243 /// Implementation of `MATCH_SAME_ARMS`.
244 fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr) {
245 fn same_bindings<'tcx>(
246 cx: &LateContext<'_, 'tcx>,
247 lhs: &FxHashMap<Symbol, Ty<'tcx>>,
248 rhs: &FxHashMap<Symbol, Ty<'tcx>>,
250 lhs.len() == rhs.len()
253 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| same_tys(cx, l_ty, r_ty)))
256 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
257 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
258 let mut h = SpanlessHash::new(cx, cx.tables);
259 h.hash_expr(&arm.body);
263 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
264 let min_index = usize::min(lindex, rindex);
265 let max_index = usize::max(lindex, rindex);
267 // Arms with a guard are ignored, those can’t always be merged together
268 // This is also the case for arms in-between each there is an arm with a guard
269 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
270 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
271 // all patterns should have the same bindings
272 same_bindings(cx, &bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
275 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
276 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
281 "this `match` has identical arm bodies",
283 db.span_note(i.body.span, "same as this");
285 // Note: this does not use `span_suggestion` on purpose:
286 // there is no clean way
287 // to remove the other arm. Building a span and suggest to replace it to ""
288 // makes an even more confusing error message. Also in order not to make up a
289 // span for the whole pattern, the suggestion is only shown when there is only
290 // one pattern. The user should know about `|` if they are already using it…
292 let lhs = snippet(cx, i.pat.span, "<pat1>");
293 let rhs = snippet(cx, j.pat.span, "<pat2>");
295 if let PatKind::Wild = j.pat.kind {
296 // if the last arm is _, then i could be integrated into _
297 // note that i.pat cannot be _, because that would mean that we're
298 // hiding all the subsequent arms, and rust won't compile
302 "`{}` has the same arm body as the `_` wildcard, consider removing it`",
307 db.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
315 /// Returns the list of bindings in a pattern.
316 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<Symbol, Ty<'tcx>> {
317 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
319 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
320 PatKind::TupleStruct(_, ref pats, _) => {
322 bindings_impl(cx, pat, map);
325 PatKind::Binding(.., ident, ref as_pat) => {
326 if let Entry::Vacant(v) = map.entry(ident.name) {
327 v.insert(cx.tables.pat_ty(pat));
329 if let Some(ref as_pat) = *as_pat {
330 bindings_impl(cx, as_pat, map);
333 PatKind::Or(ref fields) | PatKind::Tuple(ref fields, _) => {
335 bindings_impl(cx, pat, map);
338 PatKind::Struct(_, ref fields, _) => {
340 bindings_impl(cx, &pat.pat, map);
343 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
345 bindings_impl(cx, pat, map);
347 if let Some(ref mid) = *mid {
348 bindings_impl(cx, mid, map);
351 bindings_impl(cx, pat, map);
354 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
358 let mut result = FxHashMap::default();
359 bindings_impl(cx, pat, &mut result);
363 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
365 Eq: Fn(&T, &T) -> bool,
367 for win in exprs.windows(2) {
368 if eq(&win[0], &win[1]) {
369 return Some((&win[0], &win[1]));
375 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
377 Eq: Fn(&T, &T) -> bool,
379 if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
380 Some((&exprs[0], &exprs[1]))
386 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
389 Eq: Fn(&T, &T) -> bool,
391 if let Some(expr) = search_common_cases(&exprs, &eq) {
395 let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
397 let mut map: FxHashMap<_, Vec<&_>> =
398 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
401 match map.entry(hash(expr)) {
402 Entry::Occupied(mut o) => {
405 match_expr_list.push((o, expr));
408 o.get_mut().push(expr);
410 Entry::Vacant(v) => {
411 v.insert(vec![expr]);