1 use clippy_utils::diagnostics::{
2 multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
4 use clippy_utils::macros::{is_panic, root_macro_call};
5 use clippy_utils::peel_blocks_with_stmt;
6 use clippy_utils::source::{indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
7 use clippy_utils::sugg::Sugg;
8 use clippy_utils::ty::is_type_diagnostic_item;
9 use clippy_utils::visitors::is_local_used;
11 get_parent_expr, is_lang_ctor, is_refutable, is_wild, meets_msrv, msrvs, path_to_local_id, peel_blocks,
12 peel_hir_pat_refs, recurse_or_patterns, strip_pat_refs,
15 use if_chain::if_chain;
16 use rustc_errors::Applicability;
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::LangItem::{OptionNone, OptionSome};
20 self as hir, Arm, BindingAnnotation, BorrowKind, Expr, ExprKind, Local, MatchSource, Mutability, Node, Pat,
21 PatKind, PathSegment, QPath, TyKind,
23 use rustc_lint::{LateContext, LateLintPass};
24 use rustc_middle::ty::{self, VariantDef};
25 use rustc_semver::RustcVersion;
26 use rustc_session::{declare_tool_lint, impl_lint_pass};
27 use rustc_span::{sym, symbol::kw};
30 mod match_like_matches;
33 mod redundant_pattern_match;
36 declare_clippy_lint! {
38 /// Checks for matches with a single arm where an `if let`
39 /// will usually suffice.
41 /// ### Why is this bad?
42 /// Just readability – `if let` nests less than a `match`.
46 /// # fn bar(stool: &str) {}
47 /// # let x = Some("abc");
50 /// Some(ref foo) => bar(foo),
55 /// if let Some(ref foo) = x {
59 #[clippy::version = "pre 1.29.0"]
62 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
65 declare_clippy_lint! {
67 /// Checks for matches with two arms where an `if let else` will
70 /// ### Why is this bad?
71 /// Just readability – `if let` nests less than a `match`.
73 /// ### Known problems
74 /// Personal style preferences may differ.
80 /// # fn bar(foo: &usize) {}
81 /// # let other_ref: usize = 1;
82 /// # let x: Option<&usize> = Some(&1);
84 /// Some(ref foo) => bar(foo),
85 /// _ => bar(&other_ref),
89 /// Using `if let` with `else`:
92 /// # fn bar(foo: &usize) {}
93 /// # let other_ref: usize = 1;
94 /// # let x: Option<&usize> = Some(&1);
95 /// if let Some(ref foo) = x {
101 #[clippy::version = "pre 1.29.0"]
102 pub SINGLE_MATCH_ELSE,
104 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
107 declare_clippy_lint! {
109 /// Checks for matches where all arms match a reference,
110 /// suggesting to remove the reference and deref the matched expression
111 /// instead. It also checks for `if let &foo = bar` blocks.
113 /// ### Why is this bad?
114 /// It just makes the code less readable. That reference
115 /// destructuring adds nothing to the code.
121 /// &A(ref y) => foo(y),
128 /// A(ref y) => foo(y),
133 #[clippy::version = "pre 1.29.0"]
136 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
139 declare_clippy_lint! {
141 /// Checks for matches where match expression is a `bool`. It
142 /// suggests to replace the expression with an `if...else` block.
144 /// ### Why is this bad?
145 /// It makes the code less readable.
151 /// let condition: bool = true;
152 /// match condition {
157 /// Use if/else instead:
161 /// let condition: bool = true;
168 #[clippy::version = "pre 1.29.0"]
171 "a `match` on a boolean expression instead of an `if..else` block"
174 declare_clippy_lint! {
176 /// Checks for overlapping match arms.
178 /// ### Why is this bad?
179 /// It is likely to be an error and if not, makes the code
186 /// 1..=10 => println!("1 ... 10"),
187 /// 5..=15 => println!("5 ... 15"),
191 #[clippy::version = "pre 1.29.0"]
192 pub MATCH_OVERLAPPING_ARM,
194 "a `match` with overlapping arms"
197 declare_clippy_lint! {
199 /// Checks for arm which matches all errors with `Err(_)`
200 /// and take drastic actions like `panic!`.
202 /// ### Why is this bad?
203 /// It is generally a bad practice, similar to
204 /// catching all exceptions in java with `catch(Exception)`
208 /// let x: Result<i32, &str> = Ok(3);
210 /// Ok(_) => println!("ok"),
211 /// Err(_) => panic!("err"),
214 #[clippy::version = "pre 1.29.0"]
215 pub MATCH_WILD_ERR_ARM,
217 "a `match` with `Err(_)` arm and take drastic actions"
220 declare_clippy_lint! {
222 /// Checks for match which is used to add a reference to an
225 /// ### Why is this bad?
226 /// Using `as_ref()` or `as_mut()` instead is shorter.
230 /// let x: Option<()> = None;
233 /// let r: Option<&()> = match x {
235 /// Some(ref v) => Some(v),
239 /// let r: Option<&()> = x.as_ref();
241 #[clippy::version = "pre 1.29.0"]
244 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
247 declare_clippy_lint! {
249 /// Checks for wildcard enum matches using `_`.
251 /// ### Why is this bad?
252 /// New enum variants added by library updates can be missed.
254 /// ### Known problems
255 /// Suggested replacements may be incorrect if guards exhaustively cover some
256 /// variants, and also may not use correct path to enum if it's not present in the current scope.
260 /// # enum Foo { A(usize), B(usize) }
261 /// # let x = Foo::B(1);
274 #[clippy::version = "1.34.0"]
275 pub WILDCARD_ENUM_MATCH_ARM,
277 "a wildcard enum match arm using `_`"
280 declare_clippy_lint! {
282 /// Checks for wildcard enum matches for a single variant.
284 /// ### Why is this bad?
285 /// New enum variants added by library updates can be missed.
287 /// ### Known problems
288 /// Suggested replacements may not use correct path to enum
289 /// if it's not present in the current scope.
293 /// # enum Foo { A, B, C }
294 /// # let x = Foo::B;
309 #[clippy::version = "1.45.0"]
310 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
312 "a wildcard enum match for a single variant"
315 declare_clippy_lint! {
317 /// Checks for wildcard pattern used with others patterns in same match arm.
319 /// ### Why is this bad?
320 /// Wildcard pattern already covers any other pattern as it will match anyway.
321 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
337 #[clippy::version = "1.42.0"]
338 pub WILDCARD_IN_OR_PATTERNS,
340 "a wildcard pattern used with others patterns in same match arm"
343 declare_clippy_lint! {
345 /// Checks for matches being used to destructure a single-variant enum
346 /// or tuple struct where a `let` will suffice.
348 /// ### Why is this bad?
349 /// Just readability – `let` doesn't nest, whereas a `match` does.
357 /// let wrapper = Wrapper::Data(42);
359 /// let data = match wrapper {
360 /// Wrapper::Data(i) => i,
364 /// The correct use would be:
370 /// let wrapper = Wrapper::Data(42);
371 /// let Wrapper::Data(data) = wrapper;
373 #[clippy::version = "pre 1.29.0"]
374 pub INFALLIBLE_DESTRUCTURING_MATCH,
376 "a `match` statement with a single infallible arm instead of a `let`"
379 declare_clippy_lint! {
381 /// Checks for useless match that binds to only one value.
383 /// ### Why is this bad?
384 /// Readability and needless complexity.
386 /// ### Known problems
387 /// Suggested replacements may be incorrect when `match`
388 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
403 /// let (c, d) = (a, b);
405 #[clippy::version = "1.43.0"]
406 pub MATCH_SINGLE_BINDING,
408 "a match with a single binding instead of using `let` statement"
411 declare_clippy_lint! {
413 /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
415 /// ### Why is this bad?
416 /// Correctness and readability. It's like having a wildcard pattern after
417 /// matching all enum variants explicitly.
421 /// # struct A { a: i32 }
422 /// let a = A { a: 5 };
426 /// A { a: 5, .. } => {},
432 /// A { a: 5 } => {},
436 #[clippy::version = "1.43.0"]
437 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
439 "a match on a struct that binds all fields but still uses the wildcard pattern"
442 declare_clippy_lint! {
444 /// Lint for redundant pattern matching over `Result`, `Option`,
445 /// `std::task::Poll` or `std::net::IpAddr`
447 /// ### Why is this bad?
448 /// It's more concise and clear to just use the proper
451 /// ### Known problems
452 /// This will change the drop order for the matched type. Both `if let` and
453 /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
454 /// value before entering the block. For most types this change will not matter, but for a few
455 /// types this will not be an acceptable change (e.g. locks). See the
456 /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
461 /// # use std::task::Poll;
462 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
463 /// if let Ok(_) = Ok::<i32, i32>(42) {}
464 /// if let Err(_) = Err::<i32, i32>(42) {}
465 /// if let None = None::<()> {}
466 /// if let Some(_) = Some(42) {}
467 /// if let Poll::Pending = Poll::Pending::<()> {}
468 /// if let Poll::Ready(_) = Poll::Ready(42) {}
469 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
470 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
471 /// match Ok::<i32, i32>(42) {
477 /// The more idiomatic use would be:
480 /// # use std::task::Poll;
481 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
482 /// if Ok::<i32, i32>(42).is_ok() {}
483 /// if Err::<i32, i32>(42).is_err() {}
484 /// if None::<()>.is_none() {}
485 /// if Some(42).is_some() {}
486 /// if Poll::Pending::<()>.is_pending() {}
487 /// if Poll::Ready(42).is_ready() {}
488 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
489 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
490 /// Ok::<i32, i32>(42).is_ok();
492 #[clippy::version = "1.31.0"]
493 pub REDUNDANT_PATTERN_MATCHING,
495 "use the proper utility function avoiding an `if let`"
498 declare_clippy_lint! {
500 /// Checks for `match` or `if let` expressions producing a
501 /// `bool` that could be written using `matches!`
503 /// ### Why is this bad?
504 /// Readability and needless complexity.
506 /// ### Known problems
507 /// This lint falsely triggers, if there are arms with
508 /// `cfg` attributes that remove an arm evaluating to `false`.
515 /// let a = match x {
520 /// let a = if let Some(0) = x {
527 /// let a = matches!(x, Some(0));
529 #[clippy::version = "1.47.0"]
530 pub MATCH_LIKE_MATCHES_MACRO,
532 "a match that could be written with the matches! macro"
535 declare_clippy_lint! {
537 /// Checks for `match` with identical arm bodies.
539 /// ### Why is this bad?
540 /// This is probably a copy & paste error. If arm bodies
541 /// are the same on purpose, you can factor them
542 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
544 /// ### Known problems
545 /// False positive possible with order dependent `match`
547 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
554 /// Baz => bar(), // <= oops
558 /// This should probably be
563 /// Baz => baz(), // <= fixed
567 /// or if the original code was not a typo:
570 /// Bar | Baz => bar(), // <= shows the intent better
574 #[clippy::version = "pre 1.29.0"]
577 "`match` with identical arm bodies"
582 msrv: Option<RustcVersion>,
583 infallible_destructuring_match_linted: bool,
588 pub fn new(msrv: Option<RustcVersion>) -> Self {
596 impl_lint_pass!(Matches => [
601 MATCH_OVERLAPPING_ARM,
604 WILDCARD_ENUM_MATCH_ARM,
605 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
606 WILDCARD_IN_OR_PATTERNS,
607 MATCH_SINGLE_BINDING,
608 INFALLIBLE_DESTRUCTURING_MATCH,
609 REST_PAT_IN_FULLY_BOUND_STRUCTS,
610 REDUNDANT_PATTERN_MATCHING,
611 MATCH_LIKE_MATCHES_MACRO,
615 impl<'tcx> LateLintPass<'tcx> for Matches {
616 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
617 if expr.span.from_expansion() {
621 redundant_pattern_match::check(cx, expr);
623 if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
624 if !match_like_matches::check(cx, expr) {
625 match_same_arms::check(cx, expr);
628 match_same_arms::check(cx, expr);
631 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
632 single_match::check(cx, ex, arms, expr);
633 match_bool::check(cx, ex, arms, expr);
634 overlapping_arms::check(cx, ex, arms);
635 check_wild_err_arm(cx, ex, arms);
636 check_wild_enum_match(cx, ex, arms);
637 check_match_as_ref(cx, ex, arms, expr);
638 check_wild_in_or_pats(cx, arms);
640 if self.infallible_destructuring_match_linted {
641 self.infallible_destructuring_match_linted = false;
643 check_match_single_binding(cx, ex, arms, expr);
646 if let ExprKind::Match(ex, arms, _) = expr.kind {
647 check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
651 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
653 if !local.span.from_expansion();
654 if let Some(expr) = local.init;
655 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
656 if arms.len() == 1 && arms[0].guard.is_none();
657 if let PatKind::TupleStruct(
658 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
660 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
661 let body = peel_blocks(arms[0].body);
662 if path_to_local_id(body, arg);
665 let mut applicability = Applicability::MachineApplicable;
666 self.infallible_destructuring_match_linted = true;
669 INFALLIBLE_DESTRUCTURING_MATCH,
671 "you seem to be trying to use `match` to destructure a single infallible pattern. \
672 Consider using `let`",
676 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
677 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
678 snippet_with_applicability(cx, target.span, "..", &mut applicability),
686 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
688 if !pat.span.from_expansion();
689 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
690 if let Some(def_id) = path.res.opt_def_id();
691 let ty = cx.tcx.type_of(def_id);
692 if let ty::Adt(def, _) = ty.kind();
693 if def.is_struct() || def.is_union();
694 if fields.len() == def.non_enum_variant().fields.len();
699 REST_PAT_IN_FULLY_BOUND_STRUCTS,
701 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
703 "consider removing `..` from this binding",
709 extract_msrv_attr!(LateContext);
712 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
713 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
714 if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
716 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
717 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
718 if path_str == "Err" {
719 let mut matching_wild = inner.iter().any(is_wild);
720 let mut ident_bind_name = kw::Underscore;
722 // Looking for unused bindings (i.e.: `_e`)
723 for pat in inner.iter() {
724 if let PatKind::Binding(_, id, ident, None) = pat.kind {
725 if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
726 ident_bind_name = ident.name;
727 matching_wild = true;
734 if let Some(macro_call) = root_macro_call(peel_blocks_with_stmt(arm.body).span);
735 if is_panic(cx, macro_call.def_id);
737 // `Err(_)` or `Err(_e)` arm with `panic!` found
738 span_lint_and_note(cx,
741 &format!("`Err({})` matches all errors", ident_bind_name),
743 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
753 enum CommonPrefixSearcher<'a> {
755 Path(&'a [PathSegment<'a>]),
758 impl<'a> CommonPrefixSearcher<'a> {
759 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
761 [path @ .., _] => self.with_prefix(path),
766 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
768 Self::None => *self = Self::Path(path),
769 Self::Path(self_path)
772 .map(|p| p.ident.name)
773 .eq(self_path.iter().map(|p| p.ident.name)) => {},
774 Self::Path(_) => *self = Self::Mixed,
780 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
781 let attrs = cx.tcx.get_attrs(variant_def.def_id);
782 clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
785 #[allow(clippy::too_many_lines)]
786 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
787 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
788 let adt_def = match ty.kind() {
791 && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
798 // First pass - check for violation, but don't do much book-keeping because this is hopefully
799 // the uncommon case, and the book-keeping is slightly expensive.
800 let mut wildcard_span = None;
801 let mut wildcard_ident = None;
802 let mut has_non_wild = false;
804 match peel_hir_pat_refs(arm.pat).0.kind {
805 PatKind::Wild => wildcard_span = Some(arm.pat.span),
806 PatKind::Binding(_, _, ident, None) => {
807 wildcard_span = Some(arm.pat.span);
808 wildcard_ident = Some(ident);
810 _ => has_non_wild = true,
813 let wildcard_span = match wildcard_span {
814 Some(x) if has_non_wild => x,
818 // Accumulate the variants which should be put in place of the wildcard because they're not
820 let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
821 let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
823 let mut path_prefix = CommonPrefixSearcher::None;
825 // Guards mean that this case probably isn't exhaustively covered. Technically
826 // this is incorrect, as we should really check whether each variant is exhaustively
827 // covered by the set of guards that cover it, but that's really hard to do.
828 recurse_or_patterns(arm.pat, |pat| {
829 let path = match &peel_hir_pat_refs(pat).0.kind {
830 PatKind::Path(path) => {
831 #[allow(clippy::match_same_arms)]
832 let id = match cx.qpath_res(path, pat.hir_id) {
834 DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
837 Res::Def(_, id) => id,
840 if arm.guard.is_none() {
841 missing_variants.retain(|e| e.ctor_def_id != Some(id));
845 PatKind::TupleStruct(path, patterns, ..) => {
846 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
847 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
848 missing_variants.retain(|e| e.ctor_def_id != Some(id));
853 PatKind::Struct(path, patterns, ..) => {
854 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
855 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
856 missing_variants.retain(|e| e.def_id != id);
864 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
867 kind: TyKind::Path(QPath::Resolved(_, path)),
871 ) => path_prefix.with_prefix(path.segments),
877 let format_suggestion = |variant: &VariantDef| {
880 if let Some(ident) = wildcard_ident {
881 format!("{} @ ", ident.name)
885 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
886 let mut s = String::new();
887 for seg in path_prefix {
888 s.push_str(seg.ident.as_str());
893 let mut s = cx.tcx.def_path_str(adt_def.did);
898 match variant.ctor_kind {
899 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
900 CtorKind::Fn => "(..)",
901 CtorKind::Const => "",
902 CtorKind::Fictive => "{ .. }",
907 match missing_variants.as_slice() {
909 [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
911 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
913 "wildcard matches only a single variant and will also match any future added variants",
915 format_suggestion(x),
916 Applicability::MaybeIncorrect,
919 let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
920 let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
921 suggestions.push("_".into());
922 "wildcard matches known variants and will also match future added variants"
924 "wildcard match will also match any future added variants"
929 WILDCARD_ENUM_MATCH_ARM,
933 suggestions.join(" | "),
934 Applicability::MaybeIncorrect,
940 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
943 I: Clone + Iterator<Item = &'a Pat<'b>>,
945 if !has_multiple_ref_pats(pats.clone()) {
949 let (first_sugg, msg, title);
950 let span = ex.span.source_callsite();
951 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
952 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
954 title = "you don't need to add `&` to both the expression and the patterns";
956 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
957 msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
958 title = "you don't need to add `&` to all patterns";
961 let remaining_suggs = pats.filter_map(|pat| {
962 if let PatKind::Ref(refp, _) = pat.kind {
963 Some((pat.span, snippet(cx, refp.span, "..").to_string()))
969 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
970 if !expr.span.from_expansion() {
971 multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
976 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
977 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
978 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
979 is_ref_some_arm(cx, &arms[1])
980 } else if is_none_arm(cx, &arms[1]) {
981 is_ref_some_arm(cx, &arms[0])
985 if let Some(rb) = arm_ref {
986 let suggestion = if rb == BindingAnnotation::Ref {
992 let output_ty = cx.typeck_results().expr_ty(expr);
993 let input_ty = cx.typeck_results().expr_ty(ex);
995 let cast = if_chain! {
996 if let ty::Adt(_, substs) = input_ty.kind();
997 let input_ty = substs.type_at(0);
998 if let ty::Adt(_, substs) = output_ty.kind();
999 let output_ty = substs.type_at(0);
1000 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1001 if input_ty != output_ty;
1009 let mut applicability = Applicability::MachineApplicable;
1014 &format!("use `{}()` instead", suggestion),
1018 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1028 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1030 if let PatKind::Or(fields) = arm.pat.kind {
1031 // look for multiple fields in this arm that contains at least one Wild pattern
1032 if fields.len() > 1 && fields.iter().any(is_wild) {
1035 WILDCARD_IN_OR_PATTERNS,
1037 "wildcard pattern covers any other pattern as it will match anyway",
1039 "consider handling `_` separately",
1046 #[allow(clippy::too_many_lines)]
1047 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1048 if expr.span.from_expansion() || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1053 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1054 // to prevent false positives as there is currently no better way to detect if code was excluded by
1055 // a macro. See PR #6435
1057 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1058 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1059 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1060 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1061 if rest_snippet.contains("=>");
1063 // The code it self contains another thick arrow "=>"
1064 // -> Either another arm or a comment
1069 let matched_vars = ex.span;
1070 let bind_names = arms[0].pat.span;
1071 let match_body = peel_blocks(arms[0].body);
1072 let mut snippet_body = if match_body.span.from_expansion() {
1073 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1075 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1078 // Do we need to add ';' to suggestion ?
1079 match match_body.kind {
1080 ExprKind::Block(block, _) => {
1081 // macro + expr_ty(body) == ()
1082 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1083 snippet_body.push(';');
1087 // expr_ty(body) == ()
1088 if cx.typeck_results().expr_ty(match_body).is_unit() {
1089 snippet_body.push(';');
1094 let mut applicability = Applicability::MaybeIncorrect;
1095 match arms[0].pat.kind {
1096 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1097 // If this match is in a local (`let`) stmt
1098 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1100 parent_let_node.span,
1102 "let {} = {};\n{}let {} = {};",
1103 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1104 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1105 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1106 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1111 // If we are in closure, we need curly braces around suggestion
1112 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1113 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1114 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1115 if let ExprKind::Closure(..) = parent_expr.kind {
1116 cbrace_end = format!("\n{}}}", indent);
1117 // Fix body indent due to the closure
1118 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1119 cbrace_start = format!("{{\n{}", indent);
1122 // If the parent is already an arm, and the body is another match statement,
1123 // we need curly braces around suggestion
1124 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1125 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1126 if let ExprKind::Match(..) = arm.body.kind {
1127 cbrace_end = format!("\n{}}}", indent);
1128 // Fix body indent due to the match
1129 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1130 cbrace_start = format!("{{\n{}", indent);
1136 "{}let {} = {};\n{}{}{}",
1138 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1139 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1148 MATCH_SINGLE_BINDING,
1150 "this match could be written as a `let` statement",
1151 "consider using `let` statement",
1157 if ex.can_have_side_effects() {
1158 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1161 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1167 MATCH_SINGLE_BINDING,
1169 "this match could be replaced by its scrutinee and body",
1170 "consider using the scrutinee and body instead",
1177 MATCH_SINGLE_BINDING,
1179 "this match could be replaced by its body itself",
1180 "consider using the match body instead",
1182 Applicability::MachineApplicable,
1190 /// Returns true if the `ex` match expression is in a local (`let`) statement
1191 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1192 let map = &cx.tcx.hir();
1194 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1195 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1197 return Some(parent_let_expr);
1203 // Checks if arm has the form `None => None`
1204 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1205 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1208 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1209 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1211 if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1212 if is_lang_ctor(cx, qpath, OptionSome);
1213 if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1214 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1215 if let ExprKind::Call(e, args) = peel_blocks(arm.body).kind;
1216 if let ExprKind::Path(ref some_path) = e.kind;
1217 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1218 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1219 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1227 fn has_multiple_ref_pats<'a, 'b, I>(pats: I) -> bool
1230 I: Iterator<Item = &'a Pat<'b>>,
1232 let mut ref_count = 0;
1233 for opt in pats.map(|pat| match pat.kind {
1234 PatKind::Ref(..) => Some(true), // &-patterns
1235 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1236 _ => None, // any other pattern is not fine
1238 if let Some(inner) = opt {