2 get_parent_expr, higher, in_macro_or_desugar, same_tys, snippet, span_lint_and_then, span_note_and_lint,
4 use crate::utils::{SpanlessEq, SpanlessHash};
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::{declare_lint_pass, declare_tool_lint};
9 use rustc_data_structures::fx::FxHashMap;
10 use smallvec::SmallVec;
11 use std::collections::hash_map::Entry;
12 use std::hash::BuildHasherDefault;
13 use syntax::symbol::LocalInternedString;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for consecutive `if`s with the same condition.
18 /// **Why is this bad?** This is probably a copy & paste error.
20 /// **Known problems:** Hopefully none.
26 /// } else if a == b {
31 /// Note that this lint ignores all conditions with a function call as it could
32 /// have side effects:
37 /// } else if foo() { // not linted
43 "consecutive `ifs` with the same condition"
46 declare_clippy_lint! {
47 /// **What it does:** Checks for `if/else` with the same body as the *then* part
48 /// and the *else* part.
50 /// **Why is this bad?** This is probably a copy & paste error.
52 /// **Known problems:** Hopefully none.
62 pub IF_SAME_THEN_ELSE,
64 "if with the same *then* and *else* blocks"
67 declare_clippy_lint! {
68 /// **What it does:** Checks for `match` with identical arm bodies.
70 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
71 /// are the same on purpose, you can factor them
72 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
74 /// **Known problems:** False positive possible with order dependent `match`
76 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
83 /// Baz => bar(), // <= oops
87 /// This should probably be
92 /// Baz => baz(), // <= fixed
96 /// or if the original code was not a typo:
99 /// Bar | Baz => bar(), // <= shows the intent better
105 "`match` with identical arm bodies"
108 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
110 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
111 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
112 if !in_macro_or_desugar(expr.span) {
113 // skip ifs directly in else, it will be checked in the parent if
114 if let Some(expr) = get_parent_expr(cx, expr) {
115 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
116 if else_expr.hir_id == expr.hir_id {
122 let (conds, blocks) = if_sequence(expr);
123 lint_same_then_else(cx, &blocks);
124 lint_same_cond(cx, &conds);
125 lint_match_arms(cx, expr);
130 /// Implementation of `IF_SAME_THEN_ELSE`.
131 fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) {
132 let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
134 if let Some((i, j)) = search_same_sequenced(blocks, eq) {
139 "this `if` has identical blocks",
146 /// Implementation of `IFS_SAME_COND`.
147 fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) {
148 let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 {
149 let mut h = SpanlessHash::new(cx, cx.tables);
154 let eq: &dyn Fn(&&Expr, &&Expr) -> bool =
155 &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
157 for (i, j) in search_same(conds, hash, eq) {
162 "this `if` has the same condition as a previous if",
169 /// Implementation of `MATCH_SAME_ARMS`.
170 fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr) {
171 fn same_bindings<'tcx>(
172 cx: &LateContext<'_, 'tcx>,
173 lhs: &FxHashMap<LocalInternedString, Ty<'tcx>>,
174 rhs: &FxHashMap<LocalInternedString, Ty<'tcx>>,
176 lhs.len() == rhs.len()
179 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| same_tys(cx, l_ty, r_ty)))
182 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node {
183 let hash = |&(_, arm): &(usize, &Arm)| -> u64 {
184 let mut h = SpanlessHash::new(cx, cx.tables);
185 h.hash_expr(&arm.body);
189 let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool {
190 let min_index = usize::min(lindex, rindex);
191 let max_index = usize::max(lindex, rindex);
193 // Arms with a guard are ignored, those can’t always be merged together
194 // This is also the case for arms in-between each there is an arm with a guard
195 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
196 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
197 // all patterns should have the same bindings
198 same_bindings(cx, &bindings(cx, &lhs.pats[0]), &bindings(cx, &rhs.pats[0]))
201 let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
202 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
207 "this `match` has identical arm bodies",
209 db.span_note(i.body.span, "same as this");
211 // Note: this does not use `span_suggestion` on purpose:
212 // there is no clean way
213 // to remove the other arm. Building a span and suggest to replace it to ""
214 // makes an even more confusing error message. Also in order not to make up a
215 // span for the whole pattern, the suggestion is only shown when there is only
216 // one pattern. The user should know about `|` if they are already using it…
218 if i.pats.len() == 1 && j.pats.len() == 1 {
219 let lhs = snippet(cx, i.pats[0].span, "<pat1>");
220 let rhs = snippet(cx, j.pats[0].span, "<pat2>");
222 if let PatKind::Wild = j.pats[0].node {
223 // if the last arm is _, then i could be integrated into _
224 // note that i.pats[0] cannot be _, because that would mean that we're
225 // hiding all the subsequent arms, and rust won't compile
229 "`{}` has the same arm body as the `_` wildcard, consider removing it`",
236 &format!("consider refactoring into `{} | {}`", lhs, rhs),
246 /// Returns the list of condition expressions and the list of blocks in a
247 /// sequence of `if/else`.
248 /// E.g., this returns `([a, b], [c, d, e])` for the expression
249 /// `if a { c } else if b { d } else { e }`.
250 fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
251 let mut conds = SmallVec::new();
252 let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
254 while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
256 if let ExprKind::Block(ref block, _) = then_expr.node {
259 panic!("ExprKind::If node is not an ExprKind::Block");
262 if let Some(ref else_expr) = *else_expr {
270 if !blocks.is_empty() {
271 if let ExprKind::Block(ref block, _) = expr.node {
272 blocks.push(&**block);
279 /// Returns the list of bindings in a pattern.
280 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> {
281 fn bindings_impl<'a, 'tcx>(
282 cx: &LateContext<'a, 'tcx>,
284 map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>,
287 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
288 PatKind::TupleStruct(_, ref pats, _) => {
290 bindings_impl(cx, pat, map);
293 PatKind::Binding(.., ident, ref as_pat) => {
294 if let Entry::Vacant(v) = map.entry(ident.as_str()) {
295 v.insert(cx.tables.pat_ty(pat));
297 if let Some(ref as_pat) = *as_pat {
298 bindings_impl(cx, as_pat, map);
301 PatKind::Struct(_, ref fields, _) => {
303 bindings_impl(cx, &pat.node.pat, map);
306 PatKind::Tuple(ref fields, _) => {
308 bindings_impl(cx, pat, map);
311 PatKind::Slice(ref lhs, ref mid, ref rhs) => {
313 bindings_impl(cx, pat, map);
315 if let Some(ref mid) = *mid {
316 bindings_impl(cx, mid, map);
319 bindings_impl(cx, pat, map);
322 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
326 let mut result = FxHashMap::default();
327 bindings_impl(cx, pat, &mut result);
331 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
333 Eq: Fn(&T, &T) -> bool,
335 for win in exprs.windows(2) {
336 if eq(&win[0], &win[1]) {
337 return Some((&win[0], &win[1]));
343 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
345 Eq: Fn(&T, &T) -> bool,
349 } else if exprs.len() == 2 {
350 if eq(&exprs[0], &exprs[1]) {
351 Some((&exprs[0], &exprs[1]))
360 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
363 Eq: Fn(&T, &T) -> bool,
365 if let Some(expr) = search_common_cases(&exprs, &eq) {
369 let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
371 let mut map: FxHashMap<_, Vec<&_>> =
372 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
375 match map.entry(hash(expr)) {
376 Entry::Occupied(mut o) => {
379 match_expr_list.push((o, expr));
382 o.get_mut().push(expr);
384 Entry::Vacant(v) => {
385 v.insert(vec![expr]);