1 use crate::utils::{eq_expr_value, in_macro, SpanlessEq, SpanlessHash};
2 use crate::utils::{get_parent_expr, higher, if_sequence, snippet, span_lint_and_note, span_lint_and_then};
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_hir::{Arm, Block, Expr, ExprKind, MatchSource, Pat, PatKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::ty::{Ty, TyS};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::symbol::Symbol;
9 use std::collections::hash_map::Entry;
10 use std::hash::BuildHasherDefault;
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 `if`s with the same condition"
43 declare_clippy_lint! {
44 /// **What it does:** Checks for consecutive `if`s with the same function call.
46 /// **Why is this bad?** This is probably a copy & paste error.
47 /// Despite the fact that function can have side effects and `if` works as
48 /// intended, such an approach is implicit and can be considered a "code smell".
50 /// **Known problems:** Hopefully none.
56 /// } else if foo() == bar {
61 /// This probably should be:
65 /// } else if foo() == baz {
70 /// or if the original code was not a typo and called function mutates a state,
71 /// consider move the mutation out of the `if` condition to avoid similarity to
72 /// a copy & paste error:
75 /// let first = foo();
79 /// let second = foo();
80 /// if second == bar {
85 pub SAME_FUNCTIONS_IN_IF_CONDITION,
87 "consecutive `if`s with the same function call"
90 declare_clippy_lint! {
91 /// **What it does:** Checks for `if/else` with the same body as the *then* part
92 /// and the *else* part.
94 /// **Why is this bad?** This is probably a copy & paste error.
96 /// **Known problems:** Hopefully none.
106 pub IF_SAME_THEN_ELSE,
108 "`if` with the same `then` and `else` blocks"
111 declare_clippy_lint! {
112 /// **What it does:** Checks for `match` with identical arm bodies.
114 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
115 /// are the same on purpose, you can factor them
116 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
118 /// **Known problems:** False positive possible with order dependent `match`
120 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
127 /// Baz => bar(), // <= oops
131 /// This should probably be
136 /// Baz => baz(), // <= fixed
140 /// or if the original code was not a typo:
143 /// Bar | Baz => bar(), // <= shows the intent better
149 "`match` with identical arm bodies"
152 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, SAME_FUNCTIONS_IN_IF_CONDITION, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
154 impl<'tcx> LateLintPass<'tcx> for CopyAndPaste {
155 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
156 if !expr.span.from_expansion() {
157 // skip ifs directly in else, it will be checked in the parent if
158 if let Some(expr) = get_parent_expr(cx, expr) {
159 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
160 if else_expr.hir_id == expr.hir_id {
166 let (conds, blocks) = if_sequence(expr);
167 lint_same_then_else(cx, &blocks);
168 lint_same_cond(cx, &conds);
169 lint_same_fns_in_if_cond(cx, &conds);
170 lint_match_arms(cx, expr);
175 /// Implementation of `IF_SAME_THEN_ELSE`.
176 fn lint_same_then_else(cx: &LateContext<'_>, blocks: &[&Block<'_>]) {
177 let eq: &dyn Fn(&&Block<'_>, &&Block<'_>) -> bool =
178 &|&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);
200 let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool { eq_expr_value(cx, lhs, rhs) };
202 for (i, j) in search_same(conds, hash, eq) {
207 "this `if` has the same condition as a previous `if`",
214 /// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`.
215 fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
216 let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
217 let mut h = SpanlessHash::new(cx);
222 let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool {
223 // Do not lint if any expr originates from a macro
224 if in_macro(lhs.span) || in_macro(rhs.span) {
227 // Do not spawn warning if `IFS_SAME_COND` already produced it.
228 if eq_expr_value(cx, lhs, rhs) {
231 SpanlessEq::new(cx).eq_expr(lhs, rhs)
234 for (i, j) in search_same(conds, hash, eq) {
237 SAME_FUNCTIONS_IN_IF_CONDITION,
239 "this `if` has the same function call as a previous `if`",
246 /// Implementation of `MATCH_SAME_ARMS`.
247 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
248 fn same_bindings<'tcx>(lhs: &FxHashMap<Symbol, Ty<'tcx>>, rhs: &FxHashMap<Symbol, Ty<'tcx>>) -> bool {
249 lhs.len() == rhs.len()
252 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| TyS::same_type(l_ty, r_ty)))
255 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
256 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
257 let mut h = SpanlessHash::new(cx);
258 h.hash_expr(&arm.body);
262 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
263 let min_index = usize::min(lindex, rindex);
264 let max_index = usize::max(lindex, rindex);
266 // Arms with a guard are ignored, those can’t always be merged together
267 // This is also the case for arms in-between each there is an arm with a guard
268 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
269 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
270 // all patterns should have the same bindings
271 same_bindings(&bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
274 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
275 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
280 "this `match` has identical arm bodies",
282 diag.span_note(i.body.span, "same as this");
284 // Note: this does not use `span_suggestion` on purpose:
285 // there is no clean way
286 // to remove the other arm. Building a span and suggest to replace it to ""
287 // makes an even more confusing error message. Also in order not to make up a
288 // span for the whole pattern, the suggestion is only shown when there is only
289 // one pattern. The user should know about `|` if they are already using it…
291 let lhs = snippet(cx, i.pat.span, "<pat1>");
292 let rhs = snippet(cx, j.pat.span, "<pat2>");
294 if let PatKind::Wild = j.pat.kind {
295 // if the last arm is _, then i could be integrated into _
296 // note that i.pat cannot be _, because that would mean that we're
297 // hiding all the subsequent arms, and rust won't compile
301 "`{}` has the same arm body as the `_` wildcard, consider removing it",
306 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
314 /// Returns the list of bindings in a pattern.
315 fn bindings<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>) -> FxHashMap<Symbol, Ty<'tcx>> {
316 fn bindings_impl<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
318 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
319 PatKind::TupleStruct(_, pats, _) => {
321 bindings_impl(cx, pat, map);
324 PatKind::Binding(.., ident, ref as_pat) => {
325 if let Entry::Vacant(v) = map.entry(ident.name) {
326 v.insert(cx.typeck_results().pat_ty(pat));
328 if let Some(ref as_pat) = *as_pat {
329 bindings_impl(cx, as_pat, map);
332 PatKind::Or(fields) | PatKind::Tuple(fields, _) => {
334 bindings_impl(cx, pat, map);
337 PatKind::Struct(_, fields, _) => {
339 bindings_impl(cx, &pat.pat, map);
342 PatKind::Slice(lhs, ref mid, rhs) => {
344 bindings_impl(cx, pat, map);
346 if let Some(ref mid) = *mid {
347 bindings_impl(cx, mid, map);
350 bindings_impl(cx, pat, map);
353 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
357 let mut result = FxHashMap::default();
358 bindings_impl(cx, pat, &mut result);
362 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
364 Eq: Fn(&T, &T) -> bool,
366 for win in exprs.windows(2) {
367 if eq(&win[0], &win[1]) {
368 return Some((&win[0], &win[1]));
374 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
376 Eq: Fn(&T, &T) -> bool,
378 if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
379 Some((&exprs[0], &exprs[1]))
385 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
388 Eq: Fn(&T, &T) -> bool,
390 if let Some(expr) = search_common_cases(&exprs, &eq) {
394 let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
396 let mut map: FxHashMap<_, Vec<&_>> =
397 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
400 match map.entry(hash(expr)) {
401 Entry::Occupied(mut o) => {
404 match_expr_list.push((o, expr));
407 o.get_mut().push(expr);
409 Entry::Vacant(v) => {
410 v.insert(vec![expr]);