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::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
8 use clippy_utils::sugg::Sugg;
9 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
10 use clippy_utils::visitors::is_local_used;
12 get_parent_expr, is_lang_ctor, is_lint_allowed, is_refutable, is_unit_expr, is_wild, meets_msrv, msrvs,
13 path_to_local, path_to_local_id, peel_blocks, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns,
16 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
18 use if_chain::if_chain;
19 use rustc_ast::ast::LitKind;
20 use rustc_errors::Applicability;
21 use rustc_hir::def::{CtorKind, DefKind, Res};
22 use rustc_hir::LangItem::{OptionNone, OptionSome};
24 self as hir, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, HirId, Local, MatchSource, Mutability,
25 Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
27 use rustc_hir::{HirIdMap, HirIdSet};
28 use rustc_lint::{LateContext, LateLintPass};
29 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
30 use rustc_semver::RustcVersion;
31 use rustc_session::{declare_tool_lint, impl_lint_pass};
32 use rustc_span::{sym, symbol::kw, Span};
33 use std::cmp::{max, Ordering};
34 use std::collections::hash_map::Entry;
36 mod match_like_matches;
38 declare_clippy_lint! {
40 /// Checks for matches with a single arm where an `if let`
41 /// will usually suffice.
43 /// ### Why is this bad?
44 /// Just readability – `if let` nests less than a `match`.
48 /// # fn bar(stool: &str) {}
49 /// # let x = Some("abc");
52 /// Some(ref foo) => bar(foo),
57 /// if let Some(ref foo) = x {
61 #[clippy::version = "pre 1.29.0"]
64 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
67 declare_clippy_lint! {
69 /// Checks for matches with two arms where an `if let else` will
72 /// ### Why is this bad?
73 /// Just readability – `if let` nests less than a `match`.
75 /// ### Known problems
76 /// Personal style preferences may differ.
82 /// # fn bar(foo: &usize) {}
83 /// # let other_ref: usize = 1;
84 /// # let x: Option<&usize> = Some(&1);
86 /// Some(ref foo) => bar(foo),
87 /// _ => bar(&other_ref),
91 /// Using `if let` with `else`:
94 /// # fn bar(foo: &usize) {}
95 /// # let other_ref: usize = 1;
96 /// # let x: Option<&usize> = Some(&1);
97 /// if let Some(ref foo) = x {
103 #[clippy::version = "pre 1.29.0"]
104 pub SINGLE_MATCH_ELSE,
106 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
109 declare_clippy_lint! {
111 /// Checks for matches where all arms match a reference,
112 /// suggesting to remove the reference and deref the matched expression
113 /// instead. It also checks for `if let &foo = bar` blocks.
115 /// ### Why is this bad?
116 /// It just makes the code less readable. That reference
117 /// destructuring adds nothing to the code.
123 /// &A(ref y) => foo(y),
130 /// A(ref y) => foo(y),
135 #[clippy::version = "pre 1.29.0"]
138 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
141 declare_clippy_lint! {
143 /// Checks for matches where match expression is a `bool`. It
144 /// suggests to replace the expression with an `if...else` block.
146 /// ### Why is this bad?
147 /// It makes the code less readable.
153 /// let condition: bool = true;
154 /// match condition {
159 /// Use if/else instead:
163 /// let condition: bool = true;
170 #[clippy::version = "pre 1.29.0"]
173 "a `match` on a boolean expression instead of an `if..else` block"
176 declare_clippy_lint! {
178 /// Checks for overlapping match arms.
180 /// ### Why is this bad?
181 /// It is likely to be an error and if not, makes the code
188 /// 1..=10 => println!("1 ... 10"),
189 /// 5..=15 => println!("5 ... 15"),
193 #[clippy::version = "pre 1.29.0"]
194 pub MATCH_OVERLAPPING_ARM,
196 "a `match` with overlapping arms"
199 declare_clippy_lint! {
201 /// Checks for arm which matches all errors with `Err(_)`
202 /// and take drastic actions like `panic!`.
204 /// ### Why is this bad?
205 /// It is generally a bad practice, similar to
206 /// catching all exceptions in java with `catch(Exception)`
210 /// let x: Result<i32, &str> = Ok(3);
212 /// Ok(_) => println!("ok"),
213 /// Err(_) => panic!("err"),
216 #[clippy::version = "pre 1.29.0"]
217 pub MATCH_WILD_ERR_ARM,
219 "a `match` with `Err(_)` arm and take drastic actions"
222 declare_clippy_lint! {
224 /// Checks for match which is used to add a reference to an
227 /// ### Why is this bad?
228 /// Using `as_ref()` or `as_mut()` instead is shorter.
232 /// let x: Option<()> = None;
235 /// let r: Option<&()> = match x {
237 /// Some(ref v) => Some(v),
241 /// let r: Option<&()> = x.as_ref();
243 #[clippy::version = "pre 1.29.0"]
246 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
249 declare_clippy_lint! {
251 /// Checks for wildcard enum matches using `_`.
253 /// ### Why is this bad?
254 /// New enum variants added by library updates can be missed.
256 /// ### Known problems
257 /// Suggested replacements may be incorrect if guards exhaustively cover some
258 /// variants, and also may not use correct path to enum if it's not present in the current scope.
262 /// # enum Foo { A(usize), B(usize) }
263 /// # let x = Foo::B(1);
276 #[clippy::version = "1.34.0"]
277 pub WILDCARD_ENUM_MATCH_ARM,
279 "a wildcard enum match arm using `_`"
282 declare_clippy_lint! {
284 /// Checks for wildcard enum matches for a single variant.
286 /// ### Why is this bad?
287 /// New enum variants added by library updates can be missed.
289 /// ### Known problems
290 /// Suggested replacements may not use correct path to enum
291 /// if it's not present in the current scope.
295 /// # enum Foo { A, B, C }
296 /// # let x = Foo::B;
311 #[clippy::version = "1.45.0"]
312 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
314 "a wildcard enum match for a single variant"
317 declare_clippy_lint! {
319 /// Checks for wildcard pattern used with others patterns in same match arm.
321 /// ### Why is this bad?
322 /// Wildcard pattern already covers any other pattern as it will match anyway.
323 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
339 #[clippy::version = "1.42.0"]
340 pub WILDCARD_IN_OR_PATTERNS,
342 "a wildcard pattern used with others patterns in same match arm"
345 declare_clippy_lint! {
347 /// Checks for matches being used to destructure a single-variant enum
348 /// or tuple struct where a `let` will suffice.
350 /// ### Why is this bad?
351 /// Just readability – `let` doesn't nest, whereas a `match` does.
359 /// let wrapper = Wrapper::Data(42);
361 /// let data = match wrapper {
362 /// Wrapper::Data(i) => i,
366 /// The correct use would be:
372 /// let wrapper = Wrapper::Data(42);
373 /// let Wrapper::Data(data) = wrapper;
375 #[clippy::version = "pre 1.29.0"]
376 pub INFALLIBLE_DESTRUCTURING_MATCH,
378 "a `match` statement with a single infallible arm instead of a `let`"
381 declare_clippy_lint! {
383 /// Checks for useless match that binds to only one value.
385 /// ### Why is this bad?
386 /// Readability and needless complexity.
388 /// ### Known problems
389 /// Suggested replacements may be incorrect when `match`
390 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
405 /// let (c, d) = (a, b);
407 #[clippy::version = "1.43.0"]
408 pub MATCH_SINGLE_BINDING,
410 "a match with a single binding instead of using `let` statement"
413 declare_clippy_lint! {
415 /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
417 /// ### Why is this bad?
418 /// Correctness and readability. It's like having a wildcard pattern after
419 /// matching all enum variants explicitly.
423 /// # struct A { a: i32 }
424 /// let a = A { a: 5 };
428 /// A { a: 5, .. } => {},
434 /// A { a: 5 } => {},
438 #[clippy::version = "1.43.0"]
439 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
441 "a match on a struct that binds all fields but still uses the wildcard pattern"
444 declare_clippy_lint! {
446 /// Lint for redundant pattern matching over `Result`, `Option`,
447 /// `std::task::Poll` or `std::net::IpAddr`
449 /// ### Why is this bad?
450 /// It's more concise and clear to just use the proper
453 /// ### Known problems
454 /// This will change the drop order for the matched type. Both `if let` and
455 /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
456 /// value before entering the block. For most types this change will not matter, but for a few
457 /// types this will not be an acceptable change (e.g. locks). See the
458 /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
463 /// # use std::task::Poll;
464 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
465 /// if let Ok(_) = Ok::<i32, i32>(42) {}
466 /// if let Err(_) = Err::<i32, i32>(42) {}
467 /// if let None = None::<()> {}
468 /// if let Some(_) = Some(42) {}
469 /// if let Poll::Pending = Poll::Pending::<()> {}
470 /// if let Poll::Ready(_) = Poll::Ready(42) {}
471 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
472 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
473 /// match Ok::<i32, i32>(42) {
479 /// The more idiomatic use would be:
482 /// # use std::task::Poll;
483 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
484 /// if Ok::<i32, i32>(42).is_ok() {}
485 /// if Err::<i32, i32>(42).is_err() {}
486 /// if None::<()>.is_none() {}
487 /// if Some(42).is_some() {}
488 /// if Poll::Pending::<()>.is_pending() {}
489 /// if Poll::Ready(42).is_ready() {}
490 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
491 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
492 /// Ok::<i32, i32>(42).is_ok();
494 #[clippy::version = "1.31.0"]
495 pub REDUNDANT_PATTERN_MATCHING,
497 "use the proper utility function avoiding an `if let`"
500 declare_clippy_lint! {
502 /// Checks for `match` or `if let` expressions producing a
503 /// `bool` that could be written using `matches!`
505 /// ### Why is this bad?
506 /// Readability and needless complexity.
508 /// ### Known problems
509 /// This lint falsely triggers, if there are arms with
510 /// `cfg` attributes that remove an arm evaluating to `false`.
517 /// let a = match x {
522 /// let a = if let Some(0) = x {
529 /// let a = matches!(x, Some(0));
531 #[clippy::version = "1.47.0"]
532 pub MATCH_LIKE_MATCHES_MACRO,
534 "a match that could be written with the matches! macro"
537 declare_clippy_lint! {
539 /// Checks for `match` with identical arm bodies.
541 /// ### Why is this bad?
542 /// This is probably a copy & paste error. If arm bodies
543 /// are the same on purpose, you can factor them
544 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
546 /// ### Known problems
547 /// False positive possible with order dependent `match`
549 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
556 /// Baz => bar(), // <= oops
560 /// This should probably be
565 /// Baz => baz(), // <= fixed
569 /// or if the original code was not a typo:
572 /// Bar | Baz => bar(), // <= shows the intent better
576 #[clippy::version = "pre 1.29.0"]
579 "`match` with identical arm bodies"
584 msrv: Option<RustcVersion>,
585 infallible_destructuring_match_linted: bool,
590 pub fn new(msrv: Option<RustcVersion>) -> Self {
598 impl_lint_pass!(Matches => [
603 MATCH_OVERLAPPING_ARM,
606 WILDCARD_ENUM_MATCH_ARM,
607 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
608 WILDCARD_IN_OR_PATTERNS,
609 MATCH_SINGLE_BINDING,
610 INFALLIBLE_DESTRUCTURING_MATCH,
611 REST_PAT_IN_FULLY_BOUND_STRUCTS,
612 REDUNDANT_PATTERN_MATCHING,
613 MATCH_LIKE_MATCHES_MACRO,
617 impl<'tcx> LateLintPass<'tcx> for Matches {
618 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
619 if expr.span.from_expansion() {
623 redundant_pattern_match::check(cx, expr);
625 if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
626 if !match_like_matches::check(cx, expr) {
627 lint_match_arms(cx, expr);
630 lint_match_arms(cx, expr);
633 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
634 check_single_match(cx, ex, arms, expr);
635 check_match_bool(cx, ex, arms, expr);
636 check_overlapping_arms(cx, ex, arms);
637 check_wild_err_arm(cx, ex, arms);
638 check_wild_enum_match(cx, ex, arms);
639 check_match_as_ref(cx, ex, arms, expr);
640 check_wild_in_or_pats(cx, arms);
642 if self.infallible_destructuring_match_linted {
643 self.infallible_destructuring_match_linted = false;
645 check_match_single_binding(cx, ex, arms, expr);
648 if let ExprKind::Match(ex, arms, _) = expr.kind {
649 check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
653 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
655 if !local.span.from_expansion();
656 if let Some(expr) = local.init;
657 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
658 if arms.len() == 1 && arms[0].guard.is_none();
659 if let PatKind::TupleStruct(
660 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
662 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
663 let body = peel_blocks(arms[0].body);
664 if path_to_local_id(body, arg);
667 let mut applicability = Applicability::MachineApplicable;
668 self.infallible_destructuring_match_linted = true;
671 INFALLIBLE_DESTRUCTURING_MATCH,
673 "you seem to be trying to use `match` to destructure a single infallible pattern. \
674 Consider using `let`",
678 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
679 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
680 snippet_with_applicability(cx, target.span, "..", &mut applicability),
688 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
690 if !pat.span.from_expansion();
691 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
692 if let Some(def_id) = path.res.opt_def_id();
693 let ty = cx.tcx.type_of(def_id);
694 if let ty::Adt(def, _) = ty.kind();
695 if def.is_struct() || def.is_union();
696 if fields.len() == def.non_enum_variant().fields.len();
701 REST_PAT_IN_FULLY_BOUND_STRUCTS,
703 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
705 "consider removing `..` from this binding",
711 extract_msrv_attr!(LateContext);
715 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
716 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
717 if expr.span.from_expansion() {
718 // Don't lint match expressions present in
719 // macro_rules! block
722 if let PatKind::Or(..) = arms[0].pat.kind {
723 // don't lint for or patterns for now, this makes
724 // the lint noisy in unnecessary situations
727 let els = arms[1].body;
728 let els = if is_unit_expr(peel_blocks(els)) {
730 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
731 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
732 // single statement/expr "else" block, don't lint
735 // block with 2+ statements or 1 expr and 1+ statement
738 // not a block, don't lint
742 let ty = cx.typeck_results().expr_ty(ex);
743 if *ty.kind() != ty::Bool || is_lint_allowed(cx, MATCH_BOOL, ex.hir_id) {
744 check_single_match_single_pattern(cx, ex, arms, expr, els);
745 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
750 fn check_single_match_single_pattern(
751 cx: &LateContext<'_>,
755 els: Option<&Expr<'_>>,
757 if is_wild(arms[1].pat) {
758 report_single_match_single_pattern(cx, ex, arms, expr, els);
762 fn report_single_match_single_pattern(
763 cx: &LateContext<'_>,
767 els: Option<&Expr<'_>>,
769 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
770 let els_str = els.map_or(String::new(), |els| {
771 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
774 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
775 let (msg, sugg) = if_chain! {
776 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
777 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
778 if let Some(spe_trait_id) = cx.tcx.lang_items().structural_peq_trait();
779 if let Some(pe_trait_id) = cx.tcx.lang_items().eq_trait();
780 if ty.is_integral() || ty.is_char() || ty.is_str()
781 || (implements_trait(cx, ty, spe_trait_id, &[])
782 && implements_trait(cx, ty, pe_trait_id, &[ty.into()]));
784 // scrutinee derives PartialEq and the pattern is a constant.
785 let pat_ref_count = match pat.kind {
786 // string literals are already a reference.
787 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
790 // References are only implicitly added to the pattern, so no overflow here.
791 // e.g. will work: match &Some(_) { Some(_) => () }
792 // will not: match Some(_) { &Some(_) => () }
793 let ref_count_diff = ty_ref_count - pat_ref_count;
795 // Try to remove address of expressions first.
796 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
797 let ref_count_diff = ref_count_diff - removed;
799 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
801 "if {} == {}{} {}{}",
802 snippet(cx, ex.span, ".."),
803 // PartialEq for different reference counts may not exist.
804 "&".repeat(ref_count_diff),
805 snippet(cx, arms[0].pat.span, ".."),
806 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
811 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
813 "if let {} = {} {}{}",
814 snippet(cx, arms[0].pat.span, ".."),
815 snippet(cx, ex.span, ".."),
816 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
830 Applicability::HasPlaceholders,
834 fn check_single_match_opt_like<'a>(
835 cx: &LateContext<'a>,
840 els: Option<&Expr<'_>>,
842 // list of candidate `Enum`s we know will never get any more members
844 (&paths::COW, "Borrowed"),
845 (&paths::COW, "Cow::Borrowed"),
846 (&paths::COW, "Cow::Owned"),
847 (&paths::COW, "Owned"),
848 (&paths::OPTION, "None"),
849 (&paths::RESULT, "Err"),
850 (&paths::RESULT, "Ok"),
853 // We want to suggest to exclude an arm that contains only wildcards or forms the exhaustive
854 // match with the second branch, without enum variants in matches.
855 if !contains_only_wilds(arms[1].pat) && !form_exhaustive_matches(arms[0].pat, arms[1].pat) {
859 let mut paths_and_types = Vec::new();
860 if !collect_pat_paths(&mut paths_and_types, cx, arms[1].pat, ty) {
864 let in_candidate_enum = |path_info: &(String, &TyS<'_>)| -> bool {
865 let (path, ty) = path_info;
866 for &(ty_path, pat_path) in candidates {
867 if path == pat_path && match_type(cx, ty, ty_path) {
873 if paths_and_types.iter().all(in_candidate_enum) {
874 report_single_match_single_pattern(cx, ex, arms, expr, els);
878 /// Collects paths and their types from the given patterns. Returns true if the given pattern could
879 /// be simplified, false otherwise.
880 fn collect_pat_paths<'a>(acc: &mut Vec<(String, Ty<'a>)>, cx: &LateContext<'a>, pat: &Pat<'_>, ty: Ty<'a>) -> bool {
882 PatKind::Wild => true,
883 PatKind::Tuple(inner, _) => inner.iter().all(|p| {
884 let p_ty = cx.typeck_results().pat_ty(p);
885 collect_pat_paths(acc, cx, p, p_ty)
887 PatKind::TupleStruct(ref path, ..) => {
888 let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
889 s.print_qpath(path, false);
891 acc.push((path, ty));
894 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => {
895 acc.push((ident.to_string(), ty));
898 PatKind::Path(ref path) => {
899 let path = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| {
900 s.print_qpath(path, false);
902 acc.push((path, ty));
909 /// Returns true if the given arm of pattern matching contains wildcard patterns.
910 fn contains_only_wilds(pat: &Pat<'_>) -> bool {
912 PatKind::Wild => true,
913 PatKind::Tuple(inner, _) | PatKind::TupleStruct(_, inner, ..) => inner.iter().all(contains_only_wilds),
918 /// Returns true if the given patterns forms only exhaustive matches that don't contain enum
919 /// patterns without a wildcard.
920 fn form_exhaustive_matches(left: &Pat<'_>, right: &Pat<'_>) -> bool {
921 match (&left.kind, &right.kind) {
922 (PatKind::Wild, _) | (_, PatKind::Wild) => true,
923 (PatKind::Tuple(left_in, left_pos), PatKind::Tuple(right_in, right_pos)) => {
924 // We don't actually know the position and the presence of the `..` (dotdot) operator
925 // in the arms, so we need to evaluate the correct offsets here in order to iterate in
926 // both arms at the same time.
929 if left_pos.is_some() { 1 } else { 0 }
932 if right_pos.is_some() { 1 } else { 0 }
935 let mut left_pos = left_pos.unwrap_or(usize::MAX);
936 let mut right_pos = right_pos.unwrap_or(usize::MAX);
937 let mut left_dot_space = 0;
938 let mut right_dot_space = 0;
940 let mut found_dotdot = false;
943 if left_dot_space < len - left_in.len() {
949 right_dot_space += 1;
950 if right_dot_space < len - right_in.len() {
958 if !contains_only_wilds(&left_in[i - left_dot_space])
959 && !contains_only_wilds(&right_in[i - right_dot_space])
970 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
971 // Type of expression is `bool`.
972 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
977 "you seem to be trying to match on a boolean expression",
981 let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
982 if let ExprKind::Lit(ref lit) = arm_bool.kind {
984 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
985 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
995 if let Some((true_expr, false_expr)) = exprs {
996 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
997 (false, false) => Some(format!(
999 snippet(cx, ex.span, "b"),
1000 expr_block(cx, true_expr, None, "..", Some(expr.span)),
1001 expr_block(cx, false_expr, None, "..", Some(expr.span))
1003 (false, true) => Some(format!(
1005 snippet(cx, ex.span, "b"),
1006 expr_block(cx, true_expr, None, "..", Some(expr.span))
1009 let test = Sugg::hir(cx, ex, "..");
1013 expr_block(cx, false_expr, None, "..", Some(expr.span))
1016 (true, true) => None,
1019 if let Some(sugg) = sugg {
1020 diag.span_suggestion(
1022 "consider using an `if`/`else` expression",
1024 Applicability::HasPlaceholders,
1034 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
1035 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
1036 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
1037 if !ranges.is_empty() {
1038 if let Some((start, end)) = overlapping(&ranges) {
1041 MATCH_OVERLAPPING_ARM,
1043 "some ranges overlap",
1045 "overlaps with this",
1052 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
1053 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
1054 if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
1056 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
1057 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
1058 if path_str == "Err" {
1059 let mut matching_wild = inner.iter().any(is_wild);
1060 let mut ident_bind_name = kw::Underscore;
1062 // Looking for unused bindings (i.e.: `_e`)
1063 for pat in inner.iter() {
1064 if let PatKind::Binding(_, id, ident, None) = pat.kind {
1065 if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
1066 ident_bind_name = ident.name;
1067 matching_wild = true;
1074 if let Some(macro_call) = root_macro_call(peel_blocks_with_stmt(arm.body).span);
1075 if is_panic(cx, macro_call.def_id);
1077 // `Err(_)` or `Err(_e)` arm with `panic!` found
1078 span_lint_and_note(cx,
1081 &format!("`Err({})` matches all errors", ident_bind_name),
1083 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
1093 enum CommonPrefixSearcher<'a> {
1095 Path(&'a [PathSegment<'a>]),
1098 impl<'a> CommonPrefixSearcher<'a> {
1099 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
1101 [path @ .., _] => self.with_prefix(path),
1106 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
1108 Self::None => *self = Self::Path(path),
1109 Self::Path(self_path)
1112 .map(|p| p.ident.name)
1113 .eq(self_path.iter().map(|p| p.ident.name)) => {},
1114 Self::Path(_) => *self = Self::Mixed,
1120 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
1121 let attrs = cx.tcx.get_attrs(variant_def.def_id);
1122 clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
1125 #[allow(clippy::too_many_lines)]
1126 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
1127 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
1128 let adt_def = match ty.kind() {
1130 if adt_def.is_enum()
1131 && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
1138 // First pass - check for violation, but don't do much book-keeping because this is hopefully
1139 // the uncommon case, and the book-keeping is slightly expensive.
1140 let mut wildcard_span = None;
1141 let mut wildcard_ident = None;
1142 let mut has_non_wild = false;
1144 match peel_hir_pat_refs(arm.pat).0.kind {
1145 PatKind::Wild => wildcard_span = Some(arm.pat.span),
1146 PatKind::Binding(_, _, ident, None) => {
1147 wildcard_span = Some(arm.pat.span);
1148 wildcard_ident = Some(ident);
1150 _ => has_non_wild = true,
1153 let wildcard_span = match wildcard_span {
1154 Some(x) if has_non_wild => x,
1158 // Accumulate the variants which should be put in place of the wildcard because they're not
1160 let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
1161 let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
1163 let mut path_prefix = CommonPrefixSearcher::None;
1165 // Guards mean that this case probably isn't exhaustively covered. Technically
1166 // this is incorrect, as we should really check whether each variant is exhaustively
1167 // covered by the set of guards that cover it, but that's really hard to do.
1168 recurse_or_patterns(arm.pat, |pat| {
1169 let path = match &peel_hir_pat_refs(pat).0.kind {
1170 PatKind::Path(path) => {
1171 #[allow(clippy::match_same_arms)]
1172 let id = match cx.qpath_res(path, pat.hir_id) {
1174 DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
1177 Res::Def(_, id) => id,
1180 if arm.guard.is_none() {
1181 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1185 PatKind::TupleStruct(path, patterns, ..) => {
1186 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1187 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1188 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1193 PatKind::Struct(path, patterns, ..) => {
1194 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1195 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1196 missing_variants.retain(|e| e.def_id != id);
1204 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1205 QPath::TypeRelative(
1207 kind: TyKind::Path(QPath::Resolved(_, path)),
1211 ) => path_prefix.with_prefix(path.segments),
1217 let format_suggestion = |variant: &VariantDef| {
1220 if let Some(ident) = wildcard_ident {
1221 format!("{} @ ", ident.name)
1225 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1226 let mut s = String::new();
1227 for seg in path_prefix {
1228 s.push_str(seg.ident.as_str());
1233 let mut s = cx.tcx.def_path_str(adt_def.did);
1238 match variant.ctor_kind {
1239 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1240 CtorKind::Fn => "(..)",
1241 CtorKind::Const => "",
1242 CtorKind::Fictive => "{ .. }",
1247 match missing_variants.as_slice() {
1249 [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
1251 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1253 "wildcard matches only a single variant and will also match any future added variants",
1255 format_suggestion(x),
1256 Applicability::MaybeIncorrect,
1259 let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1260 let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
1261 suggestions.push("_".into());
1262 "wildcard matches known variants and will also match future added variants"
1264 "wildcard match will also match any future added variants"
1269 WILDCARD_ENUM_MATCH_ARM,
1273 suggestions.join(" | "),
1274 Applicability::MaybeIncorrect,
1280 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
1283 I: Clone + Iterator<Item = &'a Pat<'b>>,
1285 if !has_multiple_ref_pats(pats.clone()) {
1289 let (first_sugg, msg, title);
1290 let span = ex.span.source_callsite();
1291 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1292 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1294 title = "you don't need to add `&` to both the expression and the patterns";
1296 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1297 msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
1298 title = "you don't need to add `&` to all patterns";
1301 let remaining_suggs = pats.filter_map(|pat| {
1302 if let PatKind::Ref(refp, _) = pat.kind {
1303 Some((pat.span, snippet(cx, refp.span, "..").to_string()))
1309 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1310 if !expr.span.from_expansion() {
1311 multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
1316 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1317 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1318 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1319 is_ref_some_arm(cx, &arms[1])
1320 } else if is_none_arm(cx, &arms[1]) {
1321 is_ref_some_arm(cx, &arms[0])
1325 if let Some(rb) = arm_ref {
1326 let suggestion = if rb == BindingAnnotation::Ref {
1332 let output_ty = cx.typeck_results().expr_ty(expr);
1333 let input_ty = cx.typeck_results().expr_ty(ex);
1335 let cast = if_chain! {
1336 if let ty::Adt(_, substs) = input_ty.kind();
1337 let input_ty = substs.type_at(0);
1338 if let ty::Adt(_, substs) = output_ty.kind();
1339 let output_ty = substs.type_at(0);
1340 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1341 if input_ty != output_ty;
1349 let mut applicability = Applicability::MachineApplicable;
1354 &format!("use `{}()` instead", suggestion),
1358 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1368 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1370 if let PatKind::Or(fields) = arm.pat.kind {
1371 // look for multiple fields in this arm that contains at least one Wild pattern
1372 if fields.len() > 1 && fields.iter().any(is_wild) {
1375 WILDCARD_IN_OR_PATTERNS,
1377 "wildcard pattern covers any other pattern as it will match anyway",
1379 "consider handling `_` separately",
1386 #[allow(clippy::too_many_lines)]
1387 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1388 if expr.span.from_expansion() || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1393 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1394 // to prevent false positives as there is currently no better way to detect if code was excluded by
1395 // a macro. See PR #6435
1397 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1398 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1399 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1400 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1401 if rest_snippet.contains("=>");
1403 // The code it self contains another thick arrow "=>"
1404 // -> Either another arm or a comment
1409 let matched_vars = ex.span;
1410 let bind_names = arms[0].pat.span;
1411 let match_body = peel_blocks(arms[0].body);
1412 let mut snippet_body = if match_body.span.from_expansion() {
1413 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1415 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1418 // Do we need to add ';' to suggestion ?
1419 match match_body.kind {
1420 ExprKind::Block(block, _) => {
1421 // macro + expr_ty(body) == ()
1422 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1423 snippet_body.push(';');
1427 // expr_ty(body) == ()
1428 if cx.typeck_results().expr_ty(match_body).is_unit() {
1429 snippet_body.push(';');
1434 let mut applicability = Applicability::MaybeIncorrect;
1435 match arms[0].pat.kind {
1436 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1437 // If this match is in a local (`let`) stmt
1438 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1440 parent_let_node.span,
1442 "let {} = {};\n{}let {} = {};",
1443 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1444 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1445 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1446 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1451 // If we are in closure, we need curly braces around suggestion
1452 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1453 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1454 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1455 if let ExprKind::Closure(..) = parent_expr.kind {
1456 cbrace_end = format!("\n{}}}", indent);
1457 // Fix body indent due to the closure
1458 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1459 cbrace_start = format!("{{\n{}", indent);
1462 // If the parent is already an arm, and the body is another match statement,
1463 // we need curly braces around suggestion
1464 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1465 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1466 if let ExprKind::Match(..) = arm.body.kind {
1467 cbrace_end = format!("\n{}}}", indent);
1468 // Fix body indent due to the match
1469 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1470 cbrace_start = format!("{{\n{}", indent);
1476 "{}let {} = {};\n{}{}{}",
1478 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1479 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1488 MATCH_SINGLE_BINDING,
1490 "this match could be written as a `let` statement",
1491 "consider using `let` statement",
1497 if ex.can_have_side_effects() {
1498 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1501 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1507 MATCH_SINGLE_BINDING,
1509 "this match could be replaced by its scrutinee and body",
1510 "consider using the scrutinee and body instead",
1517 MATCH_SINGLE_BINDING,
1519 "this match could be replaced by its body itself",
1520 "consider using the match body instead",
1522 Applicability::MachineApplicable,
1530 /// Returns true if the `ex` match expression is in a local (`let`) statement
1531 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1532 let map = &cx.tcx.hir();
1534 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1535 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1537 return Some(parent_let_expr);
1543 /// Gets the ranges for each range pattern arm. Applies `ty` bounds for open ranges.
1544 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<FullInt>> {
1547 if let Arm { pat, guard: None, .. } = *arm {
1548 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1549 let lhs_const = match lhs {
1550 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1551 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1553 let rhs_const = match rhs {
1554 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1555 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1558 let lhs_val = lhs_const.int_value(cx, ty)?;
1559 let rhs_val = rhs_const.int_value(cx, ty)?;
1561 let rhs_bound = match range_end {
1562 RangeEnd::Included => EndBound::Included(rhs_val),
1563 RangeEnd::Excluded => EndBound::Excluded(rhs_val),
1565 return Some(SpannedRange {
1567 node: (lhs_val, rhs_bound),
1571 if let PatKind::Lit(value) = pat.kind {
1572 let value = constant_full_int(cx, cx.typeck_results(), value)?;
1573 return Some(SpannedRange {
1575 node: (value, EndBound::Included(value)),
1584 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1585 pub enum EndBound<T> {
1590 #[derive(Debug, Eq, PartialEq)]
1591 struct SpannedRange<T> {
1593 pub node: (T, EndBound<T>),
1596 // Checks if arm has the form `None => None`
1597 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1598 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1601 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1602 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1604 if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1605 if is_lang_ctor(cx, qpath, OptionSome);
1606 if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1607 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1608 if let ExprKind::Call(e, args) = peel_blocks(arm.body).kind;
1609 if let ExprKind::Path(ref some_path) = e.kind;
1610 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1611 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1612 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1620 fn has_multiple_ref_pats<'a, 'b, I>(pats: I) -> bool
1623 I: Iterator<Item = &'a Pat<'b>>,
1625 let mut ref_count = 0;
1626 for opt in pats.map(|pat| match pat.kind {
1627 PatKind::Ref(..) => Some(true), // &-patterns
1628 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1629 _ => None, // any other pattern is not fine
1631 if let Some(inner) = opt {
1642 fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1646 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1653 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1654 struct RangeBound<'a, T>(T, BoundKind, &'a SpannedRange<T>);
1656 impl<'a, T: Copy + Ord> PartialOrd for RangeBound<'a, T> {
1657 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1658 Some(self.cmp(other))
1662 impl<'a, T: Copy + Ord> Ord for RangeBound<'a, T> {
1663 fn cmp(&self, RangeBound(other_value, other_kind, _): &Self) -> Ordering {
1664 let RangeBound(self_value, self_kind, _) = *self;
1665 (self_value, self_kind).cmp(&(*other_value, *other_kind))
1669 let mut values = Vec::with_capacity(2 * ranges.len());
1671 for r @ SpannedRange { node: (start, end), .. } in ranges {
1672 values.push(RangeBound(*start, BoundKind::Start, r));
1673 values.push(match end {
1674 EndBound::Excluded(val) => RangeBound(*val, BoundKind::EndExcluded, r),
1675 EndBound::Included(val) => RangeBound(*val, BoundKind::EndIncluded, r),
1681 let mut started = vec![];
1683 for RangeBound(_, kind, range) in values {
1685 BoundKind::Start => started.push(range),
1686 BoundKind::EndExcluded | BoundKind::EndIncluded => {
1687 let mut overlap = None;
1689 while let Some(last_started) = started.pop() {
1690 if last_started == range {
1693 overlap = Some(last_started);
1696 if let Some(first_overlapping) = overlap {
1697 return Some((range, first_overlapping));
1706 mod redundant_pattern_match {
1707 use super::REDUNDANT_PATTERN_MATCHING;
1708 use clippy_utils::diagnostics::span_lint_and_then;
1709 use clippy_utils::source::snippet;
1710 use clippy_utils::sugg::Sugg;
1711 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, is_type_lang_item, match_type};
1712 use clippy_utils::{higher, match_def_path};
1713 use clippy_utils::{is_lang_ctor, is_trait_method, paths};
1714 use if_chain::if_chain;
1715 use rustc_ast::ast::LitKind;
1716 use rustc_data_structures::fx::FxHashSet;
1717 use rustc_errors::Applicability;
1718 use rustc_hir::LangItem::{OptionNone, PollPending};
1720 intravisit::{walk_expr, Visitor},
1721 Arm, Block, Expr, ExprKind, LangItem, MatchSource, Node, Pat, PatKind, QPath, UnOp,
1723 use rustc_lint::LateContext;
1724 use rustc_middle::ty::{self, subst::GenericArgKind, DefIdTree, Ty};
1725 use rustc_span::sym;
1727 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1728 if let Some(higher::IfLet {
1733 }) = higher::IfLet::hir(cx, expr)
1735 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "if", if_else.is_some());
1737 if let ExprKind::Match(op, arms, MatchSource::Normal) = &expr.kind {
1738 find_sugg_for_match(cx, expr, op, arms);
1740 if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) {
1741 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "while", false);
1745 /// Checks if the drop order for a type matters. Some std types implement drop solely to
1746 /// deallocate memory. For these types, and composites containing them, changing the drop order
1747 /// won't result in any observable side effects.
1748 fn type_needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1749 type_needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
1752 fn type_needs_ordered_drop_inner<'tcx>(
1753 cx: &LateContext<'tcx>,
1755 seen: &mut FxHashSet<Ty<'tcx>>,
1757 if !seen.insert(ty) {
1760 if !ty.needs_drop(cx.tcx, cx.param_env) {
1766 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1768 // This type doesn't implement drop, so no side effects here.
1769 // Check if any component type has any.
1771 ty::Tuple(_) => ty.tuple_fields().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1772 ty::Array(ty, _) => type_needs_ordered_drop_inner(cx, ty, seen),
1773 ty::Adt(adt, subs) => adt
1775 .map(|f| f.ty(cx.tcx, subs))
1776 .any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1780 // Check for std types which implement drop, but only for memory allocation.
1781 else if is_type_diagnostic_item(cx, ty, sym::Vec)
1782 || is_type_lang_item(cx, ty, LangItem::OwnedBox)
1783 || is_type_diagnostic_item(cx, ty, sym::Rc)
1784 || is_type_diagnostic_item(cx, ty, sym::Arc)
1785 || is_type_diagnostic_item(cx, ty, sym::cstring_type)
1786 || is_type_diagnostic_item(cx, ty, sym::BTreeMap)
1787 || is_type_diagnostic_item(cx, ty, sym::LinkedList)
1788 || match_type(cx, ty, &paths::WEAK_RC)
1789 || match_type(cx, ty, &paths::WEAK_ARC)
1791 // Check all of the generic arguments.
1792 if let ty::Adt(_, subs) = ty.kind() {
1793 subs.types().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen))
1802 // Extract the generic arguments out of a type
1803 fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
1805 if let ty::Adt(_, subs) = ty.kind();
1806 if let Some(sub) = subs.get(index);
1807 if let GenericArgKind::Type(sub_ty) = sub.unpack();
1816 // Checks if there are any temporaries created in the given expression for which drop order
1818 fn temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1819 struct V<'a, 'tcx> {
1820 cx: &'a LateContext<'tcx>,
1823 impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
1824 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1826 // Taking the reference of a value leaves a temporary
1827 // e.g. In `&String::new()` the string is a temporary value.
1828 // Remaining fields are temporary values
1829 // e.g. In `(String::new(), 0).1` the string is a temporary value.
1830 ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
1831 if !matches!(expr.kind, ExprKind::Path(_)) {
1832 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
1835 self.visit_expr(expr);
1839 // the base type is alway taken by reference.
1840 // e.g. In `(vec![0])[0]` the vector is a temporary value.
1841 ExprKind::Index(base, index) => {
1842 if !matches!(base.kind, ExprKind::Path(_)) {
1843 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
1846 self.visit_expr(base);
1849 self.visit_expr(index);
1851 // Method calls can take self by reference.
1852 // e.g. In `String::new().len()` the string is a temporary value.
1853 ExprKind::MethodCall(_, [self_arg, args @ ..], _) => {
1854 if !matches!(self_arg.kind, ExprKind::Path(_)) {
1855 let self_by_ref = self
1858 .type_dependent_def_id(expr.hir_id)
1859 .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
1861 && type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg))
1865 self.visit_expr(self_arg);
1868 args.iter().for_each(|arg| self.visit_expr(arg));
1870 // Either explicitly drops values, or changes control flow.
1871 ExprKind::DropTemps(_)
1873 | ExprKind::Break(..)
1874 | ExprKind::Yield(..)
1875 | ExprKind::Block(Block { expr: None, .. }, _)
1876 | ExprKind::Loop(..) => (),
1878 // Only consider the final expression.
1879 ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
1881 _ => walk_expr(self, expr),
1886 let mut v = V { cx, res: false };
1891 fn find_sugg_for_if_let<'tcx>(
1892 cx: &LateContext<'tcx>,
1893 expr: &'tcx Expr<'_>,
1895 let_expr: &'tcx Expr<'_>,
1896 keyword: &'static str,
1899 // also look inside refs
1900 // if we have &None for example, peel it so we can detect "if let None = x"
1901 let check_pat = match let_pat.kind {
1902 PatKind::Ref(inner, _mutability) => inner,
1905 let op_ty = cx.typeck_results().expr_ty(let_expr);
1906 // Determine which function should be used, and the type contained by the corresponding
1908 let (good_method, inner_ty) = match check_pat.kind {
1909 PatKind::TupleStruct(ref qpath, [sub_pat], _) => {
1910 if let PatKind::Wild = sub_pat.kind {
1911 let res = cx.typeck_results().qpath_res(qpath, check_pat.hir_id);
1912 let Some(id) = res.opt_def_id().and_then(|ctor_id| cx.tcx.parent(ctor_id)) else { return };
1913 let lang_items = cx.tcx.lang_items();
1914 if Some(id) == lang_items.result_ok_variant() {
1915 ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
1916 } else if Some(id) == lang_items.result_err_variant() {
1917 ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
1918 } else if Some(id) == lang_items.option_some_variant() {
1919 ("is_some()", op_ty)
1920 } else if Some(id) == lang_items.poll_ready_variant() {
1921 ("is_ready()", op_ty)
1922 } else if match_def_path(cx, id, &paths::IPADDR_V4) {
1923 ("is_ipv4()", op_ty)
1924 } else if match_def_path(cx, id, &paths::IPADDR_V6) {
1925 ("is_ipv6()", op_ty)
1933 PatKind::Path(ref path) => {
1934 let method = if is_lang_ctor(cx, path, OptionNone) {
1936 } else if is_lang_ctor(cx, path, PollPending) {
1941 // `None` and `Pending` don't have an inner type.
1942 (method, cx.tcx.types.unit)
1947 // If this is the last expression in a block or there is an else clause then the whole
1948 // type needs to be considered, not just the inner type of the branch being matched on.
1949 // Note the last expression in a block is dropped after all local bindings.
1950 let check_ty = if has_else
1951 || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
1958 // All temporaries created in the scrutinee expression are dropped at the same time as the
1959 // scrutinee would be, so they have to be considered as well.
1960 // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
1961 // for the duration if body.
1962 let needs_drop = type_needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
1964 // check that `while_let_on_iterator` lint does not trigger
1966 if keyword == "while";
1967 if let ExprKind::MethodCall(method_path, _, _) = let_expr.kind;
1968 if method_path.ident.name == sym::next;
1969 if is_trait_method(cx, let_expr, sym::Iterator);
1975 let result_expr = match &let_expr.kind {
1976 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1977 ExprKind::Unary(UnOp::Deref, deref) => deref,
1983 REDUNDANT_PATTERN_MATCHING,
1985 &format!("redundant pattern matching, consider using `{}`", good_method),
1987 // if/while let ... = ... { ... }
1988 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1989 let expr_span = expr.span;
1991 // if/while let ... = ... { ... }
1993 let op_span = result_expr.span.source_callsite();
1995 // if/while let ... = ... { ... }
1996 // ^^^^^^^^^^^^^^^^^^^
1997 let span = expr_span.until(op_span.shrink_to_hi());
1999 let app = if needs_drop {
2000 Applicability::MaybeIncorrect
2002 Applicability::MachineApplicable
2005 let sugg = Sugg::hir_with_macro_callsite(cx, result_expr, "_")
2009 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
2012 diag.note("this will change drop order of the result, as well as all temporaries");
2013 diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
2019 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
2020 if arms.len() == 2 {
2021 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
2023 let found_good_method = match node_pair {
2025 PatKind::TupleStruct(ref path_left, patterns_left, _),
2026 PatKind::TupleStruct(ref path_right, patterns_right, _),
2027 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
2028 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
2029 find_good_method_for_match(
2040 find_good_method_for_match(
2055 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
2056 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
2057 if patterns.len() == 1 =>
2059 if let PatKind::Wild = patterns[0].kind {
2060 find_good_method_for_match(
2065 &paths::OPTION_SOME,
2066 &paths::OPTION_NONE,
2071 find_good_method_for_match(
2077 &paths::POLL_PENDING,
2089 if let Some(good_method) = found_good_method {
2090 let span = expr.span.to(op.span);
2091 let result_expr = match &op.kind {
2092 ExprKind::AddrOf(_, _, borrowed) => borrowed,
2097 REDUNDANT_PATTERN_MATCHING,
2099 &format!("redundant pattern matching, consider using `{}`", good_method),
2101 diag.span_suggestion(
2104 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
2105 Applicability::MaybeIncorrect, // snippet
2113 #[allow(clippy::too_many_arguments)]
2114 fn find_good_method_for_match<'a>(
2115 cx: &LateContext<'_>,
2117 path_left: &QPath<'_>,
2118 path_right: &QPath<'_>,
2119 expected_left: &[&str],
2120 expected_right: &[&str],
2121 should_be_left: &'a str,
2122 should_be_right: &'a str,
2123 ) -> Option<&'a str> {
2126 .qpath_res(path_left, arms[0].pat.hir_id)
2130 .qpath_res(path_right, arms[1].pat.hir_id)
2132 let body_node_pair =
2133 if match_def_path(cx, left_id, expected_left) && match_def_path(cx, right_id, expected_right) {
2134 (&(*arms[0].body).kind, &(*arms[1].body).kind)
2135 } else if match_def_path(cx, right_id, expected_left) && match_def_path(cx, right_id, expected_right) {
2136 (&(*arms[1].body).kind, &(*arms[0].body).kind)
2141 match body_node_pair {
2142 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
2143 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
2144 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
2153 fn test_overlapping() {
2154 use rustc_span::source_map::DUMMY_SP;
2156 let sp = |s, e| SpannedRange {
2161 assert_eq!(None, overlapping::<u8>(&[]));
2162 assert_eq!(None, overlapping(&[sp(1, EndBound::Included(4))]));
2165 overlapping(&[sp(1, EndBound::Included(4)), sp(5, EndBound::Included(6))])
2170 sp(1, EndBound::Included(4)),
2171 sp(5, EndBound::Included(6)),
2172 sp(10, EndBound::Included(11))
2176 Some((&sp(1, EndBound::Included(4)), &sp(3, EndBound::Included(6)))),
2177 overlapping(&[sp(1, EndBound::Included(4)), sp(3, EndBound::Included(6))])
2180 Some((&sp(5, EndBound::Included(6)), &sp(6, EndBound::Included(11)))),
2182 sp(1, EndBound::Included(4)),
2183 sp(5, EndBound::Included(6)),
2184 sp(6, EndBound::Included(11))
2189 /// Implementation of `MATCH_SAME_ARMS`.
2190 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
2191 if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
2192 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
2193 let mut h = SpanlessHash::new(cx);
2194 h.hash_expr(arm.body);
2198 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
2199 let min_index = usize::min(lindex, rindex);
2200 let max_index = usize::max(lindex, rindex);
2202 let mut local_map: HirIdMap<HirId> = HirIdMap::default();
2203 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
2205 if let Some(a_id) = path_to_local(a);
2206 if let Some(b_id) = path_to_local(b);
2207 let entry = match local_map.entry(a_id) {
2208 Entry::Vacant(entry) => entry,
2209 // check if using the same bindings as before
2210 Entry::Occupied(entry) => return *entry.get() == b_id,
2212 // the names technically don't have to match; this makes the lint more conservative
2213 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2214 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2215 if pat_contains_local(lhs.pat, a_id);
2216 if pat_contains_local(rhs.pat, b_id);
2225 // Arms with a guard are ignored, those can’t always be merged together
2226 // This is also the case for arms in-between each there is an arm with a guard
2227 (min_index..=max_index).all(|index| arms[index].guard.is_none())
2228 && SpanlessEq::new(cx)
2229 .expr_fallback(eq_fallback)
2230 .eq_expr(lhs.body, rhs.body)
2231 // these checks could be removed to allow unused bindings
2232 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2233 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2236 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2237 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2242 "this `match` has identical arm bodies",
2244 diag.span_note(i.body.span, "same as this");
2246 // Note: this does not use `span_suggestion` on purpose:
2247 // there is no clean way
2248 // to remove the other arm. Building a span and suggest to replace it to ""
2249 // makes an even more confusing error message. Also in order not to make up a
2250 // span for the whole pattern, the suggestion is only shown when there is only
2251 // one pattern. The user should know about `|` if they are already using it…
2253 let lhs = snippet(cx, i.pat.span, "<pat1>");
2254 let rhs = snippet(cx, j.pat.span, "<pat2>");
2256 if let PatKind::Wild = j.pat.kind {
2257 // if the last arm is _, then i could be integrated into _
2258 // note that i.pat cannot be _, because that would mean that we're
2259 // hiding all the subsequent arms, and rust won't compile
2263 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2268 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs,))
2269 .help("...or consider changing the match arm bodies");
2277 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2278 let mut result = false;
2279 pat.walk_short(|p| {
2280 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2286 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2287 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2288 let mut result = true;
2289 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2290 result && ids.is_empty()