1 use clippy_utils::consts::{constant, constant_full_int, miri_to_const, FullInt};
2 use clippy_utils::diagnostics::{
3 multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
5 use clippy_utils::macros::{is_panic, root_macro_call};
6 use clippy_utils::peel_blocks_with_stmt;
7 use clippy_utils::source::{indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
8 use clippy_utils::sugg::Sugg;
9 use clippy_utils::ty::is_type_diagnostic_item;
10 use clippy_utils::visitors::is_local_used;
12 get_parent_expr, is_lang_ctor, is_refutable, is_wild, meets_msrv, msrvs, path_to_local_id, peel_blocks,
13 peel_hir_pat_refs, recurse_or_patterns, strip_pat_refs,
16 use if_chain::if_chain;
17 use rustc_errors::Applicability;
18 use rustc_hir::def::{CtorKind, DefKind, Res};
19 use rustc_hir::LangItem::{OptionNone, OptionSome};
21 self as hir, Arm, BindingAnnotation, BorrowKind, Expr, ExprKind, Local, MatchSource, Mutability, Node, Pat,
22 PatKind, PathSegment, QPath, RangeEnd, TyKind,
24 use rustc_lint::{LateContext, LateLintPass};
25 use rustc_middle::ty::{self, Ty, VariantDef};
26 use rustc_semver::RustcVersion;
27 use rustc_session::{declare_tool_lint, impl_lint_pass};
28 use rustc_span::{sym, symbol::kw, Span};
29 use std::cmp::Ordering;
32 mod match_like_matches;
34 mod redundant_pattern_match;
37 declare_clippy_lint! {
39 /// Checks for matches with a single arm where an `if let`
40 /// will usually suffice.
42 /// ### Why is this bad?
43 /// Just readability – `if let` nests less than a `match`.
47 /// # fn bar(stool: &str) {}
48 /// # let x = Some("abc");
51 /// Some(ref foo) => bar(foo),
56 /// if let Some(ref foo) = x {
60 #[clippy::version = "pre 1.29.0"]
63 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
66 declare_clippy_lint! {
68 /// Checks for matches with two arms where an `if let else` will
71 /// ### Why is this bad?
72 /// Just readability – `if let` nests less than a `match`.
74 /// ### Known problems
75 /// Personal style preferences may differ.
81 /// # fn bar(foo: &usize) {}
82 /// # let other_ref: usize = 1;
83 /// # let x: Option<&usize> = Some(&1);
85 /// Some(ref foo) => bar(foo),
86 /// _ => bar(&other_ref),
90 /// Using `if let` with `else`:
93 /// # fn bar(foo: &usize) {}
94 /// # let other_ref: usize = 1;
95 /// # let x: Option<&usize> = Some(&1);
96 /// if let Some(ref foo) = x {
102 #[clippy::version = "pre 1.29.0"]
103 pub SINGLE_MATCH_ELSE,
105 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
108 declare_clippy_lint! {
110 /// Checks for matches where all arms match a reference,
111 /// suggesting to remove the reference and deref the matched expression
112 /// instead. It also checks for `if let &foo = bar` blocks.
114 /// ### Why is this bad?
115 /// It just makes the code less readable. That reference
116 /// destructuring adds nothing to the code.
122 /// &A(ref y) => foo(y),
129 /// A(ref y) => foo(y),
134 #[clippy::version = "pre 1.29.0"]
137 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
140 declare_clippy_lint! {
142 /// Checks for matches where match expression is a `bool`. It
143 /// suggests to replace the expression with an `if...else` block.
145 /// ### Why is this bad?
146 /// It makes the code less readable.
152 /// let condition: bool = true;
153 /// match condition {
158 /// Use if/else instead:
162 /// let condition: bool = true;
169 #[clippy::version = "pre 1.29.0"]
172 "a `match` on a boolean expression instead of an `if..else` block"
175 declare_clippy_lint! {
177 /// Checks for overlapping match arms.
179 /// ### Why is this bad?
180 /// It is likely to be an error and if not, makes the code
187 /// 1..=10 => println!("1 ... 10"),
188 /// 5..=15 => println!("5 ... 15"),
192 #[clippy::version = "pre 1.29.0"]
193 pub MATCH_OVERLAPPING_ARM,
195 "a `match` with overlapping arms"
198 declare_clippy_lint! {
200 /// Checks for arm which matches all errors with `Err(_)`
201 /// and take drastic actions like `panic!`.
203 /// ### Why is this bad?
204 /// It is generally a bad practice, similar to
205 /// catching all exceptions in java with `catch(Exception)`
209 /// let x: Result<i32, &str> = Ok(3);
211 /// Ok(_) => println!("ok"),
212 /// Err(_) => panic!("err"),
215 #[clippy::version = "pre 1.29.0"]
216 pub MATCH_WILD_ERR_ARM,
218 "a `match` with `Err(_)` arm and take drastic actions"
221 declare_clippy_lint! {
223 /// Checks for match which is used to add a reference to an
226 /// ### Why is this bad?
227 /// Using `as_ref()` or `as_mut()` instead is shorter.
231 /// let x: Option<()> = None;
234 /// let r: Option<&()> = match x {
236 /// Some(ref v) => Some(v),
240 /// let r: Option<&()> = x.as_ref();
242 #[clippy::version = "pre 1.29.0"]
245 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
248 declare_clippy_lint! {
250 /// Checks for wildcard enum matches using `_`.
252 /// ### Why is this bad?
253 /// New enum variants added by library updates can be missed.
255 /// ### Known problems
256 /// Suggested replacements may be incorrect if guards exhaustively cover some
257 /// variants, and also may not use correct path to enum if it's not present in the current scope.
261 /// # enum Foo { A(usize), B(usize) }
262 /// # let x = Foo::B(1);
275 #[clippy::version = "1.34.0"]
276 pub WILDCARD_ENUM_MATCH_ARM,
278 "a wildcard enum match arm using `_`"
281 declare_clippy_lint! {
283 /// Checks for wildcard enum matches for a single variant.
285 /// ### Why is this bad?
286 /// New enum variants added by library updates can be missed.
288 /// ### Known problems
289 /// Suggested replacements may not use correct path to enum
290 /// if it's not present in the current scope.
294 /// # enum Foo { A, B, C }
295 /// # let x = Foo::B;
310 #[clippy::version = "1.45.0"]
311 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
313 "a wildcard enum match for a single variant"
316 declare_clippy_lint! {
318 /// Checks for wildcard pattern used with others patterns in same match arm.
320 /// ### Why is this bad?
321 /// Wildcard pattern already covers any other pattern as it will match anyway.
322 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
338 #[clippy::version = "1.42.0"]
339 pub WILDCARD_IN_OR_PATTERNS,
341 "a wildcard pattern used with others patterns in same match arm"
344 declare_clippy_lint! {
346 /// Checks for matches being used to destructure a single-variant enum
347 /// or tuple struct where a `let` will suffice.
349 /// ### Why is this bad?
350 /// Just readability – `let` doesn't nest, whereas a `match` does.
358 /// let wrapper = Wrapper::Data(42);
360 /// let data = match wrapper {
361 /// Wrapper::Data(i) => i,
365 /// The correct use would be:
371 /// let wrapper = Wrapper::Data(42);
372 /// let Wrapper::Data(data) = wrapper;
374 #[clippy::version = "pre 1.29.0"]
375 pub INFALLIBLE_DESTRUCTURING_MATCH,
377 "a `match` statement with a single infallible arm instead of a `let`"
380 declare_clippy_lint! {
382 /// Checks for useless match that binds to only one value.
384 /// ### Why is this bad?
385 /// Readability and needless complexity.
387 /// ### Known problems
388 /// Suggested replacements may be incorrect when `match`
389 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
404 /// let (c, d) = (a, b);
406 #[clippy::version = "1.43.0"]
407 pub MATCH_SINGLE_BINDING,
409 "a match with a single binding instead of using `let` statement"
412 declare_clippy_lint! {
414 /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
416 /// ### Why is this bad?
417 /// Correctness and readability. It's like having a wildcard pattern after
418 /// matching all enum variants explicitly.
422 /// # struct A { a: i32 }
423 /// let a = A { a: 5 };
427 /// A { a: 5, .. } => {},
433 /// A { a: 5 } => {},
437 #[clippy::version = "1.43.0"]
438 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
440 "a match on a struct that binds all fields but still uses the wildcard pattern"
443 declare_clippy_lint! {
445 /// Lint for redundant pattern matching over `Result`, `Option`,
446 /// `std::task::Poll` or `std::net::IpAddr`
448 /// ### Why is this bad?
449 /// It's more concise and clear to just use the proper
452 /// ### Known problems
453 /// This will change the drop order for the matched type. Both `if let` and
454 /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
455 /// value before entering the block. For most types this change will not matter, but for a few
456 /// types this will not be an acceptable change (e.g. locks). See the
457 /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
462 /// # use std::task::Poll;
463 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
464 /// if let Ok(_) = Ok::<i32, i32>(42) {}
465 /// if let Err(_) = Err::<i32, i32>(42) {}
466 /// if let None = None::<()> {}
467 /// if let Some(_) = Some(42) {}
468 /// if let Poll::Pending = Poll::Pending::<()> {}
469 /// if let Poll::Ready(_) = Poll::Ready(42) {}
470 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
471 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
472 /// match Ok::<i32, i32>(42) {
478 /// The more idiomatic use would be:
481 /// # use std::task::Poll;
482 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
483 /// if Ok::<i32, i32>(42).is_ok() {}
484 /// if Err::<i32, i32>(42).is_err() {}
485 /// if None::<()>.is_none() {}
486 /// if Some(42).is_some() {}
487 /// if Poll::Pending::<()>.is_pending() {}
488 /// if Poll::Ready(42).is_ready() {}
489 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
490 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
491 /// Ok::<i32, i32>(42).is_ok();
493 #[clippy::version = "1.31.0"]
494 pub REDUNDANT_PATTERN_MATCHING,
496 "use the proper utility function avoiding an `if let`"
499 declare_clippy_lint! {
501 /// Checks for `match` or `if let` expressions producing a
502 /// `bool` that could be written using `matches!`
504 /// ### Why is this bad?
505 /// Readability and needless complexity.
507 /// ### Known problems
508 /// This lint falsely triggers, if there are arms with
509 /// `cfg` attributes that remove an arm evaluating to `false`.
516 /// let a = match x {
521 /// let a = if let Some(0) = x {
528 /// let a = matches!(x, Some(0));
530 #[clippy::version = "1.47.0"]
531 pub MATCH_LIKE_MATCHES_MACRO,
533 "a match that could be written with the matches! macro"
536 declare_clippy_lint! {
538 /// Checks for `match` with identical arm bodies.
540 /// ### Why is this bad?
541 /// This is probably a copy & paste error. If arm bodies
542 /// are the same on purpose, you can factor them
543 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
545 /// ### Known problems
546 /// False positive possible with order dependent `match`
548 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
555 /// Baz => bar(), // <= oops
559 /// This should probably be
564 /// Baz => baz(), // <= fixed
568 /// or if the original code was not a typo:
571 /// Bar | Baz => bar(), // <= shows the intent better
575 #[clippy::version = "pre 1.29.0"]
578 "`match` with identical arm bodies"
583 msrv: Option<RustcVersion>,
584 infallible_destructuring_match_linted: bool,
589 pub fn new(msrv: Option<RustcVersion>) -> Self {
597 impl_lint_pass!(Matches => [
602 MATCH_OVERLAPPING_ARM,
605 WILDCARD_ENUM_MATCH_ARM,
606 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
607 WILDCARD_IN_OR_PATTERNS,
608 MATCH_SINGLE_BINDING,
609 INFALLIBLE_DESTRUCTURING_MATCH,
610 REST_PAT_IN_FULLY_BOUND_STRUCTS,
611 REDUNDANT_PATTERN_MATCHING,
612 MATCH_LIKE_MATCHES_MACRO,
616 impl<'tcx> LateLintPass<'tcx> for Matches {
617 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
618 if expr.span.from_expansion() {
622 redundant_pattern_match::check(cx, expr);
624 if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
625 if !match_like_matches::check(cx, expr) {
626 match_same_arms::check(cx, expr);
629 match_same_arms::check(cx, expr);
632 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
633 single_match::check(cx, ex, arms, expr);
634 match_bool::check(cx, ex, arms, expr);
635 check_overlapping_arms(cx, ex, arms);
636 check_wild_err_arm(cx, ex, arms);
637 check_wild_enum_match(cx, ex, arms);
638 check_match_as_ref(cx, ex, arms, expr);
639 check_wild_in_or_pats(cx, arms);
641 if self.infallible_destructuring_match_linted {
642 self.infallible_destructuring_match_linted = false;
644 check_match_single_binding(cx, ex, arms, expr);
647 if let ExprKind::Match(ex, arms, _) = expr.kind {
648 check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
652 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
654 if !local.span.from_expansion();
655 if let Some(expr) = local.init;
656 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
657 if arms.len() == 1 && arms[0].guard.is_none();
658 if let PatKind::TupleStruct(
659 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
661 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
662 let body = peel_blocks(arms[0].body);
663 if path_to_local_id(body, arg);
666 let mut applicability = Applicability::MachineApplicable;
667 self.infallible_destructuring_match_linted = true;
670 INFALLIBLE_DESTRUCTURING_MATCH,
672 "you seem to be trying to use `match` to destructure a single infallible pattern. \
673 Consider using `let`",
677 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
678 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
679 snippet_with_applicability(cx, target.span, "..", &mut applicability),
687 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
689 if !pat.span.from_expansion();
690 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
691 if let Some(def_id) = path.res.opt_def_id();
692 let ty = cx.tcx.type_of(def_id);
693 if let ty::Adt(def, _) = ty.kind();
694 if def.is_struct() || def.is_union();
695 if fields.len() == def.non_enum_variant().fields.len();
700 REST_PAT_IN_FULLY_BOUND_STRUCTS,
702 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
704 "consider removing `..` from this binding",
710 extract_msrv_attr!(LateContext);
713 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
714 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
715 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
716 if !ranges.is_empty() {
717 if let Some((start, end)) = overlapping(&ranges) {
720 MATCH_OVERLAPPING_ARM,
722 "some ranges overlap",
724 "overlaps with this",
731 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
732 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
733 if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
735 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
736 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
737 if path_str == "Err" {
738 let mut matching_wild = inner.iter().any(is_wild);
739 let mut ident_bind_name = kw::Underscore;
741 // Looking for unused bindings (i.e.: `_e`)
742 for pat in inner.iter() {
743 if let PatKind::Binding(_, id, ident, None) = pat.kind {
744 if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
745 ident_bind_name = ident.name;
746 matching_wild = true;
753 if let Some(macro_call) = root_macro_call(peel_blocks_with_stmt(arm.body).span);
754 if is_panic(cx, macro_call.def_id);
756 // `Err(_)` or `Err(_e)` arm with `panic!` found
757 span_lint_and_note(cx,
760 &format!("`Err({})` matches all errors", ident_bind_name),
762 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
772 enum CommonPrefixSearcher<'a> {
774 Path(&'a [PathSegment<'a>]),
777 impl<'a> CommonPrefixSearcher<'a> {
778 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
780 [path @ .., _] => self.with_prefix(path),
785 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
787 Self::None => *self = Self::Path(path),
788 Self::Path(self_path)
791 .map(|p| p.ident.name)
792 .eq(self_path.iter().map(|p| p.ident.name)) => {},
793 Self::Path(_) => *self = Self::Mixed,
799 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
800 let attrs = cx.tcx.get_attrs(variant_def.def_id);
801 clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
804 #[allow(clippy::too_many_lines)]
805 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
806 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
807 let adt_def = match ty.kind() {
810 && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
817 // First pass - check for violation, but don't do much book-keeping because this is hopefully
818 // the uncommon case, and the book-keeping is slightly expensive.
819 let mut wildcard_span = None;
820 let mut wildcard_ident = None;
821 let mut has_non_wild = false;
823 match peel_hir_pat_refs(arm.pat).0.kind {
824 PatKind::Wild => wildcard_span = Some(arm.pat.span),
825 PatKind::Binding(_, _, ident, None) => {
826 wildcard_span = Some(arm.pat.span);
827 wildcard_ident = Some(ident);
829 _ => has_non_wild = true,
832 let wildcard_span = match wildcard_span {
833 Some(x) if has_non_wild => x,
837 // Accumulate the variants which should be put in place of the wildcard because they're not
839 let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
840 let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
842 let mut path_prefix = CommonPrefixSearcher::None;
844 // Guards mean that this case probably isn't exhaustively covered. Technically
845 // this is incorrect, as we should really check whether each variant is exhaustively
846 // covered by the set of guards that cover it, but that's really hard to do.
847 recurse_or_patterns(arm.pat, |pat| {
848 let path = match &peel_hir_pat_refs(pat).0.kind {
849 PatKind::Path(path) => {
850 #[allow(clippy::match_same_arms)]
851 let id = match cx.qpath_res(path, pat.hir_id) {
853 DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
856 Res::Def(_, id) => id,
859 if arm.guard.is_none() {
860 missing_variants.retain(|e| e.ctor_def_id != Some(id));
864 PatKind::TupleStruct(path, patterns, ..) => {
865 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
866 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
867 missing_variants.retain(|e| e.ctor_def_id != Some(id));
872 PatKind::Struct(path, patterns, ..) => {
873 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
874 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
875 missing_variants.retain(|e| e.def_id != id);
883 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
886 kind: TyKind::Path(QPath::Resolved(_, path)),
890 ) => path_prefix.with_prefix(path.segments),
896 let format_suggestion = |variant: &VariantDef| {
899 if let Some(ident) = wildcard_ident {
900 format!("{} @ ", ident.name)
904 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
905 let mut s = String::new();
906 for seg in path_prefix {
907 s.push_str(seg.ident.as_str());
912 let mut s = cx.tcx.def_path_str(adt_def.did);
917 match variant.ctor_kind {
918 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
919 CtorKind::Fn => "(..)",
920 CtorKind::Const => "",
921 CtorKind::Fictive => "{ .. }",
926 match missing_variants.as_slice() {
928 [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
930 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
932 "wildcard matches only a single variant and will also match any future added variants",
934 format_suggestion(x),
935 Applicability::MaybeIncorrect,
938 let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
939 let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
940 suggestions.push("_".into());
941 "wildcard matches known variants and will also match future added variants"
943 "wildcard match will also match any future added variants"
948 WILDCARD_ENUM_MATCH_ARM,
952 suggestions.join(" | "),
953 Applicability::MaybeIncorrect,
959 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
962 I: Clone + Iterator<Item = &'a Pat<'b>>,
964 if !has_multiple_ref_pats(pats.clone()) {
968 let (first_sugg, msg, title);
969 let span = ex.span.source_callsite();
970 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
971 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
973 title = "you don't need to add `&` to both the expression and the patterns";
975 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
976 msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
977 title = "you don't need to add `&` to all patterns";
980 let remaining_suggs = pats.filter_map(|pat| {
981 if let PatKind::Ref(refp, _) = pat.kind {
982 Some((pat.span, snippet(cx, refp.span, "..").to_string()))
988 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
989 if !expr.span.from_expansion() {
990 multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
995 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
996 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
997 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
998 is_ref_some_arm(cx, &arms[1])
999 } else if is_none_arm(cx, &arms[1]) {
1000 is_ref_some_arm(cx, &arms[0])
1004 if let Some(rb) = arm_ref {
1005 let suggestion = if rb == BindingAnnotation::Ref {
1011 let output_ty = cx.typeck_results().expr_ty(expr);
1012 let input_ty = cx.typeck_results().expr_ty(ex);
1014 let cast = if_chain! {
1015 if let ty::Adt(_, substs) = input_ty.kind();
1016 let input_ty = substs.type_at(0);
1017 if let ty::Adt(_, substs) = output_ty.kind();
1018 let output_ty = substs.type_at(0);
1019 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1020 if input_ty != output_ty;
1028 let mut applicability = Applicability::MachineApplicable;
1033 &format!("use `{}()` instead", suggestion),
1037 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1047 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1049 if let PatKind::Or(fields) = arm.pat.kind {
1050 // look for multiple fields in this arm that contains at least one Wild pattern
1051 if fields.len() > 1 && fields.iter().any(is_wild) {
1054 WILDCARD_IN_OR_PATTERNS,
1056 "wildcard pattern covers any other pattern as it will match anyway",
1058 "consider handling `_` separately",
1065 #[allow(clippy::too_many_lines)]
1066 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1067 if expr.span.from_expansion() || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1072 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1073 // to prevent false positives as there is currently no better way to detect if code was excluded by
1074 // a macro. See PR #6435
1076 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1077 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1078 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1079 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1080 if rest_snippet.contains("=>");
1082 // The code it self contains another thick arrow "=>"
1083 // -> Either another arm or a comment
1088 let matched_vars = ex.span;
1089 let bind_names = arms[0].pat.span;
1090 let match_body = peel_blocks(arms[0].body);
1091 let mut snippet_body = if match_body.span.from_expansion() {
1092 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1094 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1097 // Do we need to add ';' to suggestion ?
1098 match match_body.kind {
1099 ExprKind::Block(block, _) => {
1100 // macro + expr_ty(body) == ()
1101 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1102 snippet_body.push(';');
1106 // expr_ty(body) == ()
1107 if cx.typeck_results().expr_ty(match_body).is_unit() {
1108 snippet_body.push(';');
1113 let mut applicability = Applicability::MaybeIncorrect;
1114 match arms[0].pat.kind {
1115 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1116 // If this match is in a local (`let`) stmt
1117 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1119 parent_let_node.span,
1121 "let {} = {};\n{}let {} = {};",
1122 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1123 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1124 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1125 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1130 // If we are in closure, we need curly braces around suggestion
1131 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1132 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1133 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1134 if let ExprKind::Closure(..) = parent_expr.kind {
1135 cbrace_end = format!("\n{}}}", indent);
1136 // Fix body indent due to the closure
1137 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1138 cbrace_start = format!("{{\n{}", indent);
1141 // If the parent is already an arm, and the body is another match statement,
1142 // we need curly braces around suggestion
1143 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1144 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1145 if let ExprKind::Match(..) = arm.body.kind {
1146 cbrace_end = format!("\n{}}}", indent);
1147 // Fix body indent due to the match
1148 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1149 cbrace_start = format!("{{\n{}", indent);
1155 "{}let {} = {};\n{}{}{}",
1157 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1158 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1167 MATCH_SINGLE_BINDING,
1169 "this match could be written as a `let` statement",
1170 "consider using `let` statement",
1176 if ex.can_have_side_effects() {
1177 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1180 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1186 MATCH_SINGLE_BINDING,
1188 "this match could be replaced by its scrutinee and body",
1189 "consider using the scrutinee and body instead",
1196 MATCH_SINGLE_BINDING,
1198 "this match could be replaced by its body itself",
1199 "consider using the match body instead",
1201 Applicability::MachineApplicable,
1209 /// Returns true if the `ex` match expression is in a local (`let`) statement
1210 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1211 let map = &cx.tcx.hir();
1213 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1214 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1216 return Some(parent_let_expr);
1222 /// Gets the ranges for each range pattern arm. Applies `ty` bounds for open ranges.
1223 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<FullInt>> {
1226 if let Arm { pat, guard: None, .. } = *arm {
1227 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1228 let lhs_const = match lhs {
1229 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1230 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1232 let rhs_const = match rhs {
1233 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1234 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1237 let lhs_val = lhs_const.int_value(cx, ty)?;
1238 let rhs_val = rhs_const.int_value(cx, ty)?;
1240 let rhs_bound = match range_end {
1241 RangeEnd::Included => EndBound::Included(rhs_val),
1242 RangeEnd::Excluded => EndBound::Excluded(rhs_val),
1244 return Some(SpannedRange {
1246 node: (lhs_val, rhs_bound),
1250 if let PatKind::Lit(value) = pat.kind {
1251 let value = constant_full_int(cx, cx.typeck_results(), value)?;
1252 return Some(SpannedRange {
1254 node: (value, EndBound::Included(value)),
1263 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1264 pub enum EndBound<T> {
1269 #[derive(Debug, Eq, PartialEq)]
1270 struct SpannedRange<T> {
1272 pub node: (T, EndBound<T>),
1275 // Checks if arm has the form `None => None`
1276 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1277 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1280 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1281 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1283 if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1284 if is_lang_ctor(cx, qpath, OptionSome);
1285 if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1286 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1287 if let ExprKind::Call(e, args) = peel_blocks(arm.body).kind;
1288 if let ExprKind::Path(ref some_path) = e.kind;
1289 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1290 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1291 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1299 fn has_multiple_ref_pats<'a, 'b, I>(pats: I) -> bool
1302 I: Iterator<Item = &'a Pat<'b>>,
1304 let mut ref_count = 0;
1305 for opt in pats.map(|pat| match pat.kind {
1306 PatKind::Ref(..) => Some(true), // &-patterns
1307 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1308 _ => None, // any other pattern is not fine
1310 if let Some(inner) = opt {
1321 fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1325 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1332 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1333 struct RangeBound<'a, T>(T, BoundKind, &'a SpannedRange<T>);
1335 impl<'a, T: Copy + Ord> PartialOrd for RangeBound<'a, T> {
1336 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1337 Some(self.cmp(other))
1341 impl<'a, T: Copy + Ord> Ord for RangeBound<'a, T> {
1342 fn cmp(&self, RangeBound(other_value, other_kind, _): &Self) -> Ordering {
1343 let RangeBound(self_value, self_kind, _) = *self;
1344 (self_value, self_kind).cmp(&(*other_value, *other_kind))
1348 let mut values = Vec::with_capacity(2 * ranges.len());
1350 for r @ SpannedRange { node: (start, end), .. } in ranges {
1351 values.push(RangeBound(*start, BoundKind::Start, r));
1352 values.push(match end {
1353 EndBound::Excluded(val) => RangeBound(*val, BoundKind::EndExcluded, r),
1354 EndBound::Included(val) => RangeBound(*val, BoundKind::EndIncluded, r),
1360 let mut started = vec![];
1362 for RangeBound(_, kind, range) in values {
1364 BoundKind::Start => started.push(range),
1365 BoundKind::EndExcluded | BoundKind::EndIncluded => {
1366 let mut overlap = None;
1368 while let Some(last_started) = started.pop() {
1369 if last_started == range {
1372 overlap = Some(last_started);
1375 if let Some(first_overlapping) = overlap {
1376 return Some((range, first_overlapping));
1386 fn test_overlapping() {
1387 use rustc_span::source_map::DUMMY_SP;
1389 let sp = |s, e| SpannedRange {
1394 assert_eq!(None, overlapping::<u8>(&[]));
1395 assert_eq!(None, overlapping(&[sp(1, EndBound::Included(4))]));
1398 overlapping(&[sp(1, EndBound::Included(4)), sp(5, EndBound::Included(6))])
1403 sp(1, EndBound::Included(4)),
1404 sp(5, EndBound::Included(6)),
1405 sp(10, EndBound::Included(11))
1409 Some((&sp(1, EndBound::Included(4)), &sp(3, EndBound::Included(6)))),
1410 overlapping(&[sp(1, EndBound::Included(4)), sp(3, EndBound::Included(6))])
1413 Some((&sp(5, EndBound::Included(6)), &sp(6, EndBound::Included(11)))),
1415 sp(1, EndBound::Included(4)),
1416 sp(5, EndBound::Included(6)),
1417 sp(6, EndBound::Included(11))