1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::sugg::Sugg;
3 use crate::utils::usage::is_unused;
5 expr_block, get_arg_name, get_parent_expr, in_macro, indent_of, is_allowed, is_expn_of, is_refutable,
6 is_type_diagnostic_item, is_wild, match_qpath, match_type, match_var, meets_msrv, multispan_sugg, remove_blocks,
7 snippet, snippet_block, snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
10 use crate::utils::{paths, search_same, SpanlessEq, SpanlessHash};
11 use if_chain::if_chain;
12 use rustc_ast::ast::LitKind;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_errors::Applicability;
15 use rustc_hir::def::CtorKind;
17 Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, Local, MatchSource, Mutability, Node, Pat,
18 PatKind, QPath, RangeEnd,
20 use rustc_lint::{LateContext, LateLintPass, LintContext};
21 use rustc_middle::lint::in_external_macro;
22 use rustc_middle::ty::{self, Ty, TyS};
23 use rustc_session::{declare_tool_lint, impl_lint_pass};
24 use rustc_span::source_map::{Span, Spanned};
25 use rustc_span::{sym, Symbol};
26 use semver::{Version, VersionReq};
27 use std::cmp::Ordering;
28 use std::collections::hash_map::Entry;
29 use std::collections::Bound;
31 declare_clippy_lint! {
32 /// **What it does:** Checks for matches with a single arm where an `if let`
33 /// will usually suffice.
35 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
37 /// **Known problems:** None.
41 /// # fn bar(stool: &str) {}
42 /// # let x = Some("abc");
45 /// Some(ref foo) => bar(foo),
50 /// if let Some(ref foo) = x {
56 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
59 declare_clippy_lint! {
60 /// **What it does:** Checks for matches with two arms where an `if let else` will
63 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
65 /// **Known problems:** Personal style preferences may differ.
72 /// # fn bar(foo: &usize) {}
73 /// # let other_ref: usize = 1;
74 /// # let x: Option<&usize> = Some(&1);
76 /// Some(ref foo) => bar(foo),
77 /// _ => bar(&other_ref),
81 /// Using `if let` with `else`:
84 /// # fn bar(foo: &usize) {}
85 /// # let other_ref: usize = 1;
86 /// # let x: Option<&usize> = Some(&1);
87 /// if let Some(ref foo) = x {
93 pub SINGLE_MATCH_ELSE,
95 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
98 declare_clippy_lint! {
99 /// **What it does:** Checks for matches where all arms match a reference,
100 /// suggesting to remove the reference and deref the matched expression
101 /// instead. It also checks for `if let &foo = bar` blocks.
103 /// **Why is this bad?** It just makes the code less readable. That reference
104 /// destructuring adds nothing to the code.
106 /// **Known problems:** None.
112 /// &A(ref y) => foo(y),
119 /// A(ref y) => foo(y),
126 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
129 declare_clippy_lint! {
130 /// **What it does:** Checks for matches where match expression is a `bool`. It
131 /// suggests to replace the expression with an `if...else` block.
133 /// **Why is this bad?** It makes the code less readable.
135 /// **Known problems:** None.
141 /// let condition: bool = true;
142 /// match condition {
147 /// Use if/else instead:
151 /// let condition: bool = true;
160 "a `match` on a boolean expression instead of an `if..else` block"
163 declare_clippy_lint! {
164 /// **What it does:** Checks for overlapping match arms.
166 /// **Why is this bad?** It is likely to be an error and if not, makes the code
169 /// **Known problems:** None.
175 /// 1...10 => println!("1 ... 10"),
176 /// 5...15 => println!("5 ... 15"),
180 pub MATCH_OVERLAPPING_ARM,
182 "a `match` with overlapping arms"
185 declare_clippy_lint! {
186 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
187 /// and take drastic actions like `panic!`.
189 /// **Why is this bad?** It is generally a bad practice, similar to
190 /// catching all exceptions in java with `catch(Exception)`
192 /// **Known problems:** None.
196 /// let x: Result<i32, &str> = Ok(3);
198 /// Ok(_) => println!("ok"),
199 /// Err(_) => panic!("err"),
202 pub MATCH_WILD_ERR_ARM,
204 "a `match` with `Err(_)` arm and take drastic actions"
207 declare_clippy_lint! {
208 /// **What it does:** Checks for match which is used to add a reference to an
211 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
213 /// **Known problems:** None.
217 /// let x: Option<()> = None;
220 /// let r: Option<&()> = match x {
222 /// Some(ref v) => Some(v),
226 /// let r: Option<&()> = x.as_ref();
230 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
233 declare_clippy_lint! {
234 /// **What it does:** Checks for wildcard enum matches using `_`.
236 /// **Why is this bad?** New enum variants added by library updates can be missed.
238 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
239 /// variants, and also may not use correct path to enum if it's not present in the current scope.
243 /// # enum Foo { A(usize), B(usize) }
244 /// # let x = Foo::B(1);
257 pub WILDCARD_ENUM_MATCH_ARM,
259 "a wildcard enum match arm using `_`"
262 declare_clippy_lint! {
263 /// **What it does:** Checks for wildcard enum matches for a single variant.
265 /// **Why is this bad?** New enum variants added by library updates can be missed.
267 /// **Known problems:** Suggested replacements may not use correct path to enum
268 /// if it's not present in the current scope.
273 /// # enum Foo { A, B, C }
274 /// # let x = Foo::B;
289 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
291 "a wildcard enum match for a single variant"
294 declare_clippy_lint! {
295 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
297 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
298 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
300 /// **Known problems:** None.
316 pub WILDCARD_IN_OR_PATTERNS,
318 "a wildcard pattern used with others patterns in same match arm"
321 declare_clippy_lint! {
322 /// **What it does:** Checks for matches being used to destructure a single-variant enum
323 /// or tuple struct where a `let` will suffice.
325 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
327 /// **Known problems:** None.
335 /// let wrapper = Wrapper::Data(42);
337 /// let data = match wrapper {
338 /// Wrapper::Data(i) => i,
342 /// The correct use would be:
348 /// let wrapper = Wrapper::Data(42);
349 /// let Wrapper::Data(data) = wrapper;
351 pub INFALLIBLE_DESTRUCTURING_MATCH,
353 "a `match` statement with a single infallible arm instead of a `let`"
356 declare_clippy_lint! {
357 /// **What it does:** Checks for useless match that binds to only one value.
359 /// **Why is this bad?** Readability and needless complexity.
361 /// **Known problems:** Suggested replacements may be incorrect when `match`
362 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
377 /// let (c, d) = (a, b);
379 pub MATCH_SINGLE_BINDING,
381 "a match with a single binding instead of using `let` statement"
384 declare_clippy_lint! {
385 /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
387 /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
388 /// matching all enum variants explicitly.
390 /// **Known problems:** None.
394 /// # struct A { a: i32 }
395 /// let a = A { a: 5 };
399 /// A { a: 5, .. } => {},
405 /// A { a: 5 } => {},
409 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
411 "a match on a struct that binds all fields but still uses the wildcard pattern"
414 declare_clippy_lint! {
415 /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
416 /// `std::task::Poll` or `std::net::IpAddr`
418 /// **Why is this bad?** It's more concise and clear to just use the proper
421 /// **Known problems:** None.
426 /// # use std::task::Poll;
427 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
428 /// if let Ok(_) = Ok::<i32, i32>(42) {}
429 /// if let Err(_) = Err::<i32, i32>(42) {}
430 /// if let None = None::<()> {}
431 /// if let Some(_) = Some(42) {}
432 /// if let Poll::Pending = Poll::Pending::<()> {}
433 /// if let Poll::Ready(_) = Poll::Ready(42) {}
434 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
435 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
436 /// match Ok::<i32, i32>(42) {
442 /// The more idiomatic use would be:
445 /// # use std::task::Poll;
446 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
447 /// if Ok::<i32, i32>(42).is_ok() {}
448 /// if Err::<i32, i32>(42).is_err() {}
449 /// if None::<()>.is_none() {}
450 /// if Some(42).is_some() {}
451 /// if Poll::Pending::<()>.is_pending() {}
452 /// if Poll::Ready(42).is_ready() {}
453 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
454 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
455 /// Ok::<i32, i32>(42).is_ok();
457 pub REDUNDANT_PATTERN_MATCHING,
459 "use the proper utility function avoiding an `if let`"
462 declare_clippy_lint! {
463 /// **What it does:** Checks for `match` or `if let` expressions producing a
464 /// `bool` that could be written using `matches!`
466 /// **Why is this bad?** Readability and needless complexity.
468 /// **Known problems:** This lint falsely triggers, if there are arms with
469 /// `cfg` attributes that remove an arm evaluating to `false`.
476 /// let a = match x {
481 /// let a = if let Some(0) = x {
488 /// let a = matches!(x, Some(0));
490 pub MATCH_LIKE_MATCHES_MACRO,
492 "a match that could be written with the matches! macro"
495 declare_clippy_lint! {
496 /// **What it does:** Checks for `match` with identical arm bodies.
498 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
499 /// are the same on purpose, you can factor them
500 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
502 /// **Known problems:** False positive possible with order dependent `match`
504 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
511 /// Baz => bar(), // <= oops
515 /// This should probably be
520 /// Baz => baz(), // <= fixed
524 /// or if the original code was not a typo:
527 /// Bar | Baz => bar(), // <= shows the intent better
533 "`match` with identical arm bodies"
538 msrv: Option<VersionReq>,
539 infallible_destructuring_match_linted: bool,
544 pub fn new(msrv: Option<VersionReq>) -> Self {
552 impl_lint_pass!(Matches => [
557 MATCH_OVERLAPPING_ARM,
560 WILDCARD_ENUM_MATCH_ARM,
561 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
562 WILDCARD_IN_OR_PATTERNS,
563 MATCH_SINGLE_BINDING,
564 INFALLIBLE_DESTRUCTURING_MATCH,
565 REST_PAT_IN_FULLY_BOUND_STRUCTS,
566 REDUNDANT_PATTERN_MATCHING,
567 MATCH_LIKE_MATCHES_MACRO,
571 const MATCH_LIKE_MATCHES_MACRO_MSRV: Version = Version {
579 impl<'tcx> LateLintPass<'tcx> for Matches {
580 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
581 if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
585 redundant_pattern_match::check(cx, expr);
587 if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
588 if !check_match_like_matches(cx, expr) {
589 lint_match_arms(cx, expr);
592 lint_match_arms(cx, expr);
595 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
596 check_single_match(cx, ex, arms, expr);
597 check_match_bool(cx, ex, arms, expr);
598 check_overlapping_arms(cx, ex, arms);
599 check_wild_err_arm(cx, ex, arms);
600 check_wild_enum_match(cx, ex, arms);
601 check_match_as_ref(cx, ex, arms, expr);
602 check_wild_in_or_pats(cx, arms);
604 if self.infallible_destructuring_match_linted {
605 self.infallible_destructuring_match_linted = false;
607 check_match_single_binding(cx, ex, arms, expr);
610 if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
611 check_match_ref_pats(cx, ex, arms, expr);
615 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
617 if !in_external_macro(cx.sess(), local.span);
618 if !in_macro(local.span);
619 if let Some(ref expr) = local.init;
620 if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
621 if arms.len() == 1 && arms[0].guard.is_none();
622 if let PatKind::TupleStruct(
623 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
625 if let Some(arg) = get_arg_name(&args[0]);
626 let body = remove_blocks(&arms[0].body);
627 if match_var(body, arg);
630 let mut applicability = Applicability::MachineApplicable;
631 self.infallible_destructuring_match_linted = true;
634 INFALLIBLE_DESTRUCTURING_MATCH,
636 "you seem to be trying to use `match` to destructure a single infallible pattern. \
637 Consider using `let`",
641 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
642 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
643 snippet_with_applicability(cx, target.span, "..", &mut applicability),
651 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
653 if !in_external_macro(cx.sess(), pat.span);
654 if !in_macro(pat.span);
655 if let PatKind::Struct(ref qpath, fields, true) = pat.kind;
656 if let QPath::Resolved(_, ref path) = qpath;
657 if let Some(def_id) = path.res.opt_def_id();
658 let ty = cx.tcx.type_of(def_id);
659 if let ty::Adt(def, _) = ty.kind();
660 if def.is_struct() || def.is_union();
661 if fields.len() == def.non_enum_variant().fields.len();
666 REST_PAT_IN_FULLY_BOUND_STRUCTS,
668 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
670 "consider removing `..` from this binding",
676 extract_msrv_attr!(LateContext);
680 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
681 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
682 if in_macro(expr.span) {
683 // Don't lint match expressions present in
684 // macro_rules! block
687 if let PatKind::Or(..) = arms[0].pat.kind {
688 // don't lint for or patterns for now, this makes
689 // the lint noisy in unnecessary situations
692 let els = arms[1].body;
693 let els = if is_unit_expr(remove_blocks(els)) {
695 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
696 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
697 // single statement/expr "else" block, don't lint
700 // block with 2+ statements or 1 expr and 1+ statement
704 // not a block, don't lint
708 let ty = cx.typeck_results().expr_ty(ex);
709 if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
710 check_single_match_single_pattern(cx, ex, arms, expr, els);
711 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
716 fn check_single_match_single_pattern(
717 cx: &LateContext<'_>,
721 els: Option<&Expr<'_>>,
723 if is_wild(&arms[1].pat) {
724 report_single_match_single_pattern(cx, ex, arms, expr, els);
728 fn report_single_match_single_pattern(
729 cx: &LateContext<'_>,
733 els: Option<&Expr<'_>>,
735 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
736 let els_str = els.map_or(String::new(), |els| {
737 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
743 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
747 "if let {} = {} {}{}",
748 snippet(cx, arms[0].pat.span, ".."),
749 snippet(cx, ex.span, ".."),
750 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
753 Applicability::HasPlaceholders,
757 fn check_single_match_opt_like(
758 cx: &LateContext<'_>,
763 els: Option<&Expr<'_>>,
765 // list of candidate `Enum`s we know will never get any more members
767 (&paths::COW, "Borrowed"),
768 (&paths::COW, "Cow::Borrowed"),
769 (&paths::COW, "Cow::Owned"),
770 (&paths::COW, "Owned"),
771 (&paths::OPTION, "None"),
772 (&paths::RESULT, "Err"),
773 (&paths::RESULT, "Ok"),
776 let path = match arms[1].pat.kind {
777 PatKind::TupleStruct(ref path, ref inner, _) => {
778 // Contains any non wildcard patterns (e.g., `Err(err)`)?
779 if !inner.iter().all(is_wild) {
782 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
784 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
785 PatKind::Path(ref path) => {
786 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
791 for &(ty_path, pat_path) in candidates {
792 if path == *pat_path && match_type(cx, ty, ty_path) {
793 report_single_match_single_pattern(cx, ex, arms, expr, els);
798 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
799 // Type of expression is `bool`.
800 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
805 "you seem to be trying to match on a boolean expression",
809 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
810 if let ExprKind::Lit(ref lit) = arm_bool.kind {
812 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
813 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
823 if let Some((true_expr, false_expr)) = exprs {
824 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
825 (false, false) => Some(format!(
827 snippet(cx, ex.span, "b"),
828 expr_block(cx, true_expr, None, "..", Some(expr.span)),
829 expr_block(cx, false_expr, None, "..", Some(expr.span))
831 (false, true) => Some(format!(
833 snippet(cx, ex.span, "b"),
834 expr_block(cx, true_expr, None, "..", Some(expr.span))
837 let test = Sugg::hir(cx, ex, "..");
841 expr_block(cx, false_expr, None, "..", Some(expr.span))
844 (true, true) => None,
847 if let Some(sugg) = sugg {
848 diag.span_suggestion(
850 "consider using an `if`/`else` expression",
852 Applicability::HasPlaceholders,
862 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
863 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
864 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
865 let type_ranges = type_ranges(&ranges);
866 if !type_ranges.is_empty() {
867 if let Some((start, end)) = overlapping(&type_ranges) {
870 MATCH_OVERLAPPING_ARM,
872 "some ranges overlap",
874 "overlaps with this",
881 fn check_wild_err_arm(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
882 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
883 if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
885 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
886 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
887 if path_str == "Err" {
888 let mut matching_wild = inner.iter().any(is_wild);
889 let mut ident_bind_name = String::from("_");
891 // Looking for unused bindings (i.e.: `_e`)
892 inner.iter().for_each(|pat| {
893 if let PatKind::Binding(.., ident, None) = &pat.kind {
894 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
895 ident_bind_name = (&ident.name.as_str()).to_string();
896 matching_wild = true;
903 if let ExprKind::Block(ref block, _) = arm.body.kind;
904 if is_panic_block(block);
906 // `Err(_)` or `Err(_e)` arm with `panic!` found
907 span_lint_and_note(cx,
910 &format!("`Err({})` matches all errors", &ident_bind_name),
912 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
922 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
923 let ty = cx.typeck_results().expr_ty(ex);
925 // If there isn't a nice closed set of possible values that can be conveniently enumerated,
926 // don't complain about not enumerating the mall.
930 // First pass - check for violation, but don't do much book-keeping because this is hopefully
931 // the uncommon case, and the book-keeping is slightly expensive.
932 let mut wildcard_span = None;
933 let mut wildcard_ident = None;
935 if let PatKind::Wild = arm.pat.kind {
936 wildcard_span = Some(arm.pat.span);
937 } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
938 wildcard_span = Some(arm.pat.span);
939 wildcard_ident = Some(ident);
943 if let Some(wildcard_span) = wildcard_span {
944 // Accumulate the variants which should be put in place of the wildcard because they're not
947 let mut missing_variants = vec![];
948 if let ty::Adt(def, _) = ty.kind() {
949 for variant in &def.variants {
950 missing_variants.push(variant);
955 if arm.guard.is_some() {
956 // Guards mean that this case probably isn't exhaustively covered. Technically
957 // this is incorrect, as we should really check whether each variant is exhaustively
958 // covered by the set of guards that cover it, but that's really hard to do.
961 if let PatKind::Path(ref path) = arm.pat.kind {
962 if let QPath::Resolved(_, p) = path {
963 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
965 } else if let PatKind::TupleStruct(ref path, ref patterns, ..) = arm.pat.kind {
966 if let QPath::Resolved(_, p) = path {
967 // Some simple checks for exhaustive patterns.
968 // There is a room for improvements to detect more cases,
969 // but it can be more expensive to do so.
970 let is_pattern_exhaustive =
971 |pat: &&Pat<'_>| matches!(pat.kind, PatKind::Wild | PatKind::Binding(.., None));
972 if patterns.iter().all(is_pattern_exhaustive) {
973 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
979 let mut suggestion: Vec<String> = missing_variants
982 let suffix = match v.ctor_kind {
983 CtorKind::Fn => "(..)",
984 CtorKind::Const | CtorKind::Fictive => "",
986 let ident_str = if let Some(ident) = wildcard_ident {
987 format!("{} @ ", ident.name)
991 // This path assumes that the enum type is imported into scope.
992 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
996 if suggestion.is_empty() {
1000 let mut message = "wildcard match will miss any future added variants";
1002 if let ty::Adt(def, _) = ty.kind() {
1003 if def.is_variant_list_non_exhaustive() {
1004 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
1005 suggestion.push(String::from("_"));
1009 if suggestion.len() == 1 {
1010 // No need to check for non-exhaustive enum as in that case len would be greater than 1
1013 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1017 suggestion[0].clone(),
1018 Applicability::MaybeIncorrect,
1024 WILDCARD_ENUM_MATCH_ARM,
1028 suggestion.join(" | "),
1029 Applicability::MaybeIncorrect,
1034 // If the block contains only a `panic!` macro (as expression or statement)
1035 fn is_panic_block(block: &Block<'_>) -> bool {
1036 match (&block.expr, block.stmts.len(), block.stmts.first()) {
1037 (&Some(ref exp), 0, _) => {
1038 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
1040 (&None, 1, Some(stmt)) => {
1041 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1047 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1048 if has_only_ref_pats(arms) {
1049 let mut suggs = Vec::with_capacity(arms.len() + 1);
1050 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1051 let span = ex.span.source_callsite();
1052 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1054 "you don't need to add `&` to both the expression and the patterns",
1058 let span = ex.span.source_callsite();
1059 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1061 "you don't need to add `&` to all patterns",
1062 "instead of prefixing all patterns with `&`, you can dereference the expression",
1066 suggs.extend(arms.iter().filter_map(|a| {
1067 if let PatKind::Ref(ref refp, _) = a.pat.kind {
1068 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1074 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1075 if !expr.span.from_expansion() {
1076 multispan_sugg(diag, msg, suggs);
1082 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1083 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1084 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
1085 is_ref_some_arm(&arms[1])
1086 } else if is_none_arm(&arms[1]) {
1087 is_ref_some_arm(&arms[0])
1091 if let Some(rb) = arm_ref {
1092 let suggestion = if rb == BindingAnnotation::Ref {
1098 let output_ty = cx.typeck_results().expr_ty(expr);
1099 let input_ty = cx.typeck_results().expr_ty(ex);
1101 let cast = if_chain! {
1102 if let ty::Adt(_, substs) = input_ty.kind();
1103 let input_ty = substs.type_at(0);
1104 if let ty::Adt(_, substs) = output_ty.kind();
1105 let output_ty = substs.type_at(0);
1106 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1107 if input_ty != output_ty;
1115 let mut applicability = Applicability::MachineApplicable;
1120 &format!("use `{}()` instead", suggestion),
1124 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1134 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1136 if let PatKind::Or(ref fields) = arm.pat.kind {
1137 // look for multiple fields in this arm that contains at least one Wild pattern
1138 if fields.len() > 1 && fields.iter().any(is_wild) {
1141 WILDCARD_IN_OR_PATTERNS,
1143 "wildcard pattern covers any other pattern as it will match anyway.",
1145 "Consider handling `_` separately.",
1152 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1153 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1154 if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1155 match match_source {
1156 MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1157 MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1165 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1166 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1169 if cx.typeck_results().expr_ty(expr).is_bool();
1170 if let Some((b1_arm, b0_arms)) = arms.split_last();
1171 if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1172 if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1173 if is_wild(&b1_arm.pat);
1175 let if_guard = &b0_arms[0].guard;
1176 if if_guard.is_none() || b0_arms.len() == 1;
1177 if b0_arms[0].attrs.is_empty();
1178 if b0_arms[1..].iter()
1180 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1181 arm.guard.is_none() && arm.attrs.is_empty()
1184 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1185 // evaluated into `false` and so such arms will be stripped before.
1186 let mut applicability = Applicability::MaybeIncorrect;
1188 use itertools::Itertools as _;
1190 .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1193 let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1194 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1200 MATCH_LIKE_MATCHES_MACRO,
1202 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1205 "{}matches!({}, {})",
1206 if b0 { "" } else { "!" },
1207 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1219 /// Extract a `bool` or `{ bool }`
1220 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1222 ExprKind::Lit(Spanned {
1223 node: LitKind::Bool(b), ..
1233 if let ExprKind::Lit(Spanned {
1234 node: LitKind::Bool(b), ..
1246 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1247 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1250 let matched_vars = ex.span;
1251 let bind_names = arms[0].pat.span;
1252 let match_body = remove_blocks(&arms[0].body);
1253 let mut snippet_body = if match_body.span.from_expansion() {
1254 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1256 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1259 // Do we need to add ';' to suggestion ?
1260 match match_body.kind {
1261 ExprKind::Block(block, _) => {
1262 // macro + expr_ty(body) == ()
1263 if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() {
1264 snippet_body.push(';');
1268 // expr_ty(body) == ()
1269 if cx.typeck_results().expr_ty(&match_body).is_unit() {
1270 snippet_body.push(';');
1275 let mut applicability = Applicability::MaybeIncorrect;
1276 match arms[0].pat.kind {
1277 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1278 // If this match is in a local (`let`) stmt
1279 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1281 parent_let_node.span,
1283 "let {} = {};\n{}let {} = {};",
1284 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1285 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1286 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1287 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1292 // If we are in closure, we need curly braces around suggestion
1293 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1294 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1295 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1296 if let ExprKind::Closure(..) = parent_expr.kind {
1297 cbrace_end = format!("\n{}}}", indent);
1298 // Fix body indent due to the closure
1299 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1300 cbrace_start = format!("{{\n{}", indent);
1306 "{}let {} = {};\n{}{}{}",
1308 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1309 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1318 MATCH_SINGLE_BINDING,
1320 "this match could be written as a `let` statement",
1321 "consider using `let` statement",
1329 MATCH_SINGLE_BINDING,
1331 "this match could be replaced by its body itself",
1332 "consider using the match body instead",
1334 Applicability::MachineApplicable,
1341 /// Returns true if the `ex` match expression is in a local (`let`) statement
1342 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1344 let map = &cx.tcx.hir();
1345 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1346 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1348 return Some(parent_let_expr);
1354 /// Gets all arms that are unbounded `PatRange`s.
1355 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1359 ref pat, guard: None, ..
1362 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1363 let lhs = match lhs {
1364 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1365 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1367 let rhs = match rhs {
1368 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1369 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1371 let rhs = match range_end {
1372 RangeEnd::Included => Bound::Included(rhs),
1373 RangeEnd::Excluded => Bound::Excluded(rhs),
1375 return Some(SpannedRange {
1381 if let PatKind::Lit(ref value) = pat.kind {
1382 let value = constant(cx, cx.typeck_results(), value)?.0;
1383 return Some(SpannedRange {
1385 node: (value.clone(), Bound::Included(value)),
1394 #[derive(Debug, Eq, PartialEq)]
1395 pub struct SpannedRange<T> {
1397 pub node: (T, Bound<T>),
1400 type TypedRanges = Vec<SpannedRange<u128>>;
1402 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1403 /// and other types than
1404 /// `Uint` and `Int` probably don't make sense.
1405 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1408 .filter_map(|range| match range.node {
1409 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1411 node: (start, Bound::Included(end)),
1413 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1415 node: (start, Bound::Excluded(end)),
1417 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1419 node: (start, Bound::Unbounded),
1426 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1428 ExprKind::Tup(ref v) if v.is_empty() => true,
1429 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1434 // Checks if arm has the form `None => None`
1435 fn is_none_arm(arm: &Arm<'_>) -> bool {
1436 matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE))
1439 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1440 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1442 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1443 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1444 if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1445 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1446 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1447 if let ExprKind::Path(ref some_path) = e.kind;
1448 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1449 if let ExprKind::Path(ref qpath) = args[0].kind;
1450 if let &QPath::Resolved(_, ref path2) = qpath;
1451 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1459 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1464 PatKind::Ref(..) => Some(true), // &-patterns
1465 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1466 _ => None, // any other pattern is not fine
1469 .collect::<Option<Vec<bool>>>();
1470 // look for Some(v) where there's at least one true element
1471 mapped.map_or(false, |v| v.iter().any(|el| *el))
1474 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1478 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1480 Start(T, &'a SpannedRange<T>),
1481 End(Bound<T>, &'a SpannedRange<T>),
1484 impl<'a, T: Copy> Kind<'a, T> {
1485 fn range(&self) -> &'a SpannedRange<T> {
1487 Kind::Start(_, r) | Kind::End(_, r) => r,
1491 fn value(self) -> Bound<T> {
1493 Kind::Start(t, _) => Bound::Included(t),
1494 Kind::End(t, _) => t,
1499 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1500 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1501 Some(self.cmp(other))
1505 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1506 fn cmp(&self, other: &Self) -> Ordering {
1507 match (self.value(), other.value()) {
1508 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1509 // Range patterns cannot be unbounded (yet)
1510 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1511 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1512 Ordering::Equal => Ordering::Greater,
1515 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1516 Ordering::Equal => Ordering::Less,
1523 let mut values = Vec::with_capacity(2 * ranges.len());
1526 values.push(Kind::Start(r.node.0, r));
1527 values.push(Kind::End(r.node.1, r));
1532 for (a, b) in values.iter().zip(values.iter().skip(1)) {
1534 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1535 if ra.node != rb.node {
1536 return Some((ra, rb));
1539 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1540 _ => return Some((a.range(), b.range())),
1547 mod redundant_pattern_match {
1548 use super::REDUNDANT_PATTERN_MATCHING;
1549 use crate::utils::{match_qpath, match_trait_method, paths, snippet, span_lint_and_then};
1550 use if_chain::if_chain;
1551 use rustc_ast::ast::LitKind;
1552 use rustc_errors::Applicability;
1553 use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1554 use rustc_lint::LateContext;
1555 use rustc_span::sym;
1557 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1558 if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1559 match match_source {
1560 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1561 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1562 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1568 fn find_sugg_for_if_let<'tcx>(
1569 cx: &LateContext<'tcx>,
1570 expr: &'tcx Expr<'_>,
1573 keyword: &'static str,
1575 let good_method = match arms[0].pat.kind {
1576 PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => {
1577 if let PatKind::Wild = patterns[0].kind {
1578 if match_qpath(path, &paths::RESULT_OK) {
1580 } else if match_qpath(path, &paths::RESULT_ERR) {
1582 } else if match_qpath(path, &paths::OPTION_SOME) {
1584 } else if match_qpath(path, &paths::POLL_READY) {
1586 } else if match_qpath(path, &paths::IPADDR_V4) {
1588 } else if match_qpath(path, &paths::IPADDR_V6) {
1597 PatKind::Path(ref path) => {
1598 if match_qpath(path, &paths::OPTION_NONE) {
1600 } else if match_qpath(path, &paths::POLL_PENDING) {
1609 // check that `while_let_on_iterator` lint does not trigger
1611 if keyword == "while";
1612 if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1613 if method_path.ident.name == sym::next;
1614 if match_trait_method(cx, op, &paths::ITERATOR);
1620 let result_expr = match &op.kind {
1621 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1626 REDUNDANT_PATTERN_MATCHING,
1628 &format!("redundant pattern matching, consider using `{}`", good_method),
1630 // while let ... = ... { ... }
1631 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1632 let expr_span = expr.span;
1634 // while let ... = ... { ... }
1636 let op_span = result_expr.span.source_callsite();
1638 // while let ... = ... { ... }
1639 // ^^^^^^^^^^^^^^^^^^^
1640 let span = expr_span.until(op_span.shrink_to_hi());
1641 diag.span_suggestion(
1644 format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1645 Applicability::MachineApplicable, // snippet
1651 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1652 if arms.len() == 2 {
1653 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1655 let found_good_method = match node_pair {
1657 PatKind::TupleStruct(ref path_left, ref patterns_left, _),
1658 PatKind::TupleStruct(ref path_right, ref patterns_right, _),
1659 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1660 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1661 find_good_method_for_match(
1671 find_good_method_for_match(
1685 (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right))
1686 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _))
1687 if patterns.len() == 1 =>
1689 if let PatKind::Wild = patterns[0].kind {
1690 find_good_method_for_match(
1694 &paths::OPTION_SOME,
1695 &paths::OPTION_NONE,
1700 find_good_method_for_match(
1705 &paths::POLL_PENDING,
1717 if let Some(good_method) = found_good_method {
1718 let span = expr.span.to(op.span);
1719 let result_expr = match &op.kind {
1720 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1725 REDUNDANT_PATTERN_MATCHING,
1727 &format!("redundant pattern matching, consider using `{}`", good_method),
1729 diag.span_suggestion(
1732 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1733 Applicability::MaybeIncorrect, // snippet
1741 fn find_good_method_for_match<'a>(
1743 path_left: &QPath<'_>,
1744 path_right: &QPath<'_>,
1745 expected_left: &[&str],
1746 expected_right: &[&str],
1747 should_be_left: &'a str,
1748 should_be_right: &'a str,
1749 ) -> Option<&'a str> {
1750 let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) {
1751 (&(*arms[0].body).kind, &(*arms[1].body).kind)
1752 } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) {
1753 (&(*arms[1].body).kind, &(*arms[0].body).kind)
1758 match body_node_pair {
1759 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1760 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1761 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1770 fn test_overlapping() {
1771 use rustc_span::source_map::DUMMY_SP;
1773 let sp = |s, e| SpannedRange {
1778 assert_eq!(None, overlapping::<u8>(&[]));
1779 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1782 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1787 sp(1, Bound::Included(4)),
1788 sp(5, Bound::Included(6)),
1789 sp(10, Bound::Included(11))
1793 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1794 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1797 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1799 sp(1, Bound::Included(4)),
1800 sp(5, Bound::Included(6)),
1801 sp(6, Bound::Included(11))
1806 /// Implementation of `MATCH_SAME_ARMS`.
1807 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1808 fn same_bindings<'tcx>(lhs: &FxHashMap<Symbol, Ty<'tcx>>, rhs: &FxHashMap<Symbol, Ty<'tcx>>) -> bool {
1809 lhs.len() == rhs.len()
1812 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| TyS::same_type(l_ty, r_ty)))
1815 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
1816 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1817 let mut h = SpanlessHash::new(cx);
1818 h.hash_expr(&arm.body);
1822 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1823 let min_index = usize::min(lindex, rindex);
1824 let max_index = usize::max(lindex, rindex);
1826 // Arms with a guard are ignored, those can’t always be merged together
1827 // This is also the case for arms in-between each there is an arm with a guard
1828 (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
1829 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
1830 // all patterns should have the same bindings
1831 same_bindings(&bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
1834 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
1835 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
1840 "this `match` has identical arm bodies",
1842 diag.span_note(i.body.span, "same as this");
1844 // Note: this does not use `span_suggestion` on purpose:
1845 // there is no clean way
1846 // to remove the other arm. Building a span and suggest to replace it to ""
1847 // makes an even more confusing error message. Also in order not to make up a
1848 // span for the whole pattern, the suggestion is only shown when there is only
1849 // one pattern. The user should know about `|` if they are already using it…
1851 let lhs = snippet(cx, i.pat.span, "<pat1>");
1852 let rhs = snippet(cx, j.pat.span, "<pat2>");
1854 if let PatKind::Wild = j.pat.kind {
1855 // if the last arm is _, then i could be integrated into _
1856 // note that i.pat cannot be _, because that would mean that we're
1857 // hiding all the subsequent arms, and rust won't compile
1861 "`{}` has the same arm body as the `_` wildcard, consider removing it",
1866 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
1874 /// Returns the list of bindings in a pattern.
1875 fn bindings<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>) -> FxHashMap<Symbol, Ty<'tcx>> {
1876 fn bindings_impl<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
1878 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
1879 PatKind::TupleStruct(_, pats, _) => {
1881 bindings_impl(cx, pat, map);
1884 PatKind::Binding(.., ident, ref as_pat) => {
1885 if let Entry::Vacant(v) = map.entry(ident.name) {
1886 v.insert(cx.typeck_results().pat_ty(pat));
1888 if let Some(ref as_pat) = *as_pat {
1889 bindings_impl(cx, as_pat, map);
1892 PatKind::Or(fields) | PatKind::Tuple(fields, _) => {
1894 bindings_impl(cx, pat, map);
1897 PatKind::Struct(_, fields, _) => {
1899 bindings_impl(cx, &pat.pat, map);
1902 PatKind::Slice(lhs, ref mid, rhs) => {
1904 bindings_impl(cx, pat, map);
1906 if let Some(ref mid) = *mid {
1907 bindings_impl(cx, mid, map);
1910 bindings_impl(cx, pat, map);
1913 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
1917 let mut result = FxHashMap::default();
1918 bindings_impl(cx, pat, &mut result);