1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::*;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::ty::Ty;
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_data_structures::fx::FxHashMap;
15 use crate::syntax::symbol::LocalInternedString;
16 use crate::utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
17 use crate::utils::{SpanlessEq, SpanlessHash};
18 use smallvec::SmallVec;
19 use std::collections::hash_map::Entry;
20 use std::hash::BuildHasherDefault;
22 /// **What it does:** Checks for consecutive `if`s with the same condition.
24 /// **Why is this bad?** This is probably a copy & paste error.
26 /// **Known problems:** Hopefully none.
32 /// } else if a == b {
37 /// Note that this lint ignores all conditions with a function call as it could
38 /// have side effects:
43 /// } else if foo() { // not linted
47 declare_clippy_lint! {
50 "consecutive `ifs` with the same condition"
53 /// **What it does:** Checks for `if/else` with the same body as the *then* part
54 /// and the *else* part.
56 /// **Why is this bad?** This is probably a copy & paste error.
58 /// **Known problems:** Hopefully none.
68 declare_clippy_lint! {
69 pub IF_SAME_THEN_ELSE,
71 "if with the same *then* and *else* blocks"
74 /// **What it does:** Checks for `match` with identical arm bodies.
76 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
77 /// are the same on purpose, you can factor them
78 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
80 /// **Known problems:** False positive possible with order dependent `match`
82 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
89 /// Baz => bar(), // <= oops
93 /// This should probably be
98 /// Baz => baz(), // <= fixed
102 /// or if the original code was not a typo:
105 /// Bar | Baz => bar(), // <= shows the intent better
109 declare_clippy_lint! {
112 "`match` with identical arm bodies"
115 #[derive(Copy, Clone, Debug)]
116 pub struct CopyAndPaste;
118 impl LintPass for CopyAndPaste {
119 fn get_lints(&self) -> LintArray {
120 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
124 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
125 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
126 if !in_macro(expr.span) {
127 // skip ifs directly in else, it will be checked in the parent if
129 node: ExprKind::If(_, _, Some(ref else_expr)),
131 }) = get_parent_expr(cx, expr)
133 if else_expr.id == expr.id {
138 let (conds, blocks) = if_sequence(expr);
139 lint_same_then_else(cx, &blocks);
140 lint_same_cond(cx, &conds);
141 lint_match_arms(cx, expr);
146 /// Implementation of `IF_SAME_THEN_ELSE`.
147 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
148 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
150 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
155 "this `if` has identical blocks",
162 /// Implementation of `IFS_SAME_COND`.
163 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
164 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
165 let mut h = SpanlessHash::new(cx, cx.tables);
170 let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
171 &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
173 if let Some((i, j)) = search_same(conds, hash, eq) {
178 "this `if` has the same condition as a previous if",
185 /// Implementation of `MATCH_SAME_ARMS`.
186 fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
187 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node {
188 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
189 let mut h = SpanlessHash::new(cx, cx.tables);
190 h.hash_expr(&arm.body);
194 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
195 let min_index = usize::min(lindex, rindex);
196 let max_index = usize::max(lindex, rindex);
197 // Arms with a guard are ignored, those can’t always be merged together
198 // This is also the case for arms in-between each there is an arm with a guard
199 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
200 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
201 // all patterns should have the same bindings
202 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
205 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
206 if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
211 "this `match` has identical arm bodies",
213 db.span_note(i.body.span, "same as this");
215 // Note: this does not use `span_suggestion_with_applicability` on purpose:
216 // there is no clean way
217 // to remove the other arm. Building a span and suggest to replace it to ""
218 // makes an even more confusing error message. Also in order not to make up a
219 // span for the whole pattern, the suggestion is only shown when there is only
220 // one pattern. The user should know about `|` if they are already using it…
222 if i.pats.len() == 1 && j.pats.len() == 1 {
223 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
224 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
226 if let PatKind::Wild = j.pats[0].node {
227 // if the last arm is _, then i could be integrated into _
228 // note that i.pats[0] cannot be _, because that would mean that we're
229 // hiding all the subsequent arms, and rust won't compile
233 "`{}` has the same arm body as the `_` wildcard, consider removing it`",
238 db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
247 /// Return the list of condition expressions and the list of blocks in a
248 /// sequence of `if/else`.
249 /// Eg. would return `([a, b], [c, d, e])` for the expression
250 /// `if a { c } else if b { d } else { e }`.
251 fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
252 let mut conds = SmallVec::new();
253 let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
255 while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.node {
257 if let ExprKind::Block(ref block, _) = then_expr.node {
260 panic!("ExprKind::If node is not an ExprKind::Block");
263 if let Some(ref else_expr) = *else_expr {
271 if !blocks.is_empty() {
272 if let ExprKind::Block(ref block, _) = expr.node {
273 blocks.push(&**block);
280 /// Return the list of bindings in a pattern.
281 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> {
282 fn bindings_impl<'a, 'tcx>(
283 cx: &LateContext<'a, 'tcx>,
285 map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>,
288 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
289 PatKind::TupleStruct(_, ref pats, _) => {
291 bindings_impl(cx, pat, map);
294 PatKind::Binding(_, _, ident, ref as_pat) => {
295 if let Entry::Vacant(v) = map.entry(ident.as_str()) {
296 v.insert(cx.tables.pat_ty(pat));
298 if let Some(ref as_pat) = *as_pat {
299 bindings_impl(cx, as_pat, map);
302 PatKind::Struct(_, ref fields, _) => {
304 bindings_impl(cx, &pat.node.pat, map);
307 PatKind::Tuple(ref fields, _) => {
309 bindings_impl(cx, pat, map);
312 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
314 bindings_impl(cx, pat, map);
316 if let Some(ref mid) = *mid {
317 bindings_impl(cx, mid, map);
320 bindings_impl(cx, pat, map);
323 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
327 let mut result = FxHashMap::default();
328 bindings_impl(cx, pat, &mut result);
332 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
334 Eq: Fn(&T, &T) -> bool,
336 for win in exprs.windows(2) {
337 if eq(&win[0], &win[1]) {
338 return Some((&win[0], &win[1]));
344 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
347 Eq: Fn(&T, &T) -> bool,
352 } else if exprs.len() == 2 {
353 return if eq(&exprs[0], &exprs[1]) {
354 Some((&exprs[0], &exprs[1]))
360 let mut map: FxHashMap<_, Vec<&_>> =
361 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
364 match map.entry(hash(expr)) {
365 Entry::Occupied(mut o) => {
368 return Some((o, expr));
371 o.get_mut().push(expr);
373 Entry::Vacant(v) => {
374 v.insert(vec![expr]);