]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/copies.rs
Fix match_same_arms to fail late
[rust.git] / clippy_lints / src / copies.rs
index 60319045830832acff956829143209fbd8a6a385..a28af2371edf543a03445b51f9b343c52f83cdb3 100644 (file)
@@ -1,9 +1,9 @@
-use crate::utils::{get_parent_expr, in_macro, snippet, span_lint_and_then, span_note_and_lint};
+use crate::utils::{get_parent_expr, higher, in_macro_or_desugar, snippet, span_lint_and_then, span_note_and_lint};
 use crate::utils::{SpanlessEq, SpanlessHash};
 use rustc::hir::*;
 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
 use rustc::ty::Ty;
-use rustc::{declare_tool_lint, lint_array};
+use rustc::{declare_lint_pass, declare_tool_lint};
 use rustc_data_structures::fx::FxHashMap;
 use smallvec::SmallVec;
 use std::collections::hash_map::Entry;
@@ -18,7 +18,7 @@
     /// **Known problems:** Hopefully none.
     ///
     /// **Example:**
-    /// ```rust
+    /// ```ignore
     /// if a == b {
     ///     …
     /// } else if a == b {
@@ -29,7 +29,7 @@
     /// Note that this lint ignores all conditions with a function call as it could
     /// have side effects:
     ///
-    /// ```rust
+    /// ```ignore
     /// if foo() {
     ///     …
     /// } else if foo() { // not linted
@@ -50,7 +50,7 @@
     /// **Known problems:** Hopefully none.
     ///
     /// **Example:**
-    /// ```rust
+    /// ```ignore
     /// let foo = if … {
     ///     42
     /// } else {
     "`match` with identical arm bodies"
 }
 
-#[derive(Copy, Clone, Debug)]
-pub struct CopyAndPaste;
-
-impl LintPass for CopyAndPaste {
-    fn get_lints(&self) -> LintArray {
-        lint_array![IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]
-    }
-
-    fn name(&self) -> &'static str {
-        "CopyAndPaste"
-    }
-}
+declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste {
     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
-        if !in_macro(expr.span) {
+        if !in_macro_or_desugar(expr.span) {
             // skip ifs directly in else, it will be checked in the parent if
-            if let Some(&Expr {
-                node: ExprKind::If(_, _, Some(ref else_expr)),
-                ..
-            }) = get_parent_expr(cx, expr)
-            {
-                if else_expr.hir_id == expr.hir_id {
-                    return;
+            if let Some(expr) = get_parent_expr(cx, expr) {
+                if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
+                    if else_expr.hir_id == expr.hir_id {
+                        return;
+                    }
                 }
             }
 
@@ -198,56 +185,60 @@ fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
         };
 
         let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect();
-        if let Some((&(_, i), &(_, j))) = search_same(&indexed_arms, hash, eq) {
-            span_lint_and_then(
-                cx,
-                MATCH_SAME_ARMS,
-                j.body.span,
-                "this `match` has identical arm bodies",
-                |db| {
-                    db.span_note(i.body.span, "same as this");
-
-                    // Note: this does not use `span_suggestion` on purpose:
-                    // there is no clean way
-                    // to remove the other arm. Building a span and suggest to replace it to ""
-                    // makes an even more confusing error message. Also in order not to make up a
-                    // span for the whole pattern, the suggestion is only shown when there is only
-                    // one pattern. The user should know about `|` if they are already using it…
-
-                    if i.pats.len() == 1 && j.pats.len() == 1 {
-                        let lhs = snippet(cx, i.pats[0].span, "<pat1>");
-                        let rhs = snippet(cx, j.pats[0].span, "<pat2>");
-
-                        if let PatKind::Wild = j.pats[0].node {
-                            // if the last arm is _, then i could be integrated into _
-                            // note that i.pats[0] cannot be _, because that would mean that we're
-                            // hiding all the subsequent arms, and rust won't compile
-                            db.span_note(
-                                i.body.span,
-                                &format!(
-                                    "`{}` has the same arm body as the `_` wildcard, consider removing it`",
-                                    lhs
-                                ),
-                            );
-                        } else {
-                            db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
+        search_same_list(&indexed_arms, hash, eq).map(|item| {
+            for match_expr in item {
+                let (&(_, i), &(_, j)) = match_expr;
+
+                span_lint_and_then(
+                    cx,
+                    MATCH_SAME_ARMS,
+                    j.body.span,
+                    "this `match` has identical arm bodies",
+                    |db| {
+                        db.span_note(i.body.span, "same as this");
+
+                        // Note: this does not use `span_suggestion` on purpose:
+                        // there is no clean way
+                        // to remove the other arm. Building a span and suggest to replace it to ""
+                        // makes an even more confusing error message. Also in order not to make up a
+                        // span for the whole pattern, the suggestion is only shown when there is only
+                        // one pattern. The user should know about `|` if they are already using it…
+
+                        if i.pats.len() == 1 && j.pats.len() == 1 {
+                            let lhs = snippet(cx, i.pats[0].span, "<pat1>");
+                            let rhs = snippet(cx, j.pats[0].span, "<pat2>");
+
+                            if let PatKind::Wild = j.pats[0].node {
+                                // if the last arm is _, then i could be integrated into _
+                                // note that i.pats[0] cannot be _, because that would mean that we're
+                                // hiding all the subsequent arms, and rust won't compile
+                                db.span_note(
+                                    i.body.span,
+                                    &format!(
+                                        "`{}` has the same arm body as the `_` wildcard, consider removing it`",
+                                        lhs
+                                    ),
+                                );
+                            } else {
+                                db.span_note(i.body.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
+                            }
                         }
-                    }
-                },
-            );
-        }
+                    },
+                );
+            }
+        });
     }
 }
 
-/// Return the list of condition expressions and the list of blocks in a
+/// Returns the list of condition expressions and the list of blocks in a
 /// sequence of `if/else`.
-/// Eg. would return `([a, b], [c, d, e])` for the expression
+/// E.g., this returns `([a, b], [c, d, e])` for the expression
 /// `if a { c } else if b { d } else { e }`.
 fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
     let mut conds = SmallVec::new();
     let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
 
-    while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.node {
+    while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
         conds.push(&**cond);
         if let ExprKind::Block(ref block, _) = then_expr.node {
             blocks.push(block);
@@ -272,7 +263,7 @@ fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) {
     (conds, blocks)
 }
 
-/// Return the list of bindings in a pattern.
+/// Returns the list of bindings in a pattern.
 fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> {
     fn bindings_impl<'a, 'tcx>(
         cx: &LateContext<'a, 'tcx>,
@@ -373,3 +364,36 @@ fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<(&T, &T)>
 
     None
 }
+
+fn search_same_list<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Option<Vec<(&T, &T)>>
+where
+    Hash: Fn(&T) -> u64,
+    Eq: Fn(&T, &T) -> bool,
+{
+    let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
+
+    let mut map: FxHashMap<_, Vec<&_>> =
+        FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
+
+    for expr in exprs {
+        match map.entry(hash(expr)) {
+            Entry::Occupied(mut o) => {
+                for o in o.get() {
+                    if eq(o, expr) {
+                        match_expr_list.push((o, expr));
+                    }
+                }
+                o.get_mut().push(expr);
+            },
+            Entry::Vacant(v) => {
+                v.insert(vec![expr]);
+            },
+        }
+    }
+
+    if match_expr_list.is_empty() {
+        None
+    } else {
+        Some(match_expr_list)
+    }
+}