1 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use crate::rustc::{declare_tool_lint, lint_array};
3 use crate::rustc::ty::Ty;
4 use crate::rustc::hir::*;
5 use crate::rustc_data_structures::fx::FxHashMap;
6 use std::collections::hash_map::Entry;
7 use std::hash::BuildHasherDefault;
8 use crate::syntax::symbol::LocalInternedString;
9 use crate::rustc_data_structures::small_vec::OneVector;
10 use crate::utils::{SpanlessEq, SpanlessHash};
11 use crate::utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_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
38 declare_clippy_lint! {
41 "consecutive `ifs` with the same condition"
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 declare_clippy_lint! {
60 pub IF_SAME_THEN_ELSE,
62 "if with the same *then* and *else* blocks"
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-nursery/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
100 declare_clippy_lint! {
103 "`match` with identical arm bodies"
106 #[derive(Copy, Clone, Debug)]
107 pub struct CopyAndPaste;
109 impl LintPass for CopyAndPaste {
110 fn get_lints(&self) -> LintArray {
111 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
115 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
116 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
117 if !in_macro(expr.span) {
118 // skip ifs directly in else, it will be checked in the parent if
120 node: ExprKind::If(_, _, Some(ref else_expr)),
122 }) = get_parent_expr(cx, expr)
124 if else_expr.id == expr.id {
129 let (conds, blocks) = if_sequence(expr);
130 lint_same_then_else(cx, &blocks);
131 lint_same_cond(cx, &conds);
132 lint_match_arms(cx, expr);
137 /// Implementation of `IF_SAME_THEN_ELSE`.
138 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
139 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
141 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
146 "this `if` has identical blocks",
153 /// Implementation of `IFS_SAME_COND`.
154 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
155 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
156 let mut h = SpanlessHash::new(cx, cx.tables);
161 let eq: &dyn Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
163 if let Some((i, j)) = search_same(conds, hash, eq) {
168 "this `if` has the same condition as a previous if",
175 /// Implementation of `MATCH_SAME_ARMS`.
176 fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
177 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node {
178 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
179 let mut h = SpanlessHash::new(cx, cx.tables);
180 h.hash_expr(&arm.body);
184 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
185 let min_index = usize::min(lindex, rindex);
186 let max_index = usize::max(lindex, rindex);
187 // Arms with a guard are ignored, those can’t always be merged together
188 // This is also the case for arms in-between each there is an arm with a guard
189 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
190 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
191 // all patterns should have the same bindings
192 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
195 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
196 if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
201 "this `match` has identical arm bodies",
203 db.span_note(i.body.span, "same as this");
205 // Note: this does not use `span_suggestion_with_applicability` on purpose:
206 // there is no clean way
207 // to remove the other arm. Building a span and suggest to replace it to ""
208 // makes an even more confusing error message. Also in order not to make up a
209 // span for the whole pattern, the suggestion is only shown when there is only
210 // one pattern. The user should know about `|` if they are already using it…
212 if i.pats.len() == 1 && j.pats.len() == 1 {
213 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
214 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
216 if let PatKind::Wild = j.pats[0].node {
217 // if the last arm is _, then i could be integrated into _
218 // note that i.pats[0] cannot be _, because that would mean that we're
219 // hiding all the subsequent arms, and rust won't compile
222 &format!("`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs),
225 db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
234 /// Return the list of condition expressions and the list of blocks in a
235 /// sequence of `if/else`.
236 /// Eg. would return `([a, b], [c, d, e])` for the expression
237 /// `if a { c } else if b { d } else { e }`.
238 fn if_sequence(mut expr: &Expr) -> (OneVector<&Expr>, OneVector<&Block>) {
239 let mut conds = OneVector::new();
240 let mut blocks: OneVector<&Block> = OneVector::new();
242 while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.node {
244 if let ExprKind::Block(ref block, _) = then_expr.node {
247 panic!("ExprKind::If node is not an ExprKind::Block");
250 if let Some(ref else_expr) = *else_expr {
258 if !blocks.is_empty() {
259 if let ExprKind::Block(ref block, _) = expr.node {
260 blocks.push(&**block);
267 /// Return the list of bindings in a pattern.
268 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> {
269 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>) {
271 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
272 PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
273 bindings_impl(cx, pat, map);
275 PatKind::Binding(_, _, ident, ref as_pat) => {
276 if let Entry::Vacant(v) = map.entry(ident.as_str()) {
277 v.insert(cx.tables.pat_ty(pat));
279 if let Some(ref as_pat) = *as_pat {
280 bindings_impl(cx, as_pat, map);
283 PatKind::Struct(_, ref fields, _) => for pat in fields {
284 bindings_impl(cx, &pat.node.pat, map);
286 PatKind::Tuple(ref fields, _) => for pat in fields {
287 bindings_impl(cx, pat, map);
289 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
291 bindings_impl(cx, pat, map);
293 if let Some(ref mid) = *mid {
294 bindings_impl(cx, mid, map);
297 bindings_impl(cx, pat, map);
300 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
304 let mut result = FxHashMap::default();
305 bindings_impl(cx, pat, &mut result);
310 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
312 Eq: Fn(&T, &T) -> bool,
314 for win in exprs.windows(2) {
315 if eq(&win[0], &win[1]) {
316 return Some((&win[0], &win[1]));
322 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
325 Eq: Fn(&T, &T) -> bool,
330 } else if exprs.len() == 2 {
331 return if eq(&exprs[0], &exprs[1]) {
332 Some((&exprs[0], &exprs[1]))
338 let mut map: FxHashMap<_, Vec<&_>> = FxHashMap::with_capacity_and_hasher(
340 BuildHasherDefault::default()
344 match map.entry(hash(expr)) {
345 Entry::Occupied(mut o) => {
348 return Some((o, expr));
351 o.get_mut().push(expr);
353 Entry::Vacant(v) => {
354 v.insert(vec![expr]);