1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::sugg::Sugg;
3 use crate::utils::visitors::LocalUsedVisitor;
5 expr_block, get_parent_expr, implements_trait, in_macro, indent_of, is_allowed, is_expn_of, is_refutable,
6 is_type_diagnostic_item, is_wild, match_qpath, match_type, meets_msrv, multispan_sugg, path_to_local,
7 path_to_local_id, peel_hir_pat_refs, peel_mid_ty_refs, peel_n_hir_expr_refs, remove_blocks, snippet, snippet_block,
8 snippet_opt, snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
9 span_lint_and_then, strip_pat_refs,
11 use crate::utils::{paths, search_same, SpanlessEq, SpanlessHash};
12 use if_chain::if_chain;
13 use rustc_ast::ast::LitKind;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_errors::Applicability;
16 use rustc_hir::def::CtorKind;
18 Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource, Mutability, Node, Pat,
19 PatKind, QPath, RangeEnd,
21 use rustc_lint::{LateContext, LateLintPass, LintContext};
22 use rustc_middle::lint::in_external_macro;
23 use rustc_middle::ty::{self, Ty, TyS};
24 use rustc_semver::RustcVersion;
25 use rustc_session::{declare_tool_lint, impl_lint_pass};
26 use rustc_span::source_map::{Span, Spanned};
28 use std::cmp::Ordering;
29 use std::collections::hash_map::Entry;
30 use std::collections::Bound;
32 declare_clippy_lint! {
33 /// **What it does:** Checks for matches with a single arm where an `if let`
34 /// will usually suffice.
36 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
38 /// **Known problems:** None.
42 /// # fn bar(stool: &str) {}
43 /// # let x = Some("abc");
46 /// Some(ref foo) => bar(foo),
51 /// if let Some(ref foo) = x {
57 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
60 declare_clippy_lint! {
61 /// **What it does:** Checks for matches with two arms where an `if let else` will
64 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
66 /// **Known problems:** Personal style preferences may differ.
73 /// # fn bar(foo: &usize) {}
74 /// # let other_ref: usize = 1;
75 /// # let x: Option<&usize> = Some(&1);
77 /// Some(ref foo) => bar(foo),
78 /// _ => bar(&other_ref),
82 /// Using `if let` with `else`:
85 /// # fn bar(foo: &usize) {}
86 /// # let other_ref: usize = 1;
87 /// # let x: Option<&usize> = Some(&1);
88 /// if let Some(ref foo) = x {
94 pub SINGLE_MATCH_ELSE,
96 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
99 declare_clippy_lint! {
100 /// **What it does:** Checks for matches where all arms match a reference,
101 /// suggesting to remove the reference and deref the matched expression
102 /// instead. It also checks for `if let &foo = bar` blocks.
104 /// **Why is this bad?** It just makes the code less readable. That reference
105 /// destructuring adds nothing to the code.
107 /// **Known problems:** None.
113 /// &A(ref y) => foo(y),
120 /// A(ref y) => foo(y),
127 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
130 declare_clippy_lint! {
131 /// **What it does:** Checks for matches where match expression is a `bool`. It
132 /// suggests to replace the expression with an `if...else` block.
134 /// **Why is this bad?** It makes the code less readable.
136 /// **Known problems:** None.
142 /// let condition: bool = true;
143 /// match condition {
148 /// Use if/else instead:
152 /// let condition: bool = true;
161 "a `match` on a boolean expression instead of an `if..else` block"
164 declare_clippy_lint! {
165 /// **What it does:** Checks for overlapping match arms.
167 /// **Why is this bad?** It is likely to be an error and if not, makes the code
170 /// **Known problems:** None.
176 /// 1...10 => println!("1 ... 10"),
177 /// 5...15 => println!("5 ... 15"),
181 pub MATCH_OVERLAPPING_ARM,
183 "a `match` with overlapping arms"
186 declare_clippy_lint! {
187 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
188 /// and take drastic actions like `panic!`.
190 /// **Why is this bad?** It is generally a bad practice, similar to
191 /// catching all exceptions in java with `catch(Exception)`
193 /// **Known problems:** None.
197 /// let x: Result<i32, &str> = Ok(3);
199 /// Ok(_) => println!("ok"),
200 /// Err(_) => panic!("err"),
203 pub MATCH_WILD_ERR_ARM,
205 "a `match` with `Err(_)` arm and take drastic actions"
208 declare_clippy_lint! {
209 /// **What it does:** Checks for match which is used to add a reference to an
212 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
214 /// **Known problems:** None.
218 /// let x: Option<()> = None;
221 /// let r: Option<&()> = match x {
223 /// Some(ref v) => Some(v),
227 /// let r: Option<&()> = x.as_ref();
231 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
234 declare_clippy_lint! {
235 /// **What it does:** Checks for wildcard enum matches using `_`.
237 /// **Why is this bad?** New enum variants added by library updates can be missed.
239 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
240 /// variants, and also may not use correct path to enum if it's not present in the current scope.
244 /// # enum Foo { A(usize), B(usize) }
245 /// # let x = Foo::B(1);
258 pub WILDCARD_ENUM_MATCH_ARM,
260 "a wildcard enum match arm using `_`"
263 declare_clippy_lint! {
264 /// **What it does:** Checks for wildcard enum matches for a single variant.
266 /// **Why is this bad?** New enum variants added by library updates can be missed.
268 /// **Known problems:** Suggested replacements may not use correct path to enum
269 /// if it's not present in the current scope.
274 /// # enum Foo { A, B, C }
275 /// # let x = Foo::B;
290 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
292 "a wildcard enum match for a single variant"
295 declare_clippy_lint! {
296 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
298 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
299 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
301 /// **Known problems:** None.
317 pub WILDCARD_IN_OR_PATTERNS,
319 "a wildcard pattern used with others patterns in same match arm"
322 declare_clippy_lint! {
323 /// **What it does:** Checks for matches being used to destructure a single-variant enum
324 /// or tuple struct where a `let` will suffice.
326 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
328 /// **Known problems:** None.
336 /// let wrapper = Wrapper::Data(42);
338 /// let data = match wrapper {
339 /// Wrapper::Data(i) => i,
343 /// The correct use would be:
349 /// let wrapper = Wrapper::Data(42);
350 /// let Wrapper::Data(data) = wrapper;
352 pub INFALLIBLE_DESTRUCTURING_MATCH,
354 "a `match` statement with a single infallible arm instead of a `let`"
357 declare_clippy_lint! {
358 /// **What it does:** Checks for useless match that binds to only one value.
360 /// **Why is this bad?** Readability and needless complexity.
362 /// **Known problems:** Suggested replacements may be incorrect when `match`
363 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
378 /// let (c, d) = (a, b);
380 pub MATCH_SINGLE_BINDING,
382 "a match with a single binding instead of using `let` statement"
385 declare_clippy_lint! {
386 /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
388 /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
389 /// matching all enum variants explicitly.
391 /// **Known problems:** None.
395 /// # struct A { a: i32 }
396 /// let a = A { a: 5 };
400 /// A { a: 5, .. } => {},
406 /// A { a: 5 } => {},
410 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
412 "a match on a struct that binds all fields but still uses the wildcard pattern"
415 declare_clippy_lint! {
416 /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
417 /// `std::task::Poll` or `std::net::IpAddr`
419 /// **Why is this bad?** It's more concise and clear to just use the proper
422 /// **Known problems:** None.
427 /// # use std::task::Poll;
428 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
429 /// if let Ok(_) = Ok::<i32, i32>(42) {}
430 /// if let Err(_) = Err::<i32, i32>(42) {}
431 /// if let None = None::<()> {}
432 /// if let Some(_) = Some(42) {}
433 /// if let Poll::Pending = Poll::Pending::<()> {}
434 /// if let Poll::Ready(_) = Poll::Ready(42) {}
435 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
436 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
437 /// match Ok::<i32, i32>(42) {
443 /// The more idiomatic use would be:
446 /// # use std::task::Poll;
447 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
448 /// if Ok::<i32, i32>(42).is_ok() {}
449 /// if Err::<i32, i32>(42).is_err() {}
450 /// if None::<()>.is_none() {}
451 /// if Some(42).is_some() {}
452 /// if Poll::Pending::<()>.is_pending() {}
453 /// if Poll::Ready(42).is_ready() {}
454 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
455 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
456 /// Ok::<i32, i32>(42).is_ok();
458 pub REDUNDANT_PATTERN_MATCHING,
460 "use the proper utility function avoiding an `if let`"
463 declare_clippy_lint! {
464 /// **What it does:** Checks for `match` or `if let` expressions producing a
465 /// `bool` that could be written using `matches!`
467 /// **Why is this bad?** Readability and needless complexity.
469 /// **Known problems:** This lint falsely triggers, if there are arms with
470 /// `cfg` attributes that remove an arm evaluating to `false`.
477 /// let a = match x {
482 /// let a = if let Some(0) = x {
489 /// let a = matches!(x, Some(0));
491 pub MATCH_LIKE_MATCHES_MACRO,
493 "a match that could be written with the matches! macro"
496 declare_clippy_lint! {
497 /// **What it does:** Checks for `match` with identical arm bodies.
499 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
500 /// are the same on purpose, you can factor them
501 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
503 /// **Known problems:** False positive possible with order dependent `match`
505 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
512 /// Baz => bar(), // <= oops
516 /// This should probably be
521 /// Baz => baz(), // <= fixed
525 /// or if the original code was not a typo:
528 /// Bar | Baz => bar(), // <= shows the intent better
534 "`match` with identical arm bodies"
539 msrv: Option<RustcVersion>,
540 infallible_destructuring_match_linted: bool,
545 pub fn new(msrv: Option<RustcVersion>) -> Self {
553 impl_lint_pass!(Matches => [
558 MATCH_OVERLAPPING_ARM,
561 WILDCARD_ENUM_MATCH_ARM,
562 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
563 WILDCARD_IN_OR_PATTERNS,
564 MATCH_SINGLE_BINDING,
565 INFALLIBLE_DESTRUCTURING_MATCH,
566 REST_PAT_IN_FULLY_BOUND_STRUCTS,
567 REDUNDANT_PATTERN_MATCHING,
568 MATCH_LIKE_MATCHES_MACRO,
572 const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0);
574 impl<'tcx> LateLintPass<'tcx> for Matches {
575 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
576 if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
580 redundant_pattern_match::check(cx, expr);
582 if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
583 if !check_match_like_matches(cx, expr) {
584 lint_match_arms(cx, expr);
587 lint_match_arms(cx, expr);
590 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
591 check_single_match(cx, ex, arms, expr);
592 check_match_bool(cx, ex, arms, expr);
593 check_overlapping_arms(cx, ex, arms);
594 check_wild_err_arm(cx, ex, arms);
595 check_wild_enum_match(cx, ex, arms);
596 check_match_as_ref(cx, ex, arms, expr);
597 check_wild_in_or_pats(cx, arms);
599 if self.infallible_destructuring_match_linted {
600 self.infallible_destructuring_match_linted = false;
602 check_match_single_binding(cx, ex, arms, expr);
605 if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
606 check_match_ref_pats(cx, ex, arms, expr);
610 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
612 if !in_external_macro(cx.sess(), local.span);
613 if !in_macro(local.span);
614 if let Some(ref expr) = local.init;
615 if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
616 if arms.len() == 1 && arms[0].guard.is_none();
617 if let PatKind::TupleStruct(
618 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
620 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
621 let body = remove_blocks(&arms[0].body);
622 if path_to_local_id(body, arg);
625 let mut applicability = Applicability::MachineApplicable;
626 self.infallible_destructuring_match_linted = true;
629 INFALLIBLE_DESTRUCTURING_MATCH,
631 "you seem to be trying to use `match` to destructure a single infallible pattern. \
632 Consider using `let`",
636 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
637 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
638 snippet_with_applicability(cx, target.span, "..", &mut applicability),
646 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
648 if !in_external_macro(cx.sess(), pat.span);
649 if !in_macro(pat.span);
650 if let PatKind::Struct(QPath::Resolved(_, ref path), fields, true) = pat.kind;
651 if let Some(def_id) = path.res.opt_def_id();
652 let ty = cx.tcx.type_of(def_id);
653 if let ty::Adt(def, _) = ty.kind();
654 if def.is_struct() || def.is_union();
655 if fields.len() == def.non_enum_variant().fields.len();
660 REST_PAT_IN_FULLY_BOUND_STRUCTS,
662 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
664 "consider removing `..` from this binding",
670 extract_msrv_attr!(LateContext);
674 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
675 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
676 if in_macro(expr.span) {
677 // Don't lint match expressions present in
678 // macro_rules! block
681 if let PatKind::Or(..) = arms[0].pat.kind {
682 // don't lint for or patterns for now, this makes
683 // the lint noisy in unnecessary situations
686 let els = arms[1].body;
687 let els = if is_unit_expr(remove_blocks(els)) {
689 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
690 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
691 // single statement/expr "else" block, don't lint
694 // block with 2+ statements or 1 expr and 1+ statement
697 // not a block, don't lint
701 let ty = cx.typeck_results().expr_ty(ex);
702 if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
703 check_single_match_single_pattern(cx, ex, arms, expr, els);
704 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
709 fn check_single_match_single_pattern(
710 cx: &LateContext<'_>,
714 els: Option<&Expr<'_>>,
716 if is_wild(&arms[1].pat) {
717 report_single_match_single_pattern(cx, ex, arms, expr, els);
721 fn report_single_match_single_pattern(
722 cx: &LateContext<'_>,
726 els: Option<&Expr<'_>>,
728 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
729 let els_str = els.map_or(String::new(), |els| {
730 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
733 let (msg, sugg) = if_chain! {
734 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
735 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
736 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
737 if let Some(trait_id) = cx.tcx.lang_items().structural_peq_trait();
738 if ty.is_integral() || ty.is_char() || ty.is_str() || implements_trait(cx, ty, trait_id, &[]);
740 // scrutinee derives PartialEq and the pattern is a constant.
741 let pat_ref_count = match pat.kind {
742 // string literals are already a reference.
743 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
746 // References are only implicitly added to the pattern, so no overflow here.
747 // e.g. will work: match &Some(_) { Some(_) => () }
748 // will not: match Some(_) { &Some(_) => () }
749 let ref_count_diff = ty_ref_count - pat_ref_count;
751 // Try to remove address of expressions first.
752 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
753 let ref_count_diff = ref_count_diff - removed;
755 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
757 "if {} == {}{} {}{}",
758 snippet(cx, ex.span, ".."),
759 // PartialEq for different reference counts may not exist.
760 "&".repeat(ref_count_diff),
761 snippet(cx, arms[0].pat.span, ".."),
762 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
767 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
769 "if let {} = {} {}{}",
770 snippet(cx, arms[0].pat.span, ".."),
771 snippet(cx, ex.span, ".."),
772 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
786 Applicability::HasPlaceholders,
790 fn check_single_match_opt_like(
791 cx: &LateContext<'_>,
796 els: Option<&Expr<'_>>,
798 // list of candidate `Enum`s we know will never get any more members
800 (&paths::COW, "Borrowed"),
801 (&paths::COW, "Cow::Borrowed"),
802 (&paths::COW, "Cow::Owned"),
803 (&paths::COW, "Owned"),
804 (&paths::OPTION, "None"),
805 (&paths::RESULT, "Err"),
806 (&paths::RESULT, "Ok"),
809 let path = match arms[1].pat.kind {
810 PatKind::TupleStruct(ref path, ref inner, _) => {
811 // Contains any non wildcard patterns (e.g., `Err(err)`)?
812 if !inner.iter().all(is_wild) {
815 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
817 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
818 PatKind::Path(ref path) => {
819 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
824 for &(ty_path, pat_path) in candidates {
825 if path == *pat_path && match_type(cx, ty, ty_path) {
826 report_single_match_single_pattern(cx, ex, arms, expr, els);
831 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
832 // Type of expression is `bool`.
833 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
838 "you seem to be trying to match on a boolean expression",
842 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
843 if let ExprKind::Lit(ref lit) = arm_bool.kind {
845 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
846 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
856 if let Some((true_expr, false_expr)) = exprs {
857 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
858 (false, false) => Some(format!(
860 snippet(cx, ex.span, "b"),
861 expr_block(cx, true_expr, None, "..", Some(expr.span)),
862 expr_block(cx, false_expr, None, "..", Some(expr.span))
864 (false, true) => Some(format!(
866 snippet(cx, ex.span, "b"),
867 expr_block(cx, true_expr, None, "..", Some(expr.span))
870 let test = Sugg::hir(cx, ex, "..");
874 expr_block(cx, false_expr, None, "..", Some(expr.span))
877 (true, true) => None,
880 if let Some(sugg) = sugg {
881 diag.span_suggestion(
883 "consider using an `if`/`else` expression",
885 Applicability::HasPlaceholders,
895 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
896 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
897 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
898 let type_ranges = type_ranges(&ranges);
899 if !type_ranges.is_empty() {
900 if let Some((start, end)) = overlapping(&type_ranges) {
903 MATCH_OVERLAPPING_ARM,
905 "some ranges overlap",
907 "overlaps with this",
914 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
915 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
916 if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
918 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
919 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
920 if path_str == "Err" {
921 let mut matching_wild = inner.iter().any(is_wild);
922 let mut ident_bind_name = String::from("_");
924 // Looking for unused bindings (i.e.: `_e`)
925 inner.iter().for_each(|pat| {
926 if let PatKind::Binding(_, id, ident, None) = pat.kind {
927 if ident.as_str().starts_with('_')
928 && !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
930 ident_bind_name = (&ident.name.as_str()).to_string();
931 matching_wild = true;
938 if let ExprKind::Block(ref block, _) = arm.body.kind;
939 if is_panic_block(block);
941 // `Err(_)` or `Err(_e)` arm with `panic!` found
942 span_lint_and_note(cx,
945 &format!("`Err({})` matches all errors", &ident_bind_name),
947 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
957 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
958 let ty = cx.typeck_results().expr_ty(ex);
960 // If there isn't a nice closed set of possible values that can be conveniently enumerated,
961 // don't complain about not enumerating the mall.
965 // First pass - check for violation, but don't do much book-keeping because this is hopefully
966 // the uncommon case, and the book-keeping is slightly expensive.
967 let mut wildcard_span = None;
968 let mut wildcard_ident = None;
970 if let PatKind::Wild = arm.pat.kind {
971 wildcard_span = Some(arm.pat.span);
972 } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
973 wildcard_span = Some(arm.pat.span);
974 wildcard_ident = Some(ident);
978 if let Some(wildcard_span) = wildcard_span {
979 // Accumulate the variants which should be put in place of the wildcard because they're not
982 let mut missing_variants = vec![];
983 if let ty::Adt(def, _) = ty.kind() {
984 for variant in &def.variants {
985 missing_variants.push(variant);
990 if arm.guard.is_some() {
991 // Guards mean that this case probably isn't exhaustively covered. Technically
992 // this is incorrect, as we should really check whether each variant is exhaustively
993 // covered by the set of guards that cover it, but that's really hard to do.
996 if let PatKind::Path(ref path) = arm.pat.kind {
997 if let QPath::Resolved(_, p) = path {
998 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
1000 } else if let PatKind::TupleStruct(QPath::Resolved(_, p), ref patterns, ..) = arm.pat.kind {
1001 // Some simple checks for exhaustive patterns.
1002 // There is a room for improvements to detect more cases,
1003 // but it can be more expensive to do so.
1004 let is_pattern_exhaustive =
1005 |pat: &&Pat<'_>| matches!(pat.kind, PatKind::Wild | PatKind::Binding(.., None));
1006 if patterns.iter().all(is_pattern_exhaustive) {
1007 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
1012 let mut suggestion: Vec<String> = missing_variants
1015 let suffix = match v.ctor_kind {
1016 CtorKind::Fn => "(..)",
1017 CtorKind::Const | CtorKind::Fictive => "",
1019 let ident_str = if let Some(ident) = wildcard_ident {
1020 format!("{} @ ", ident.name)
1024 // This path assumes that the enum type is imported into scope.
1025 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
1029 if suggestion.is_empty() {
1033 let mut message = "wildcard match will miss any future added variants";
1035 if let ty::Adt(def, _) = ty.kind() {
1036 if def.is_variant_list_non_exhaustive() {
1037 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
1038 suggestion.push(String::from("_"));
1042 if suggestion.len() == 1 {
1043 // No need to check for non-exhaustive enum as in that case len would be greater than 1
1046 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1050 suggestion[0].clone(),
1051 Applicability::MaybeIncorrect,
1057 WILDCARD_ENUM_MATCH_ARM,
1061 suggestion.join(" | "),
1062 Applicability::MaybeIncorrect,
1067 // If the block contains only a `panic!` macro (as expression or statement)
1068 fn is_panic_block(block: &Block<'_>) -> bool {
1069 match (&block.expr, block.stmts.len(), block.stmts.first()) {
1070 (&Some(ref exp), 0, _) => {
1071 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
1073 (&None, 1, Some(stmt)) => {
1074 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1080 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1081 if has_only_ref_pats(arms) {
1082 let mut suggs = Vec::with_capacity(arms.len() + 1);
1083 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1084 let span = ex.span.source_callsite();
1085 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1087 "you don't need to add `&` to both the expression and the patterns",
1091 let span = ex.span.source_callsite();
1092 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1094 "you don't need to add `&` to all patterns",
1095 "instead of prefixing all patterns with `&`, you can dereference the expression",
1099 suggs.extend(arms.iter().filter_map(|a| {
1100 if let PatKind::Ref(ref refp, _) = a.pat.kind {
1101 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1107 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1108 if !expr.span.from_expansion() {
1109 multispan_sugg(diag, msg, suggs);
1115 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1116 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1117 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
1118 is_ref_some_arm(&arms[1])
1119 } else if is_none_arm(&arms[1]) {
1120 is_ref_some_arm(&arms[0])
1124 if let Some(rb) = arm_ref {
1125 let suggestion = if rb == BindingAnnotation::Ref {
1131 let output_ty = cx.typeck_results().expr_ty(expr);
1132 let input_ty = cx.typeck_results().expr_ty(ex);
1134 let cast = if_chain! {
1135 if let ty::Adt(_, substs) = input_ty.kind();
1136 let input_ty = substs.type_at(0);
1137 if let ty::Adt(_, substs) = output_ty.kind();
1138 let output_ty = substs.type_at(0);
1139 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1140 if input_ty != output_ty;
1148 let mut applicability = Applicability::MachineApplicable;
1153 &format!("use `{}()` instead", suggestion),
1157 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1167 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1169 if let PatKind::Or(ref fields) = arm.pat.kind {
1170 // look for multiple fields in this arm that contains at least one Wild pattern
1171 if fields.len() > 1 && fields.iter().any(is_wild) {
1174 WILDCARD_IN_OR_PATTERNS,
1176 "wildcard pattern covers any other pattern as it will match anyway.",
1178 "Consider handling `_` separately.",
1185 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1186 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1187 if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1188 match match_source {
1189 MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1190 MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1198 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1199 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1202 if cx.typeck_results().expr_ty(expr).is_bool();
1203 if let Some((b1_arm, b0_arms)) = arms.split_last();
1204 if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1205 if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1206 if is_wild(&b1_arm.pat);
1208 let if_guard = &b0_arms[0].guard;
1209 if if_guard.is_none() || b0_arms.len() == 1;
1210 if b0_arms[0].attrs.is_empty();
1211 if b0_arms[1..].iter()
1213 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1214 arm.guard.is_none() && arm.attrs.is_empty()
1217 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1218 // evaluated into `false` and so such arms will be stripped before.
1219 let mut applicability = Applicability::MaybeIncorrect;
1221 use itertools::Itertools as _;
1223 .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1226 let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1227 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1232 // strip potential borrows (#6503), but only if the type is a reference
1233 let mut ex_new = ex;
1234 if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1235 if let ty::Ref(..) = cx.typeck_results().expr_ty(&ex_inner).kind() {
1241 MATCH_LIKE_MATCHES_MACRO,
1243 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1246 "{}matches!({}, {})",
1247 if b0 { "" } else { "!" },
1248 snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1260 /// Extract a `bool` or `{ bool }`
1261 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1263 ExprKind::Lit(Spanned {
1264 node: LitKind::Bool(b), ..
1274 if let ExprKind::Lit(Spanned {
1275 node: LitKind::Bool(b), ..
1287 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1288 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1293 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1294 // to prevent false positives as there is currently no better way to detect if code was excluded by
1295 // a macro. See PR #6435
1297 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1298 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1299 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1300 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1301 if rest_snippet.contains("=>");
1303 // The code it self contains another thick arrow "=>"
1304 // -> Either another arm or a comment
1309 let matched_vars = ex.span;
1310 let bind_names = arms[0].pat.span;
1311 let match_body = remove_blocks(&arms[0].body);
1312 let mut snippet_body = if match_body.span.from_expansion() {
1313 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1315 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1318 // Do we need to add ';' to suggestion ?
1319 match match_body.kind {
1320 ExprKind::Block(block, _) => {
1321 // macro + expr_ty(body) == ()
1322 if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() {
1323 snippet_body.push(';');
1327 // expr_ty(body) == ()
1328 if cx.typeck_results().expr_ty(&match_body).is_unit() {
1329 snippet_body.push(';');
1334 let mut applicability = Applicability::MaybeIncorrect;
1335 match arms[0].pat.kind {
1336 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1337 // If this match is in a local (`let`) stmt
1338 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1340 parent_let_node.span,
1342 "let {} = {};\n{}let {} = {};",
1343 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1344 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1345 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1346 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1351 // If we are in closure, we need curly braces around suggestion
1352 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1353 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1354 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1355 if let ExprKind::Closure(..) = parent_expr.kind {
1356 cbrace_end = format!("\n{}}}", indent);
1357 // Fix body indent due to the closure
1358 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1359 cbrace_start = format!("{{\n{}", indent);
1365 "{}let {} = {};\n{}{}{}",
1367 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1368 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1377 MATCH_SINGLE_BINDING,
1379 "this match could be written as a `let` statement",
1380 "consider using `let` statement",
1388 MATCH_SINGLE_BINDING,
1390 "this match could be replaced by its body itself",
1391 "consider using the match body instead",
1393 Applicability::MachineApplicable,
1400 /// Returns true if the `ex` match expression is in a local (`let`) statement
1401 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1403 let map = &cx.tcx.hir();
1404 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1405 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1407 return Some(parent_let_expr);
1413 /// Gets all arms that are unbounded `PatRange`s.
1414 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1418 ref pat, guard: None, ..
1421 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1422 let lhs = match lhs {
1423 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1424 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1426 let rhs = match rhs {
1427 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1428 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1430 let rhs = match range_end {
1431 RangeEnd::Included => Bound::Included(rhs),
1432 RangeEnd::Excluded => Bound::Excluded(rhs),
1434 return Some(SpannedRange {
1440 if let PatKind::Lit(ref value) = pat.kind {
1441 let value = constant(cx, cx.typeck_results(), value)?.0;
1442 return Some(SpannedRange {
1444 node: (value.clone(), Bound::Included(value)),
1453 #[derive(Debug, Eq, PartialEq)]
1454 pub struct SpannedRange<T> {
1456 pub node: (T, Bound<T>),
1459 type TypedRanges = Vec<SpannedRange<u128>>;
1461 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1462 /// and other types than
1463 /// `Uint` and `Int` probably don't make sense.
1464 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1467 .filter_map(|range| match range.node {
1468 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1470 node: (start, Bound::Included(end)),
1472 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1474 node: (start, Bound::Excluded(end)),
1476 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1478 node: (start, Bound::Unbounded),
1485 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1487 ExprKind::Tup(ref v) if v.is_empty() => true,
1488 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1493 // Checks if arm has the form `None => None`
1494 fn is_none_arm(arm: &Arm<'_>) -> bool {
1495 matches!(arm.pat.kind, PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE))
1498 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1499 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1501 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1502 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1503 if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1504 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1505 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1506 if let ExprKind::Path(ref some_path) = e.kind;
1507 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1508 if let ExprKind::Path(QPath::Resolved(_, ref path2)) = args[0].kind;
1509 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1517 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1522 PatKind::Ref(..) => Some(true), // &-patterns
1523 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1524 _ => None, // any other pattern is not fine
1527 .collect::<Option<Vec<bool>>>();
1528 // look for Some(v) where there's at least one true element
1529 mapped.map_or(false, |v| v.iter().any(|el| *el))
1532 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1536 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1538 Start(T, &'a SpannedRange<T>),
1539 End(Bound<T>, &'a SpannedRange<T>),
1542 impl<'a, T: Copy> Kind<'a, T> {
1543 fn range(&self) -> &'a SpannedRange<T> {
1545 Kind::Start(_, r) | Kind::End(_, r) => r,
1549 fn value(self) -> Bound<T> {
1551 Kind::Start(t, _) => Bound::Included(t),
1552 Kind::End(t, _) => t,
1557 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1558 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1559 Some(self.cmp(other))
1563 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1564 fn cmp(&self, other: &Self) -> Ordering {
1565 match (self.value(), other.value()) {
1566 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1567 // Range patterns cannot be unbounded (yet)
1568 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1569 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1570 Ordering::Equal => Ordering::Greater,
1573 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1574 Ordering::Equal => Ordering::Less,
1581 let mut values = Vec::with_capacity(2 * ranges.len());
1584 values.push(Kind::Start(r.node.0, r));
1585 values.push(Kind::End(r.node.1, r));
1590 for (a, b) in values.iter().zip(values.iter().skip(1)) {
1592 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1593 if ra.node != rb.node {
1594 return Some((ra, rb));
1597 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1599 // skip if the range `a` is completely included into the range `b`
1600 if let Ordering::Equal | Ordering::Less = a.cmp(&b) {
1601 let kind_a = Kind::End(a.range().node.1, a.range());
1602 let kind_b = Kind::End(b.range().node.1, b.range());
1603 if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1607 return Some((a.range(), b.range()));
1615 mod redundant_pattern_match {
1616 use super::REDUNDANT_PATTERN_MATCHING;
1617 use crate::utils::{match_qpath, match_trait_method, paths, snippet, span_lint_and_then};
1618 use if_chain::if_chain;
1619 use rustc_ast::ast::LitKind;
1620 use rustc_errors::Applicability;
1621 use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1622 use rustc_lint::LateContext;
1623 use rustc_span::sym;
1625 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1626 if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1627 match match_source {
1628 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1629 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1630 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1636 fn find_sugg_for_if_let<'tcx>(
1637 cx: &LateContext<'tcx>,
1638 expr: &'tcx Expr<'_>,
1641 keyword: &'static str,
1643 let good_method = match arms[0].pat.kind {
1644 PatKind::TupleStruct(ref path, ref patterns, _) if patterns.len() == 1 => {
1645 if let PatKind::Wild = patterns[0].kind {
1646 if match_qpath(path, &paths::RESULT_OK) {
1648 } else if match_qpath(path, &paths::RESULT_ERR) {
1650 } else if match_qpath(path, &paths::OPTION_SOME) {
1652 } else if match_qpath(path, &paths::POLL_READY) {
1654 } else if match_qpath(path, &paths::IPADDR_V4) {
1656 } else if match_qpath(path, &paths::IPADDR_V6) {
1665 PatKind::Path(ref path) => {
1666 if match_qpath(path, &paths::OPTION_NONE) {
1668 } else if match_qpath(path, &paths::POLL_PENDING) {
1677 // check that `while_let_on_iterator` lint does not trigger
1679 if keyword == "while";
1680 if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1681 if method_path.ident.name == sym::next;
1682 if match_trait_method(cx, op, &paths::ITERATOR);
1688 let result_expr = match &op.kind {
1689 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1694 REDUNDANT_PATTERN_MATCHING,
1696 &format!("redundant pattern matching, consider using `{}`", good_method),
1698 // while let ... = ... { ... }
1699 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1700 let expr_span = expr.span;
1702 // while let ... = ... { ... }
1704 let op_span = result_expr.span.source_callsite();
1706 // while let ... = ... { ... }
1707 // ^^^^^^^^^^^^^^^^^^^
1708 let span = expr_span.until(op_span.shrink_to_hi());
1709 diag.span_suggestion(
1712 format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1713 Applicability::MachineApplicable, // snippet
1719 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1720 if arms.len() == 2 {
1721 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1723 let found_good_method = match node_pair {
1725 PatKind::TupleStruct(ref path_left, ref patterns_left, _),
1726 PatKind::TupleStruct(ref path_right, ref patterns_right, _),
1727 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1728 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1729 find_good_method_for_match(
1739 find_good_method_for_match(
1753 (PatKind::TupleStruct(ref path_left, ref patterns, _), PatKind::Path(ref path_right))
1754 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, ref patterns, _))
1755 if patterns.len() == 1 =>
1757 if let PatKind::Wild = patterns[0].kind {
1758 find_good_method_for_match(
1762 &paths::OPTION_SOME,
1763 &paths::OPTION_NONE,
1768 find_good_method_for_match(
1773 &paths::POLL_PENDING,
1785 if let Some(good_method) = found_good_method {
1786 let span = expr.span.to(op.span);
1787 let result_expr = match &op.kind {
1788 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1793 REDUNDANT_PATTERN_MATCHING,
1795 &format!("redundant pattern matching, consider using `{}`", good_method),
1797 diag.span_suggestion(
1800 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1801 Applicability::MaybeIncorrect, // snippet
1809 fn find_good_method_for_match<'a>(
1811 path_left: &QPath<'_>,
1812 path_right: &QPath<'_>,
1813 expected_left: &[&str],
1814 expected_right: &[&str],
1815 should_be_left: &'a str,
1816 should_be_right: &'a str,
1817 ) -> Option<&'a str> {
1818 let body_node_pair = if match_qpath(path_left, expected_left) && match_qpath(path_right, expected_right) {
1819 (&(*arms[0].body).kind, &(*arms[1].body).kind)
1820 } else if match_qpath(path_right, expected_left) && match_qpath(path_left, expected_right) {
1821 (&(*arms[1].body).kind, &(*arms[0].body).kind)
1826 match body_node_pair {
1827 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1828 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1829 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1838 fn test_overlapping() {
1839 use rustc_span::source_map::DUMMY_SP;
1841 let sp = |s, e| SpannedRange {
1846 assert_eq!(None, overlapping::<u8>(&[]));
1847 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1850 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1855 sp(1, Bound::Included(4)),
1856 sp(5, Bound::Included(6)),
1857 sp(10, Bound::Included(11))
1861 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1862 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1865 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1867 sp(1, Bound::Included(4)),
1868 sp(5, Bound::Included(6)),
1869 sp(6, Bound::Included(11))
1874 /// Implementation of `MATCH_SAME_ARMS`.
1875 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1876 if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
1877 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1878 let mut h = SpanlessHash::new(cx);
1879 h.hash_expr(&arm.body);
1883 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1884 let min_index = usize::min(lindex, rindex);
1885 let max_index = usize::max(lindex, rindex);
1887 let mut local_map: FxHashMap<HirId, HirId> = FxHashMap::default();
1888 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
1890 if let Some(a_id) = path_to_local(a);
1891 if let Some(b_id) = path_to_local(b);
1892 let entry = match local_map.entry(a_id) {
1893 Entry::Vacant(entry) => entry,
1894 // check if using the same bindings as before
1895 Entry::Occupied(entry) => return *entry.get() == b_id,
1897 // the names technically don't have to match; this makes the lint more conservative
1898 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
1899 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
1900 if pat_contains_local(lhs.pat, a_id);
1901 if pat_contains_local(rhs.pat, b_id);
1910 // Arms with a guard are ignored, those can’t always be merged together
1911 // This is also the case for arms in-between each there is an arm with a guard
1912 (min_index..=max_index).all(|index| arms[index].guard.is_none())
1913 && SpanlessEq::new(cx)
1914 .expr_fallback(eq_fallback)
1915 .eq_expr(&lhs.body, &rhs.body)
1916 // these checks could be removed to allow unused bindings
1917 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
1918 && bindings_eq(rhs.pat, local_map.values().copied().collect())
1921 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
1922 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
1927 "this `match` has identical arm bodies",
1929 diag.span_note(i.body.span, "same as this");
1931 // Note: this does not use `span_suggestion` on purpose:
1932 // there is no clean way
1933 // to remove the other arm. Building a span and suggest to replace it to ""
1934 // makes an even more confusing error message. Also in order not to make up a
1935 // span for the whole pattern, the suggestion is only shown when there is only
1936 // one pattern. The user should know about `|` if they are already using it…
1938 let lhs = snippet(cx, i.pat.span, "<pat1>");
1939 let rhs = snippet(cx, j.pat.span, "<pat2>");
1941 if let PatKind::Wild = j.pat.kind {
1942 // if the last arm is _, then i could be integrated into _
1943 // note that i.pat cannot be _, because that would mean that we're
1944 // hiding all the subsequent arms, and rust won't compile
1948 "`{}` has the same arm body as the `_` wildcard, consider removing it",
1953 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
1961 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
1962 let mut result = false;
1963 pat.walk_short(|p| {
1964 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
1970 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
1971 fn bindings_eq(pat: &Pat<'_>, mut ids: FxHashSet<HirId>) -> bool {
1972 let mut result = true;
1973 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
1974 result && ids.is_empty()