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.
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc::ty::Ty;
14 use crate::rustc::hir::*;
15 use crate::rustc_data_structures::fx::FxHashMap;
16 use std::collections::hash_map::Entry;
17 use std::hash::BuildHasherDefault;
18 use crate::syntax::symbol::LocalInternedString;
19 use smallvec::SmallVec;
20 use crate::utils::{SpanlessEq, SpanlessHash};
21 use crate::utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
23 /// **What it does:** Checks for consecutive `if`s with the same condition.
25 /// **Why is this bad?** This is probably a copy & paste error.
27 /// **Known problems:** Hopefully none.
33 /// } else if a == b {
38 /// Note that this lint ignores all conditions with a function call as it could
39 /// have side effects:
44 /// } else if foo() { // not linted
48 declare_clippy_lint! {
51 "consecutive `ifs` with the same condition"
54 /// **What it does:** Checks for `if/else` with the same body as the *then* part
55 /// and the *else* part.
57 /// **Why is this bad?** This is probably a copy & paste error.
59 /// **Known problems:** Hopefully none.
69 declare_clippy_lint! {
70 pub IF_SAME_THEN_ELSE,
72 "if with the same *then* and *else* blocks"
75 /// **What it does:** Checks for `match` with identical arm bodies.
77 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
78 /// are the same on purpose, you can factor them
79 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
81 /// **Known problems:** False positive possible with order dependent `match`
83 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
90 /// Baz => bar(), // <= oops
94 /// This should probably be
99 /// Baz => baz(), // <= fixed
103 /// or if the original code was not a typo:
106 /// Bar | Baz => bar(), // <= shows the intent better
110 declare_clippy_lint! {
113 "`match` with identical arm bodies"
116 #[derive(Copy, Clone, Debug)]
117 pub struct CopyAndPaste;
119 impl LintPass for CopyAndPaste {
120 fn get_lints(&self) -> LintArray {
121 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
125 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
126 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
127 if !in_macro(expr.span) {
128 // skip ifs directly in else, it will be checked in the parent if
130 node: ExprKind::If(_, _, Some(ref else_expr)),
132 }) = get_parent_expr(cx, expr)
134 if else_expr.id == expr.id {
139 let (conds, blocks) = if_sequence(expr);
140 lint_same_then_else(cx, &blocks);
141 lint_same_cond(cx, &conds);
142 lint_match_arms(cx, expr);
147 /// Implementation of `IF_SAME_THEN_ELSE`.
148 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
149 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
151 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
156 "this `if` has identical blocks",
163 /// Implementation of `IFS_SAME_COND`.
164 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
165 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
166 let mut h = SpanlessHash::new(cx, cx.tables);
171 let eq: &dyn Fn(&&Expr, &&Expr) -> bool = &|&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
232 &format!("`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs),
235 db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
244 /// Return the list of condition expressions and the list of blocks in a
245 /// sequence of `if/else`.
246 /// Eg. would return `([a, b], [c, d, e])` for the expression
247 /// `if a { c } else if b { d } else { e }`.
248 fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
249 let mut conds = SmallVec::new();
250 let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
252 while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.node {
254 if let ExprKind::Block(ref block, _) = then_expr.node {
257 panic!("ExprKind::If node is not an ExprKind::Block");
260 if let Some(ref else_expr) = *else_expr {
268 if !blocks.is_empty() {
269 if let ExprKind::Block(ref block, _) = expr.node {
270 blocks.push(&**block);
277 /// Return the list of bindings in a pattern.
278 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> {
279 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>) {
281 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
282 PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
283 bindings_impl(cx, pat, map);
285 PatKind::Binding(_, _, ident, ref as_pat) => {
286 if let Entry::Vacant(v) = map.entry(ident.as_str()) {
287 v.insert(cx.tables.pat_ty(pat));
289 if let Some(ref as_pat) = *as_pat {
290 bindings_impl(cx, as_pat, map);
293 PatKind::Struct(_, ref fields, _) => for pat in fields {
294 bindings_impl(cx, &pat.node.pat, map);
296 PatKind::Tuple(ref fields, _) => for pat in fields {
297 bindings_impl(cx, pat, map);
299 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
301 bindings_impl(cx, pat, map);
303 if let Some(ref mid) = *mid {
304 bindings_impl(cx, mid, map);
307 bindings_impl(cx, pat, map);
310 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
314 let mut result = FxHashMap::default();
315 bindings_impl(cx, pat, &mut result);
320 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
322 Eq: Fn(&T, &T) -> bool,
324 for win in exprs.windows(2) {
325 if eq(&win[0], &win[1]) {
326 return Some((&win[0], &win[1]));
332 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
335 Eq: Fn(&T, &T) -> bool,
340 } else if exprs.len() == 2 {
341 return if eq(&exprs[0], &exprs[1]) {
342 Some((&exprs[0], &exprs[1]))
348 let mut map: FxHashMap<_, Vec<&_>> = FxHashMap::with_capacity_and_hasher(
350 BuildHasherDefault::default()
354 match map.entry(hash(expr)) {
355 Entry::Occupied(mut o) => {
358 return Some((o, expr));
361 o.get_mut().push(expr);
363 Entry::Vacant(v) => {
364 v.insert(vec![expr]);