1 use crate::consts::{constant, miri_to_const, Constant};
2 use clippy_utils::diagnostics::{
3 multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
5 use clippy_utils::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
6 use clippy_utils::sugg::Sugg;
7 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
8 use clippy_utils::visitors::LocalUsedVisitor;
10 get_parent_expr, in_macro, is_allowed, is_expn_of, is_refutable, is_wild, match_qpath, meets_msrv, path_to_local,
11 path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, remove_blocks, strip_pat_refs,
13 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
14 use if_chain::if_chain;
15 use rustc_ast::ast::LitKind;
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_errors::Applicability;
18 use rustc_hir::def::CtorKind;
20 Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource, Mutability, Node, Pat,
21 PatKind, QPath, RangeEnd,
23 use rustc_lint::{LateContext, LateLintPass, LintContext};
24 use rustc_middle::lint::in_external_macro;
25 use rustc_middle::ty::{self, Ty, TyS};
26 use rustc_semver::RustcVersion;
27 use rustc_session::{declare_tool_lint, impl_lint_pass};
28 use rustc_span::source_map::{Span, Spanned};
30 use std::cmp::Ordering;
31 use std::collections::hash_map::Entry;
32 use std::collections::Bound;
34 declare_clippy_lint! {
35 /// **What it does:** Checks for matches with a single arm where an `if let`
36 /// will usually suffice.
38 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
40 /// **Known problems:** None.
44 /// # fn bar(stool: &str) {}
45 /// # let x = Some("abc");
48 /// Some(ref foo) => bar(foo),
53 /// if let Some(ref foo) = x {
59 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for matches with two arms where an `if let else` will
66 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
68 /// **Known problems:** Personal style preferences may differ.
75 /// # fn bar(foo: &usize) {}
76 /// # let other_ref: usize = 1;
77 /// # let x: Option<&usize> = Some(&1);
79 /// Some(ref foo) => bar(foo),
80 /// _ => bar(&other_ref),
84 /// Using `if let` with `else`:
87 /// # fn bar(foo: &usize) {}
88 /// # let other_ref: usize = 1;
89 /// # let x: Option<&usize> = Some(&1);
90 /// if let Some(ref foo) = x {
96 pub SINGLE_MATCH_ELSE,
98 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for matches where all arms match a reference,
103 /// suggesting to remove the reference and deref the matched expression
104 /// instead. It also checks for `if let &foo = bar` blocks.
106 /// **Why is this bad?** It just makes the code less readable. That reference
107 /// destructuring adds nothing to the code.
109 /// **Known problems:** None.
115 /// &A(ref y) => foo(y),
122 /// A(ref y) => foo(y),
129 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
132 declare_clippy_lint! {
133 /// **What it does:** Checks for matches where match expression is a `bool`. It
134 /// suggests to replace the expression with an `if...else` block.
136 /// **Why is this bad?** It makes the code less readable.
138 /// **Known problems:** None.
144 /// let condition: bool = true;
145 /// match condition {
150 /// Use if/else instead:
154 /// let condition: bool = true;
163 "a `match` on a boolean expression instead of an `if..else` block"
166 declare_clippy_lint! {
167 /// **What it does:** Checks for overlapping match arms.
169 /// **Why is this bad?** It is likely to be an error and if not, makes the code
172 /// **Known problems:** None.
178 /// 1...10 => println!("1 ... 10"),
179 /// 5...15 => println!("5 ... 15"),
183 pub MATCH_OVERLAPPING_ARM,
185 "a `match` with overlapping arms"
188 declare_clippy_lint! {
189 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
190 /// and take drastic actions like `panic!`.
192 /// **Why is this bad?** It is generally a bad practice, similar to
193 /// catching all exceptions in java with `catch(Exception)`
195 /// **Known problems:** None.
199 /// let x: Result<i32, &str> = Ok(3);
201 /// Ok(_) => println!("ok"),
202 /// Err(_) => panic!("err"),
205 pub MATCH_WILD_ERR_ARM,
207 "a `match` with `Err(_)` arm and take drastic actions"
210 declare_clippy_lint! {
211 /// **What it does:** Checks for match which is used to add a reference to an
214 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
216 /// **Known problems:** None.
220 /// let x: Option<()> = None;
223 /// let r: Option<&()> = match x {
225 /// Some(ref v) => Some(v),
229 /// let r: Option<&()> = x.as_ref();
233 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
236 declare_clippy_lint! {
237 /// **What it does:** Checks for wildcard enum matches using `_`.
239 /// **Why is this bad?** New enum variants added by library updates can be missed.
241 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
242 /// variants, and also may not use correct path to enum if it's not present in the current scope.
246 /// # enum Foo { A(usize), B(usize) }
247 /// # let x = Foo::B(1);
260 pub WILDCARD_ENUM_MATCH_ARM,
262 "a wildcard enum match arm using `_`"
265 declare_clippy_lint! {
266 /// **What it does:** Checks for wildcard enum matches for a single variant.
268 /// **Why is this bad?** New enum variants added by library updates can be missed.
270 /// **Known problems:** Suggested replacements may not use correct path to enum
271 /// if it's not present in the current scope.
276 /// # enum Foo { A, B, C }
277 /// # let x = Foo::B;
292 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
294 "a wildcard enum match for a single variant"
297 declare_clippy_lint! {
298 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
300 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
301 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
303 /// **Known problems:** None.
319 pub WILDCARD_IN_OR_PATTERNS,
321 "a wildcard pattern used with others patterns in same match arm"
324 declare_clippy_lint! {
325 /// **What it does:** Checks for matches being used to destructure a single-variant enum
326 /// or tuple struct where a `let` will suffice.
328 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
330 /// **Known problems:** None.
338 /// let wrapper = Wrapper::Data(42);
340 /// let data = match wrapper {
341 /// Wrapper::Data(i) => i,
345 /// The correct use would be:
351 /// let wrapper = Wrapper::Data(42);
352 /// let Wrapper::Data(data) = wrapper;
354 pub INFALLIBLE_DESTRUCTURING_MATCH,
356 "a `match` statement with a single infallible arm instead of a `let`"
359 declare_clippy_lint! {
360 /// **What it does:** Checks for useless match that binds to only one value.
362 /// **Why is this bad?** Readability and needless complexity.
364 /// **Known problems:** Suggested replacements may be incorrect when `match`
365 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
380 /// let (c, d) = (a, b);
382 pub MATCH_SINGLE_BINDING,
384 "a match with a single binding instead of using `let` statement"
387 declare_clippy_lint! {
388 /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
390 /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
391 /// matching all enum variants explicitly.
393 /// **Known problems:** None.
397 /// # struct A { a: i32 }
398 /// let a = A { a: 5 };
402 /// A { a: 5, .. } => {},
408 /// A { a: 5 } => {},
412 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
414 "a match on a struct that binds all fields but still uses the wildcard pattern"
417 declare_clippy_lint! {
418 /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
419 /// `std::task::Poll` or `std::net::IpAddr`
421 /// **Why is this bad?** It's more concise and clear to just use the proper
424 /// **Known problems:** None.
429 /// # use std::task::Poll;
430 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
431 /// if let Ok(_) = Ok::<i32, i32>(42) {}
432 /// if let Err(_) = Err::<i32, i32>(42) {}
433 /// if let None = None::<()> {}
434 /// if let Some(_) = Some(42) {}
435 /// if let Poll::Pending = Poll::Pending::<()> {}
436 /// if let Poll::Ready(_) = Poll::Ready(42) {}
437 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
438 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
439 /// match Ok::<i32, i32>(42) {
445 /// The more idiomatic use would be:
448 /// # use std::task::Poll;
449 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
450 /// if Ok::<i32, i32>(42).is_ok() {}
451 /// if Err::<i32, i32>(42).is_err() {}
452 /// if None::<()>.is_none() {}
453 /// if Some(42).is_some() {}
454 /// if Poll::Pending::<()>.is_pending() {}
455 /// if Poll::Ready(42).is_ready() {}
456 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
457 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
458 /// Ok::<i32, i32>(42).is_ok();
460 pub REDUNDANT_PATTERN_MATCHING,
462 "use the proper utility function avoiding an `if let`"
465 declare_clippy_lint! {
466 /// **What it does:** Checks for `match` or `if let` expressions producing a
467 /// `bool` that could be written using `matches!`
469 /// **Why is this bad?** Readability and needless complexity.
471 /// **Known problems:** This lint falsely triggers, if there are arms with
472 /// `cfg` attributes that remove an arm evaluating to `false`.
479 /// let a = match x {
484 /// let a = if let Some(0) = x {
491 /// let a = matches!(x, Some(0));
493 pub MATCH_LIKE_MATCHES_MACRO,
495 "a match that could be written with the matches! macro"
498 declare_clippy_lint! {
499 /// **What it does:** Checks for `match` with identical arm bodies.
501 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
502 /// are the same on purpose, you can factor them
503 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
505 /// **Known problems:** False positive possible with order dependent `match`
507 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
514 /// Baz => bar(), // <= oops
518 /// This should probably be
523 /// Baz => baz(), // <= fixed
527 /// or if the original code was not a typo:
530 /// Bar | Baz => bar(), // <= shows the intent better
536 "`match` with identical arm bodies"
541 msrv: Option<RustcVersion>,
542 infallible_destructuring_match_linted: bool,
547 pub fn new(msrv: Option<RustcVersion>) -> Self {
555 impl_lint_pass!(Matches => [
560 MATCH_OVERLAPPING_ARM,
563 WILDCARD_ENUM_MATCH_ARM,
564 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
565 WILDCARD_IN_OR_PATTERNS,
566 MATCH_SINGLE_BINDING,
567 INFALLIBLE_DESTRUCTURING_MATCH,
568 REST_PAT_IN_FULLY_BOUND_STRUCTS,
569 REDUNDANT_PATTERN_MATCHING,
570 MATCH_LIKE_MATCHES_MACRO,
574 const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0);
576 impl<'tcx> LateLintPass<'tcx> for Matches {
577 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
578 if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
582 redundant_pattern_match::check(cx, expr);
584 if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
585 if !check_match_like_matches(cx, expr) {
586 lint_match_arms(cx, expr);
589 lint_match_arms(cx, expr);
592 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
593 check_single_match(cx, ex, arms, expr);
594 check_match_bool(cx, ex, arms, expr);
595 check_overlapping_arms(cx, ex, arms);
596 check_wild_err_arm(cx, ex, arms);
597 check_wild_enum_match(cx, ex, arms);
598 check_match_as_ref(cx, ex, arms, expr);
599 check_wild_in_or_pats(cx, arms);
601 if self.infallible_destructuring_match_linted {
602 self.infallible_destructuring_match_linted = false;
604 check_match_single_binding(cx, ex, arms, expr);
607 if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
608 check_match_ref_pats(cx, ex, arms, expr);
612 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
614 if !in_external_macro(cx.sess(), local.span);
615 if !in_macro(local.span);
616 if let Some(ref expr) = local.init;
617 if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
618 if arms.len() == 1 && arms[0].guard.is_none();
619 if let PatKind::TupleStruct(
620 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
622 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
623 let body = remove_blocks(&arms[0].body);
624 if path_to_local_id(body, arg);
627 let mut applicability = Applicability::MachineApplicable;
628 self.infallible_destructuring_match_linted = true;
631 INFALLIBLE_DESTRUCTURING_MATCH,
633 "you seem to be trying to use `match` to destructure a single infallible pattern. \
634 Consider using `let`",
638 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
639 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
640 snippet_with_applicability(cx, target.span, "..", &mut applicability),
648 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
650 if !in_external_macro(cx.sess(), pat.span);
651 if !in_macro(pat.span);
652 if let PatKind::Struct(QPath::Resolved(_, ref path), fields, true) = pat.kind;
653 if let Some(def_id) = path.res.opt_def_id();
654 let ty = cx.tcx.type_of(def_id);
655 if let ty::Adt(def, _) = ty.kind();
656 if def.is_struct() || def.is_union();
657 if fields.len() == def.non_enum_variant().fields.len();
662 REST_PAT_IN_FULLY_BOUND_STRUCTS,
664 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
666 "consider removing `..` from this binding",
672 extract_msrv_attr!(LateContext);
676 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
677 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
678 if in_macro(expr.span) {
679 // Don't lint match expressions present in
680 // macro_rules! block
683 if let PatKind::Or(..) = arms[0].pat.kind {
684 // don't lint for or patterns for now, this makes
685 // the lint noisy in unnecessary situations
688 let els = arms[1].body;
689 let els = if is_unit_expr(remove_blocks(els)) {
691 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
692 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
693 // single statement/expr "else" block, don't lint
696 // block with 2+ statements or 1 expr and 1+ statement
699 // not a block, don't lint
703 let ty = cx.typeck_results().expr_ty(ex);
704 if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
705 check_single_match_single_pattern(cx, ex, arms, expr, els);
706 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
711 fn check_single_match_single_pattern(
712 cx: &LateContext<'_>,
716 els: Option<&Expr<'_>>,
718 if is_wild(&arms[1].pat) {
719 report_single_match_single_pattern(cx, ex, arms, expr, els);
723 fn report_single_match_single_pattern(
724 cx: &LateContext<'_>,
728 els: Option<&Expr<'_>>,
730 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
731 let els_str = els.map_or(String::new(), |els| {
732 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
735 let (msg, sugg) = if_chain! {
736 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
737 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
738 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
739 if let Some(trait_id) = cx.tcx.lang_items().structural_peq_trait();
740 if ty.is_integral() || ty.is_char() || ty.is_str() || implements_trait(cx, ty, trait_id, &[]);
742 // scrutinee derives PartialEq and the pattern is a constant.
743 let pat_ref_count = match pat.kind {
744 // string literals are already a reference.
745 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
748 // References are only implicitly added to the pattern, so no overflow here.
749 // e.g. will work: match &Some(_) { Some(_) => () }
750 // will not: match Some(_) { &Some(_) => () }
751 let ref_count_diff = ty_ref_count - pat_ref_count;
753 // Try to remove address of expressions first.
754 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
755 let ref_count_diff = ref_count_diff - removed;
757 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
759 "if {} == {}{} {}{}",
760 snippet(cx, ex.span, ".."),
761 // PartialEq for different reference counts may not exist.
762 "&".repeat(ref_count_diff),
763 snippet(cx, arms[0].pat.span, ".."),
764 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
769 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
771 "if let {} = {} {}{}",
772 snippet(cx, arms[0].pat.span, ".."),
773 snippet(cx, ex.span, ".."),
774 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
788 Applicability::HasPlaceholders,
792 fn check_single_match_opt_like(
793 cx: &LateContext<'_>,
798 els: Option<&Expr<'_>>,
800 // list of candidate `Enum`s we know will never get any more members
802 (&paths::COW, "Borrowed"),
803 (&paths::COW, "Cow::Borrowed"),
804 (&paths::COW, "Cow::Owned"),
805 (&paths::COW, "Owned"),
806 (&paths::OPTION, "None"),
807 (&paths::RESULT, "Err"),
808 (&paths::RESULT, "Ok"),
811 let path = match arms[1].pat.kind {
812 PatKind::TupleStruct(ref path, ref inner, _) => {
813 // Contains any non wildcard patterns (e.g., `Err(err)`)?
814 if !inner.iter().all(is_wild) {
817 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
819 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
820 PatKind::Path(ref path) => {
821 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
826 for &(ty_path, pat_path) in candidates {
827 if path == *pat_path && match_type(cx, ty, ty_path) {
828 report_single_match_single_pattern(cx, ex, arms, expr, els);
833 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
834 // Type of expression is `bool`.
835 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
840 "you seem to be trying to match on a boolean expression",
844 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
845 if let ExprKind::Lit(ref lit) = arm_bool.kind {
847 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
848 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
858 if let Some((true_expr, false_expr)) = exprs {
859 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
860 (false, false) => Some(format!(
862 snippet(cx, ex.span, "b"),
863 expr_block(cx, true_expr, None, "..", Some(expr.span)),
864 expr_block(cx, false_expr, None, "..", Some(expr.span))
866 (false, true) => Some(format!(
868 snippet(cx, ex.span, "b"),
869 expr_block(cx, true_expr, None, "..", Some(expr.span))
872 let test = Sugg::hir(cx, ex, "..");
876 expr_block(cx, false_expr, None, "..", Some(expr.span))
879 (true, true) => None,
882 if let Some(sugg) = sugg {
883 diag.span_suggestion(
885 "consider using an `if`/`else` expression",
887 Applicability::HasPlaceholders,
897 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
898 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
899 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
900 let type_ranges = type_ranges(&ranges);
901 if !type_ranges.is_empty() {
902 if let Some((start, end)) = overlapping(&type_ranges) {
905 MATCH_OVERLAPPING_ARM,
907 "some ranges overlap",
909 "overlaps with this",
916 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
917 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
918 if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
920 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
921 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
922 if path_str == "Err" {
923 let mut matching_wild = inner.iter().any(is_wild);
924 let mut ident_bind_name = String::from("_");
926 // Looking for unused bindings (i.e.: `_e`)
927 inner.iter().for_each(|pat| {
928 if let PatKind::Binding(_, id, ident, None) = pat.kind {
929 if ident.as_str().starts_with('_')
930 && !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
932 ident_bind_name = (&ident.name.as_str()).to_string();
933 matching_wild = true;
940 if let ExprKind::Block(ref block, _) = arm.body.kind;
941 if is_panic_block(block);
943 // `Err(_)` or `Err(_e)` arm with `panic!` found
944 span_lint_and_note(cx,
947 &format!("`Err({})` matches all errors", &ident_bind_name),
949 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
959 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
960 let ty = cx.typeck_results().expr_ty(ex);
962 // If there isn't a nice closed set of possible values that can be conveniently enumerated,
963 // don't complain about not enumerating the mall.
967 // First pass - check for violation, but don't do much book-keeping because this is hopefully
968 // the uncommon case, and the book-keeping is slightly expensive.
969 let mut wildcard_span = None;
970 let mut wildcard_ident = None;
972 if let PatKind::Wild = arm.pat.kind {
973 wildcard_span = Some(arm.pat.span);
974 } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
975 wildcard_span = Some(arm.pat.span);
976 wildcard_ident = Some(ident);
980 if let Some(wildcard_span) = wildcard_span {
981 // Accumulate the variants which should be put in place of the wildcard because they're not
984 let mut missing_variants = vec![];
985 if let ty::Adt(def, _) = ty.kind() {
986 for variant in &def.variants {
987 missing_variants.push(variant);
992 if arm.guard.is_some() {
993 // Guards mean that this case probably isn't exhaustively covered. Technically
994 // this is incorrect, as we should really check whether each variant is exhaustively
995 // covered by the set of guards that cover it, but that's really hard to do.
998 if let PatKind::Path(ref path) = arm.pat.kind {
999 if let QPath::Resolved(_, p) = path {
1000 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
1002 } else if let PatKind::TupleStruct(QPath::Resolved(_, p), ref patterns, ..) = arm.pat.kind {
1003 // Some simple checks for exhaustive patterns.
1004 // There is a room for improvements to detect more cases,
1005 // but it can be more expensive to do so.
1006 let is_pattern_exhaustive =
1007 |pat: &&Pat<'_>| matches!(pat.kind, PatKind::Wild | PatKind::Binding(.., None));
1008 if patterns.iter().all(is_pattern_exhaustive) {
1009 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
1014 let mut suggestion: Vec<String> = missing_variants
1017 let suffix = match v.ctor_kind {
1018 CtorKind::Fn => "(..)",
1019 CtorKind::Const | CtorKind::Fictive => "",
1021 let ident_str = if let Some(ident) = wildcard_ident {
1022 format!("{} @ ", ident.name)
1026 // This path assumes that the enum type is imported into scope.
1027 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
1031 if suggestion.is_empty() {
1035 let mut message = "wildcard match will miss any future added variants";
1037 if let ty::Adt(def, _) = ty.kind() {
1038 if def.is_variant_list_non_exhaustive() {
1039 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
1040 suggestion.push(String::from("_"));
1044 if suggestion.len() == 1 {
1045 // No need to check for non-exhaustive enum as in that case len would be greater than 1
1048 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1052 suggestion[0].clone(),
1053 Applicability::MaybeIncorrect,
1059 WILDCARD_ENUM_MATCH_ARM,
1063 suggestion.join(" | "),
1064 Applicability::MaybeIncorrect,
1069 // If the block contains only a `panic!` macro (as expression or statement)
1070 fn is_panic_block(block: &Block<'_>) -> bool {
1071 match (&block.expr, block.stmts.len(), block.stmts.first()) {
1072 (&Some(ref exp), 0, _) => {
1073 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
1075 (&None, 1, Some(stmt)) => {
1076 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1082 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1083 if has_only_ref_pats(arms) {
1084 let mut suggs = Vec::with_capacity(arms.len() + 1);
1085 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1086 let span = ex.span.source_callsite();
1087 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1089 "you don't need to add `&` to both the expression and the patterns",
1093 let span = ex.span.source_callsite();
1094 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1096 "you don't need to add `&` to all patterns",
1097 "instead of prefixing all patterns with `&`, you can dereference the expression",
1101 suggs.extend(arms.iter().filter_map(|a| {
1102 if let PatKind::Ref(ref refp, _) = a.pat.kind {
1103 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1109 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1110 if !expr.span.from_expansion() {
1111 multispan_sugg(diag, msg, suggs);
1117 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1118 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1119 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
1120 is_ref_some_arm(&arms[1])
1121 } else if is_none_arm(&arms[1]) {
1122 is_ref_some_arm(&arms[0])
1126 if let Some(rb) = arm_ref {
1127 let suggestion = if rb == BindingAnnotation::Ref {
1133 let output_ty = cx.typeck_results().expr_ty(expr);
1134 let input_ty = cx.typeck_results().expr_ty(ex);
1136 let cast = if_chain! {
1137 if let ty::Adt(_, substs) = input_ty.kind();
1138 let input_ty = substs.type_at(0);
1139 if let ty::Adt(_, substs) = output_ty.kind();
1140 let output_ty = substs.type_at(0);
1141 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1142 if input_ty != output_ty;
1150 let mut applicability = Applicability::MachineApplicable;
1155 &format!("use `{}()` instead", suggestion),
1159 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1169 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1171 if let PatKind::Or(ref fields) = arm.pat.kind {
1172 // look for multiple fields in this arm that contains at least one Wild pattern
1173 if fields.len() > 1 && fields.iter().any(is_wild) {
1176 WILDCARD_IN_OR_PATTERNS,
1178 "wildcard pattern covers any other pattern as it will match anyway",
1180 "consider handling `_` separately",
1187 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1188 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1189 if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1190 match match_source {
1191 MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1192 MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1200 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1201 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1204 if cx.typeck_results().expr_ty(expr).is_bool();
1205 if let Some((b1_arm, b0_arms)) = arms.split_last();
1206 if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1207 if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1208 if is_wild(&b1_arm.pat);
1210 let if_guard = &b0_arms[0].guard;
1211 if if_guard.is_none() || b0_arms.len() == 1;
1212 if cx.tcx.hir().attrs(b0_arms[0].hir_id).is_empty();
1213 if b0_arms[1..].iter()
1215 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1216 arm.guard.is_none() && cx.tcx.hir().attrs(arm.hir_id).is_empty()
1219 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1220 // evaluated into `false` and so such arms will be stripped before.
1221 let mut applicability = Applicability::MaybeIncorrect;
1223 use itertools::Itertools as _;
1225 .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1228 let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1229 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1234 // strip potential borrows (#6503), but only if the type is a reference
1235 let mut ex_new = ex;
1236 if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1237 if let ty::Ref(..) = cx.typeck_results().expr_ty(&ex_inner).kind() {
1243 MATCH_LIKE_MATCHES_MACRO,
1245 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1248 "{}matches!({}, {})",
1249 if b0 { "" } else { "!" },
1250 snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1262 /// Extract a `bool` or `{ bool }`
1263 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1265 ExprKind::Lit(Spanned {
1266 node: LitKind::Bool(b), ..
1276 if let ExprKind::Lit(Spanned {
1277 node: LitKind::Bool(b), ..
1289 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1290 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1295 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1296 // to prevent false positives as there is currently no better way to detect if code was excluded by
1297 // a macro. See PR #6435
1299 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1300 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1301 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1302 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1303 if rest_snippet.contains("=>");
1305 // The code it self contains another thick arrow "=>"
1306 // -> Either another arm or a comment
1311 let matched_vars = ex.span;
1312 let bind_names = arms[0].pat.span;
1313 let match_body = remove_blocks(&arms[0].body);
1314 let mut snippet_body = if match_body.span.from_expansion() {
1315 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1317 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1320 // Do we need to add ';' to suggestion ?
1321 match match_body.kind {
1322 ExprKind::Block(block, _) => {
1323 // macro + expr_ty(body) == ()
1324 if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() {
1325 snippet_body.push(';');
1329 // expr_ty(body) == ()
1330 if cx.typeck_results().expr_ty(&match_body).is_unit() {
1331 snippet_body.push(';');
1336 let mut applicability = Applicability::MaybeIncorrect;
1337 match arms[0].pat.kind {
1338 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1339 // If this match is in a local (`let`) stmt
1340 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1342 parent_let_node.span,
1344 "let {} = {};\n{}let {} = {};",
1345 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1346 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1347 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1348 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1353 // If we are in closure, we need curly braces around suggestion
1354 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1355 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1356 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1357 if let ExprKind::Closure(..) = parent_expr.kind {
1358 cbrace_end = format!("\n{}}}", indent);
1359 // Fix body indent due to the closure
1360 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1361 cbrace_start = format!("{{\n{}", indent);
1367 "{}let {} = {};\n{}{}{}",
1369 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1370 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1379 MATCH_SINGLE_BINDING,
1381 "this match could be written as a `let` statement",
1382 "consider using `let` statement",
1390 MATCH_SINGLE_BINDING,
1392 "this match could be replaced by its body itself",
1393 "consider using the match body instead",
1395 Applicability::MachineApplicable,
1402 /// Returns true if the `ex` match expression is in a local (`let`) statement
1403 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1405 let map = &cx.tcx.hir();
1406 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1407 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1409 return Some(parent_let_expr);
1415 /// Gets all arms that are unbounded `PatRange`s.
1416 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1420 ref pat, guard: None, ..
1423 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1424 let lhs = match lhs {
1425 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1426 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1428 let rhs = match rhs {
1429 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1430 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1432 let rhs = match range_end {
1433 RangeEnd::Included => Bound::Included(rhs),
1434 RangeEnd::Excluded => Bound::Excluded(rhs),
1436 return Some(SpannedRange {
1442 if let PatKind::Lit(ref value) = pat.kind {
1443 let value = constant(cx, cx.typeck_results(), value)?.0;
1444 return Some(SpannedRange {
1446 node: (value.clone(), Bound::Included(value)),
1455 #[derive(Debug, Eq, PartialEq)]
1456 pub struct SpannedRange<T> {
1458 pub node: (T, Bound<T>),
1461 type TypedRanges = Vec<SpannedRange<u128>>;
1463 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1464 /// and other types than
1465 /// `Uint` and `Int` probably don't make sense.
1466 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1469 .filter_map(|range| match range.node {
1470 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1472 node: (start, Bound::Included(end)),
1474 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1476 node: (start, Bound::Excluded(end)),
1478 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1480 node: (start, Bound::Unbounded),
1487 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1489 ExprKind::Tup(ref v) if v.is_empty() => true,
1490 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1495 // Checks if arm has the form `None => None`
1496 fn is_none_arm(arm: &Arm<'_>) -> bool {
1497 matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE))
1500 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1501 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1503 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1504 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1505 if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1506 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1507 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1508 if let ExprKind::Path(ref some_path) = e.kind;
1509 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1510 if let ExprKind::Path(QPath::Resolved(_, ref path2)) = args[0].kind;
1511 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1519 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1524 PatKind::Ref(..) => Some(true), // &-patterns
1525 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1526 _ => None, // any other pattern is not fine
1529 .collect::<Option<Vec<bool>>>();
1530 // look for Some(v) where there's at least one true element
1531 mapped.map_or(false, |v| v.iter().any(|el| *el))
1534 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1538 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1540 Start(T, &'a SpannedRange<T>),
1541 End(Bound<T>, &'a SpannedRange<T>),
1544 impl<'a, T: Copy> Kind<'a, T> {
1545 fn range(&self) -> &'a SpannedRange<T> {
1547 Kind::Start(_, r) | Kind::End(_, r) => r,
1551 fn value(self) -> Bound<T> {
1553 Kind::Start(t, _) => Bound::Included(t),
1554 Kind::End(t, _) => t,
1559 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1560 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1561 Some(self.cmp(other))
1565 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1566 fn cmp(&self, other: &Self) -> Ordering {
1567 match (self.value(), other.value()) {
1568 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1569 // Range patterns cannot be unbounded (yet)
1570 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1571 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1572 Ordering::Equal => Ordering::Greater,
1575 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1576 Ordering::Equal => Ordering::Less,
1583 let mut values = Vec::with_capacity(2 * ranges.len());
1586 values.push(Kind::Start(r.node.0, r));
1587 values.push(Kind::End(r.node.1, r));
1592 for (a, b) in values.iter().zip(values.iter().skip(1)) {
1594 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1595 if ra.node != rb.node {
1596 return Some((ra, rb));
1599 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1601 // skip if the range `a` is completely included into the range `b`
1602 if let Ordering::Equal | Ordering::Less = a.cmp(&b) {
1603 let kind_a = Kind::End(a.range().node.1, a.range());
1604 let kind_b = Kind::End(b.range().node.1, b.range());
1605 if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1609 return Some((a.range(), b.range()));
1617 mod redundant_pattern_match {
1618 use super::REDUNDANT_PATTERN_MATCHING;
1619 use clippy_utils::diagnostics::span_lint_and_then;
1620 use clippy_utils::source::snippet;
1621 use clippy_utils::{is_trait_method, match_qpath, paths};
1622 use if_chain::if_chain;
1623 use rustc_ast::ast::LitKind;
1624 use rustc_errors::Applicability;
1625 use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1626 use rustc_lint::LateContext;
1627 use rustc_span::sym;
1629 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1630 if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1631 match match_source {
1632 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1633 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1634 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1640 fn find_sugg_for_if_let<'tcx>(
1641 cx: &LateContext<'tcx>,
1642 expr: &'tcx Expr<'_>,
1645 keyword: &'static str,
1647 let good_method = match arms[0].pat.kind {
1648 PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => {
1649 if let PatKind::Wild = patterns[0].kind {
1650 if match_qpath(path, &paths::RESULT_OK) {
1652 } else if match_qpath(path, &paths::RESULT_ERR) {
1654 } else if match_qpath(path, &paths::OPTION_SOME) {
1656 } else if match_qpath(path, &paths::POLL_READY) {
1658 } else if match_qpath(path, &paths::IPADDR_V4) {
1660 } else if match_qpath(path, &paths::IPADDR_V6) {
1669 PatKind::Path(ref path) => {
1670 if match_qpath(path, &paths::OPTION_NONE) {
1672 } else if match_qpath(path, &paths::POLL_PENDING) {
1681 // check that `while_let_on_iterator` lint does not trigger
1683 if keyword == "while";
1684 if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1685 if method_path.ident.name == sym::next;
1686 if is_trait_method(cx, op, sym::Iterator);
1692 let result_expr = match &op.kind {
1693 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1698 REDUNDANT_PATTERN_MATCHING,
1700 &format!("redundant pattern matching, consider using `{}`", good_method),
1702 // while let ... = ... { ... }
1703 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1704 let expr_span = expr.span;
1706 // while let ... = ... { ... }
1708 let op_span = result_expr.span.source_callsite();
1710 // while let ... = ... { ... }
1711 // ^^^^^^^^^^^^^^^^^^^
1712 let span = expr_span.until(op_span.shrink_to_hi());
1713 diag.span_suggestion(
1716 format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1717 Applicability::MachineApplicable, // snippet
1723 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1724 if arms.len() == 2 {
1725 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1727 let found_good_method = match node_pair {
1729 PatKind::TupleStruct(ref path_left, ref patterns_left, _),
1730 PatKind::TupleStruct(ref path_right, ref patterns_right, _),
1731 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1732 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1733 find_good_method_for_match(
1743 find_good_method_for_match(
1757 (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right))
1758 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _))
1759 if patterns.len() == 1 =>
1761 if let PatKind::Wild = patterns[0].kind {
1762 find_good_method_for_match(
1766 &paths::OPTION_SOME,
1767 &paths::OPTION_NONE,
1772 find_good_method_for_match(
1777 &paths::POLL_PENDING,
1789 if let Some(good_method) = found_good_method {
1790 let span = expr.span.to(op.span);
1791 let result_expr = match &op.kind {
1792 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1797 REDUNDANT_PATTERN_MATCHING,
1799 &format!("redundant pattern matching, consider using `{}`", good_method),
1801 diag.span_suggestion(
1804 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1805 Applicability::MaybeIncorrect, // snippet
1813 fn find_good_method_for_match<'a>(
1815 path_left: &QPath<'_>,
1816 path_right: &QPath<'_>,
1817 expected_left: &[&str],
1818 expected_right: &[&str],
1819 should_be_left: &'a str,
1820 should_be_right: &'a str,
1821 ) -> Option<&'a str> {
1822 let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) {
1823 (&(*arms[0].body).kind, &(*arms[1].body).kind)
1824 } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) {
1825 (&(*arms[1].body).kind, &(*arms[0].body).kind)
1830 match body_node_pair {
1831 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1832 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1833 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1842 fn test_overlapping() {
1843 use rustc_span::source_map::DUMMY_SP;
1845 let sp = |s, e| SpannedRange {
1850 assert_eq!(None, overlapping::<u8>(&[]));
1851 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1854 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1859 sp(1, Bound::Included(4)),
1860 sp(5, Bound::Included(6)),
1861 sp(10, Bound::Included(11))
1865 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1866 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1869 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1871 sp(1, Bound::Included(4)),
1872 sp(5, Bound::Included(6)),
1873 sp(6, Bound::Included(11))
1878 /// Implementation of `MATCH_SAME_ARMS`.
1879 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1880 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
1881 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1882 let mut h = SpanlessHash::new(cx);
1883 h.hash_expr(&arm.body);
1887 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1888 let min_index = usize::min(lindex, rindex);
1889 let max_index = usize::max(lindex, rindex);
1891 let mut local_map: FxHashMap<HirId, HirId> = FxHashMap::default();
1892 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
1894 if let Some(a_id) = path_to_local(a);
1895 if let Some(b_id) = path_to_local(b);
1896 let entry = match local_map.entry(a_id) {
1897 Entry::Vacant(entry) => entry,
1898 // check if using the same bindings as before
1899 Entry::Occupied(entry) => return *entry.get() == b_id,
1901 // the names technically don't have to match; this makes the lint more conservative
1902 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
1903 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
1904 if pat_contains_local(lhs.pat, a_id);
1905 if pat_contains_local(rhs.pat, b_id);
1914 // Arms with a guard are ignored, those can’t always be merged together
1915 // This is also the case for arms in-between each there is an arm with a guard
1916 (min_index..=max_index).all(|index| arms[index].guard.is_none())
1917 && SpanlessEq::new(cx)
1918 .expr_fallback(eq_fallback)
1919 .eq_expr(&lhs.body, &rhs.body)
1920 // these checks could be removed to allow unused bindings
1921 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
1922 && bindings_eq(rhs.pat, local_map.values().copied().collect())
1925 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
1926 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
1931 "this `match` has identical arm bodies",
1933 diag.span_note(i.body.span, "same as this");
1935 // Note: this does not use `span_suggestion` on purpose:
1936 // there is no clean way
1937 // to remove the other arm. Building a span and suggest to replace it to ""
1938 // makes an even more confusing error message. Also in order not to make up a
1939 // span for the whole pattern, the suggestion is only shown when there is only
1940 // one pattern. The user should know about `|` if they are already using it…
1942 let lhs = snippet(cx, i.pat.span, "<pat1>");
1943 let rhs = snippet(cx, j.pat.span, "<pat2>");
1945 if let PatKind::Wild = j.pat.kind {
1946 // if the last arm is _, then i could be integrated into _
1947 // note that i.pat cannot be _, because that would mean that we're
1948 // hiding all the subsequent arms, and rust won't compile
1952 "`{}` has the same arm body as the `_` wildcard, consider removing it",
1957 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
1965 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
1966 let mut result = false;
1967 pat.walk_short(|p| {
1968 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
1974 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
1975 fn bindings_eq(pat: &Pat<'_>, mut ids: FxHashSet<HirId>) -> bool {
1976 let mut result = true;
1977 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
1978 result && ids.is_empty()