1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::{declare_tool_lint, lint_array};
5 use std::collections::HashMap;
6 use std::collections::hash_map::Entry;
7 use syntax::symbol::LocalInternedString;
8 use rustc_data_structures::small_vec::OneVector;
9 use crate::utils::{SpanlessEq, SpanlessHash};
10 use crate::utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
12 /// **What it does:** Checks for consecutive `if`s with the same condition.
14 /// **Why is this bad?** This is probably a copy & paste error.
16 /// **Known problems:** Hopefully none.
22 /// } else if a == b {
27 /// Note that this lint ignores all conditions with a function call as it could
28 /// have side effects:
33 /// } else if foo() { // not linted
37 declare_clippy_lint! {
40 "consecutive `ifs` with the same condition"
43 /// **What it does:** Checks for `if/else` with the same body as the *then* part
44 /// and the *else* part.
46 /// **Why is this bad?** This is probably a copy & paste error.
48 /// **Known problems:** Hopefully none.
58 declare_clippy_lint! {
59 pub IF_SAME_THEN_ELSE,
61 "if with the same *then* and *else* blocks"
64 /// **What it does:** Checks for `match` with identical arm bodies.
66 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
67 /// are the same on purpose, you can factor them
68 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
70 /// **Known problems:** False positive possible with order dependent `match`
72 /// [#860](https://github.com/rust-lang-nursery/rust-clippy/issues/860)).
79 /// Baz => bar(), // <= oops
83 /// This should probably be
88 /// Baz => baz(), // <= fixed
92 /// or if the original code was not a typo:
95 /// Bar | Baz => bar(), // <= shows the intent better
99 declare_clippy_lint! {
102 "`match` with identical arm bodies"
105 #[derive(Copy, Clone, Debug)]
106 pub struct CopyAndPaste;
108 impl LintPass for CopyAndPaste {
109 fn get_lints(&self) -> LintArray {
110 lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
114 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
115 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
116 if !in_macro(expr.span) {
117 // skip ifs directly in else, it will be checked in the parent if
119 node: ExprKind::If(_, _, Some(ref else_expr)),
121 }) = get_parent_expr(cx, expr)
123 if else_expr.id == expr.id {
128 let (conds, blocks) = if_sequence(expr);
129 lint_same_then_else(cx, &blocks);
130 lint_same_cond(cx, &conds);
131 lint_match_arms(cx, expr);
136 /// Implementation of `IF_SAME_THEN_ELSE`.
137 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
138 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
140 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
145 "this `if` has identical blocks",
152 /// Implementation of `IFS_SAME_COND`.
153 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
154 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
155 let mut h = SpanlessHash::new(cx, cx.tables);
160 let eq: &dyn Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
162 if let Some((i, j)) = search_same(conds, hash, eq) {
167 "this `if` has the same condition as a previous if",
174 /// Implementation of `MATCH_SAME_ARMS`.
175 fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
176 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node {
177 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
178 let mut h = SpanlessHash::new(cx, cx.tables);
179 h.hash_expr(&arm.body);
183 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
184 let min_index = usize::min(lindex, rindex);
185 let max_index = usize::max(lindex, rindex);
186 // Arms with a guard are ignored, those can’t always be merged together
187 // This is also the case for arms in-between each there is an arm with a guard
188 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
189 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
190 // all patterns should have the same bindings
191 bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0])
194 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
195 if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
200 "this `match` has identical arm bodies",
202 db.span_note(i.body.span, "same as this");
204 // Note: this does not use `span_suggestion` on purpose: there is no clean way
205 // to remove the other arm. Building a span and suggest to replace it to ""
206 // makes an even more confusing error message. Also in order not to make up a
207 // span for the whole pattern, the suggestion is only shown when there is only
208 // one pattern. The user should know about `|` if they are already using it…
210 if i.pats.len() == 1 && j.pats.len() == 1 {
211 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
212 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
214 if let PatKind::Wild = j.pats[0].node {
215 // if the last arm is _, then i could be integrated into _
216 // note that i.pats[0] cannot be _, because that would mean that we're
217 // hiding all the subsequent arms, and rust won't compile
220 &format!("`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs),
223 db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
232 /// Return the list of condition expressions and the list of blocks in a
233 /// sequence of `if/else`.
234 /// Eg. would return `([a, b], [c, d, e])` for the expression
235 /// `if a { c } else if b { d } else { e }`.
236 fn if_sequence(mut expr: &Expr) -> (OneVector<&Expr>, OneVector<&Block>) {
237 let mut conds = OneVector::new();
238 let mut blocks: OneVector<&Block> = OneVector::new();
240 while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.node {
242 if let ExprKind::Block(ref block, _) = then_expr.node {
245 panic!("ExprKind::If node is not an ExprKind::Block");
248 if let Some(ref else_expr) = *else_expr {
256 if !blocks.is_empty() {
257 if let ExprKind::Block(ref block, _) = expr.node {
258 blocks.push(&**block);
265 /// Return the list of bindings in a pattern.
266 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> HashMap<LocalInternedString, Ty<'tcx>> {
267 fn bindings_impl<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut HashMap<LocalInternedString, Ty<'tcx>>) {
269 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
270 PatKind::TupleStruct(_, ref pats, _) => for pat in pats {
271 bindings_impl(cx, pat, map);
273 PatKind::Binding(_, _, ident, ref as_pat) => {
274 if let Entry::Vacant(v) = map.entry(ident.as_str()) {
275 v.insert(cx.tables.pat_ty(pat));
277 if let Some(ref as_pat) = *as_pat {
278 bindings_impl(cx, as_pat, map);
281 PatKind::Struct(_, ref fields, _) => for pat in fields {
282 bindings_impl(cx, &pat.node.pat, map);
284 PatKind::Tuple(ref fields, _) => for pat in fields {
285 bindings_impl(cx, pat, map);
287 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
289 bindings_impl(cx, pat, map);
291 if let Some(ref mid) = *mid {
292 bindings_impl(cx, mid, map);
295 bindings_impl(cx, pat, map);
298 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
302 let mut result = HashMap::new();
303 bindings_impl(cx, pat, &mut result);
308 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
310 Eq: Fn(&T, &T) -> bool,
312 for win in exprs.windows(2) {
313 if eq(&win[0], &win[1]) {
314 return Some((&win[0], &win[1]));
320 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
323 Eq: Fn(&T, &T) -> bool,
328 } else if exprs.len() == 2 {
329 return if eq(&exprs[0], &exprs[1]) {
330 Some((&exprs[0], &exprs[1]))
336 let mut map: HashMap<_, Vec<&_>> = HashMap::with_capacity(exprs.len());
339 match map.entry(hash(expr)) {
340 Entry::Occupied(mut o) => {
343 return Some((o, expr));
346 o.get_mut().push(expr);
348 Entry::Vacant(v) => {
349 v.insert(vec![expr]);