1 use clippy_utils::consts::{constant, miri_to_const, Constant};
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::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
6 use clippy_utils::sugg::Sugg;
7 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
8 use clippy_utils::visitors::LocalUsedVisitor;
10 get_parent_expr, in_macro, is_expn_of, is_lang_ctor, is_lint_allowed, is_refutable, is_wild, meets_msrv, msrvs,
11 path_to_local, path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks,
14 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
15 use if_chain::if_chain;
16 use rustc_ast::ast::LitKind;
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, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource,
22 Mutability, Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
24 use rustc_hir::{HirIdMap, HirIdSet};
25 use rustc_lint::{LateContext, LateLintPass, LintContext};
26 use rustc_middle::lint::in_external_macro;
27 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
28 use rustc_semver::RustcVersion;
29 use rustc_session::{declare_tool_lint, impl_lint_pass};
30 use rustc_span::source_map::{Span, Spanned};
32 use std::cmp::Ordering;
33 use std::collections::hash_map::Entry;
37 declare_clippy_lint! {
38 /// **What it does:** Checks for matches with a single arm where an `if let`
39 /// will usually suffice.
41 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
43 /// **Known problems:** None.
47 /// # fn bar(stool: &str) {}
48 /// # let x = Some("abc");
51 /// Some(ref foo) => bar(foo),
56 /// if let Some(ref foo) = x {
62 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for matches with two arms where an `if let else` will
69 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
71 /// **Known problems:** Personal style preferences may differ.
78 /// # fn bar(foo: &usize) {}
79 /// # let other_ref: usize = 1;
80 /// # let x: Option<&usize> = Some(&1);
82 /// Some(ref foo) => bar(foo),
83 /// _ => bar(&other_ref),
87 /// Using `if let` with `else`:
90 /// # fn bar(foo: &usize) {}
91 /// # let other_ref: usize = 1;
92 /// # let x: Option<&usize> = Some(&1);
93 /// if let Some(ref foo) = x {
99 pub SINGLE_MATCH_ELSE,
101 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
104 declare_clippy_lint! {
105 /// **What it does:** Checks for matches where all arms match a reference,
106 /// suggesting to remove the reference and deref the matched expression
107 /// instead. It also checks for `if let &foo = bar` blocks.
109 /// **Why is this bad?** It just makes the code less readable. That reference
110 /// destructuring adds nothing to the code.
112 /// **Known problems:** None.
118 /// &A(ref y) => foo(y),
125 /// A(ref y) => foo(y),
132 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
135 declare_clippy_lint! {
136 /// **What it does:** Checks for matches where match expression is a `bool`. It
137 /// suggests to replace the expression with an `if...else` block.
139 /// **Why is this bad?** It makes the code less readable.
141 /// **Known problems:** None.
147 /// let condition: bool = true;
148 /// match condition {
153 /// Use if/else instead:
157 /// let condition: bool = true;
166 "a `match` on a boolean expression instead of an `if..else` block"
169 declare_clippy_lint! {
170 /// **What it does:** Checks for overlapping match arms.
172 /// **Why is this bad?** It is likely to be an error and if not, makes the code
175 /// **Known problems:** None.
181 /// 1...10 => println!("1 ... 10"),
182 /// 5...15 => println!("5 ... 15"),
186 pub MATCH_OVERLAPPING_ARM,
188 "a `match` with overlapping arms"
191 declare_clippy_lint! {
192 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
193 /// and take drastic actions like `panic!`.
195 /// **Why is this bad?** It is generally a bad practice, similar to
196 /// catching all exceptions in java with `catch(Exception)`
198 /// **Known problems:** None.
202 /// let x: Result<i32, &str> = Ok(3);
204 /// Ok(_) => println!("ok"),
205 /// Err(_) => panic!("err"),
208 pub MATCH_WILD_ERR_ARM,
210 "a `match` with `Err(_)` arm and take drastic actions"
213 declare_clippy_lint! {
214 /// **What it does:** Checks for match which is used to add a reference to an
217 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
219 /// **Known problems:** None.
223 /// let x: Option<()> = None;
226 /// let r: Option<&()> = match x {
228 /// Some(ref v) => Some(v),
232 /// let r: Option<&()> = x.as_ref();
236 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
239 declare_clippy_lint! {
240 /// **What it does:** Checks for wildcard enum matches using `_`.
242 /// **Why is this bad?** New enum variants added by library updates can be missed.
244 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
245 /// variants, and also may not use correct path to enum if it's not present in the current scope.
249 /// # enum Foo { A(usize), B(usize) }
250 /// # let x = Foo::B(1);
263 pub WILDCARD_ENUM_MATCH_ARM,
265 "a wildcard enum match arm using `_`"
268 declare_clippy_lint! {
269 /// **What it does:** Checks for wildcard enum matches for a single variant.
271 /// **Why is this bad?** New enum variants added by library updates can be missed.
273 /// **Known problems:** Suggested replacements may not use correct path to enum
274 /// if it's not present in the current scope.
279 /// # enum Foo { A, B, C }
280 /// # let x = Foo::B;
295 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
297 "a wildcard enum match for a single variant"
300 declare_clippy_lint! {
301 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
303 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
304 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
306 /// **Known problems:** None.
322 pub WILDCARD_IN_OR_PATTERNS,
324 "a wildcard pattern used with others patterns in same match arm"
327 declare_clippy_lint! {
328 /// **What it does:** Checks for matches being used to destructure a single-variant enum
329 /// or tuple struct where a `let` will suffice.
331 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
333 /// **Known problems:** None.
341 /// let wrapper = Wrapper::Data(42);
343 /// let data = match wrapper {
344 /// Wrapper::Data(i) => i,
348 /// The correct use would be:
354 /// let wrapper = Wrapper::Data(42);
355 /// let Wrapper::Data(data) = wrapper;
357 pub INFALLIBLE_DESTRUCTURING_MATCH,
359 "a `match` statement with a single infallible arm instead of a `let`"
362 declare_clippy_lint! {
363 /// **What it does:** Checks for useless match that binds to only one value.
365 /// **Why is this bad?** Readability and needless complexity.
367 /// **Known problems:** Suggested replacements may be incorrect when `match`
368 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
383 /// let (c, d) = (a, b);
385 pub MATCH_SINGLE_BINDING,
387 "a match with a single binding instead of using `let` statement"
390 declare_clippy_lint! {
391 /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
393 /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
394 /// matching all enum variants explicitly.
396 /// **Known problems:** None.
400 /// # struct A { a: i32 }
401 /// let a = A { a: 5 };
405 /// A { a: 5, .. } => {},
411 /// A { a: 5 } => {},
415 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
417 "a match on a struct that binds all fields but still uses the wildcard pattern"
420 declare_clippy_lint! {
421 /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
422 /// `std::task::Poll` or `std::net::IpAddr`
424 /// **Why is this bad?** It's more concise and clear to just use the proper
427 /// **Known problems:** This will change the drop order for the matched type. Both `if let` and
428 /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
429 /// value before entering the block. For most types this change will not matter, but for a few
430 /// types this will not be an acceptable change (e.g. locks). See the
431 /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
437 /// # use std::task::Poll;
438 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
439 /// if let Ok(_) = Ok::<i32, i32>(42) {}
440 /// if let Err(_) = Err::<i32, i32>(42) {}
441 /// if let None = None::<()> {}
442 /// if let Some(_) = Some(42) {}
443 /// if let Poll::Pending = Poll::Pending::<()> {}
444 /// if let Poll::Ready(_) = Poll::Ready(42) {}
445 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
446 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
447 /// match Ok::<i32, i32>(42) {
453 /// The more idiomatic use would be:
456 /// # use std::task::Poll;
457 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
458 /// if Ok::<i32, i32>(42).is_ok() {}
459 /// if Err::<i32, i32>(42).is_err() {}
460 /// if None::<()>.is_none() {}
461 /// if Some(42).is_some() {}
462 /// if Poll::Pending::<()>.is_pending() {}
463 /// if Poll::Ready(42).is_ready() {}
464 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
465 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
466 /// Ok::<i32, i32>(42).is_ok();
468 pub REDUNDANT_PATTERN_MATCHING,
470 "use the proper utility function avoiding an `if let`"
473 declare_clippy_lint! {
474 /// **What it does:** Checks for `match` or `if let` expressions producing a
475 /// `bool` that could be written using `matches!`
477 /// **Why is this bad?** Readability and needless complexity.
479 /// **Known problems:** This lint falsely triggers, if there are arms with
480 /// `cfg` attributes that remove an arm evaluating to `false`.
487 /// let a = match x {
492 /// let a = if let Some(0) = x {
499 /// let a = matches!(x, Some(0));
501 pub MATCH_LIKE_MATCHES_MACRO,
503 "a match that could be written with the matches! macro"
506 declare_clippy_lint! {
507 /// **What it does:** Checks for `match` with identical arm bodies.
509 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
510 /// are the same on purpose, you can factor them
511 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
513 /// **Known problems:** False positive possible with order dependent `match`
515 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
522 /// Baz => bar(), // <= oops
526 /// This should probably be
531 /// Baz => baz(), // <= fixed
535 /// or if the original code was not a typo:
538 /// Bar | Baz => bar(), // <= shows the intent better
544 "`match` with identical arm bodies"
549 msrv: Option<RustcVersion>,
550 infallible_destructuring_match_linted: bool,
555 pub fn new(msrv: Option<RustcVersion>) -> Self {
563 impl_lint_pass!(Matches => [
568 MATCH_OVERLAPPING_ARM,
571 WILDCARD_ENUM_MATCH_ARM,
572 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
573 WILDCARD_IN_OR_PATTERNS,
574 MATCH_SINGLE_BINDING,
575 INFALLIBLE_DESTRUCTURING_MATCH,
576 REST_PAT_IN_FULLY_BOUND_STRUCTS,
577 REDUNDANT_PATTERN_MATCHING,
578 MATCH_LIKE_MATCHES_MACRO,
582 impl<'tcx> LateLintPass<'tcx> for Matches {
583 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
584 if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
588 redundant_pattern_match::check(cx, expr);
590 if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
591 if !check_match_like_matches(cx, expr) {
592 lint_match_arms(cx, expr);
595 lint_match_arms(cx, expr);
598 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
599 check_single_match(cx, ex, arms, expr);
600 check_match_bool(cx, ex, arms, expr);
601 check_overlapping_arms(cx, ex, arms);
602 check_wild_err_arm(cx, ex, arms);
603 check_wild_enum_match(cx, ex, arms);
604 check_match_as_ref(cx, ex, arms, expr);
605 check_wild_in_or_pats(cx, arms);
607 if self.infallible_destructuring_match_linted {
608 self.infallible_destructuring_match_linted = false;
610 check_match_single_binding(cx, ex, arms, expr);
613 if let ExprKind::Match(ex, arms, _) = expr.kind {
614 check_match_ref_pats(cx, ex, arms, expr);
618 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
620 if !in_external_macro(cx.sess(), local.span);
621 if !in_macro(local.span);
622 if let Some(expr) = local.init;
623 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
624 if arms.len() == 1 && arms[0].guard.is_none();
625 if let PatKind::TupleStruct(
626 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
628 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
629 let body = remove_blocks(arms[0].body);
630 if path_to_local_id(body, arg);
633 let mut applicability = Applicability::MachineApplicable;
634 self.infallible_destructuring_match_linted = true;
637 INFALLIBLE_DESTRUCTURING_MATCH,
639 "you seem to be trying to use `match` to destructure a single infallible pattern. \
640 Consider using `let`",
644 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
645 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
646 snippet_with_applicability(cx, target.span, "..", &mut applicability),
654 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
656 if !in_external_macro(cx.sess(), pat.span);
657 if !in_macro(pat.span);
658 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
659 if let Some(def_id) = path.res.opt_def_id();
660 let ty = cx.tcx.type_of(def_id);
661 if let ty::Adt(def, _) = ty.kind();
662 if def.is_struct() || def.is_union();
663 if fields.len() == def.non_enum_variant().fields.len();
668 REST_PAT_IN_FULLY_BOUND_STRUCTS,
670 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
672 "consider removing `..` from this binding",
678 extract_msrv_attr!(LateContext);
682 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
683 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
684 if in_macro(expr.span) {
685 // Don't lint match expressions present in
686 // macro_rules! block
689 if let PatKind::Or(..) = arms[0].pat.kind {
690 // don't lint for or patterns for now, this makes
691 // the lint noisy in unnecessary situations
694 let els = arms[1].body;
695 let els = if is_unit_expr(remove_blocks(els)) {
697 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
698 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
699 // single statement/expr "else" block, don't lint
702 // block with 2+ statements or 1 expr and 1+ statement
705 // not a block, don't lint
709 let ty = cx.typeck_results().expr_ty(ex);
710 if *ty.kind() != ty::Bool || is_lint_allowed(cx, MATCH_BOOL, ex.hir_id) {
711 check_single_match_single_pattern(cx, ex, arms, expr, els);
712 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
717 fn check_single_match_single_pattern(
718 cx: &LateContext<'_>,
722 els: Option<&Expr<'_>>,
724 if is_wild(arms[1].pat) {
725 report_single_match_single_pattern(cx, ex, arms, expr, els);
729 fn report_single_match_single_pattern(
730 cx: &LateContext<'_>,
734 els: Option<&Expr<'_>>,
736 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
737 let els_str = els.map_or(String::new(), |els| {
738 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
741 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
742 let (msg, sugg) = if_chain! {
743 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
744 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
745 if let Some(spe_trait_id) = cx.tcx.lang_items().structural_peq_trait();
746 if let Some(pe_trait_id) = cx.tcx.lang_items().eq_trait();
747 if ty.is_integral() || ty.is_char() || ty.is_str()
748 || (implements_trait(cx, ty, spe_trait_id, &[])
749 && implements_trait(cx, ty, pe_trait_id, &[ty.into()]));
751 // scrutinee derives PartialEq and the pattern is a constant.
752 let pat_ref_count = match pat.kind {
753 // string literals are already a reference.
754 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
757 // References are only implicitly added to the pattern, so no overflow here.
758 // e.g. will work: match &Some(_) { Some(_) => () }
759 // will not: match Some(_) { &Some(_) => () }
760 let ref_count_diff = ty_ref_count - pat_ref_count;
762 // Try to remove address of expressions first.
763 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
764 let ref_count_diff = ref_count_diff - removed;
766 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
768 "if {} == {}{} {}{}",
769 snippet(cx, ex.span, ".."),
770 // PartialEq for different reference counts may not exist.
771 "&".repeat(ref_count_diff),
772 snippet(cx, arms[0].pat.span, ".."),
773 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
778 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
780 "if let {} = {} {}{}",
781 snippet(cx, arms[0].pat.span, ".."),
782 snippet(cx, ex.span, ".."),
783 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
797 Applicability::HasPlaceholders,
801 fn check_single_match_opt_like(
802 cx: &LateContext<'_>,
807 els: Option<&Expr<'_>>,
809 // list of candidate `Enum`s we know will never get any more members
811 (&paths::COW, "Borrowed"),
812 (&paths::COW, "Cow::Borrowed"),
813 (&paths::COW, "Cow::Owned"),
814 (&paths::COW, "Owned"),
815 (&paths::OPTION, "None"),
816 (&paths::RESULT, "Err"),
817 (&paths::RESULT, "Ok"),
820 let path = match arms[1].pat.kind {
821 PatKind::TupleStruct(ref path, inner, _) => {
822 // Contains any non wildcard patterns (e.g., `Err(err)`)?
823 if !inner.iter().all(is_wild) {
826 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
828 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
829 PatKind::Path(ref path) => {
830 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
835 for &(ty_path, pat_path) in candidates {
836 if path == *pat_path && match_type(cx, ty, ty_path) {
837 report_single_match_single_pattern(cx, ex, arms, expr, els);
842 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
843 // Type of expression is `bool`.
844 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
849 "you seem to be trying to match on a boolean expression",
853 let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
854 if let ExprKind::Lit(ref lit) = arm_bool.kind {
856 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
857 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
867 if let Some((true_expr, false_expr)) = exprs {
868 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
869 (false, false) => Some(format!(
871 snippet(cx, ex.span, "b"),
872 expr_block(cx, true_expr, None, "..", Some(expr.span)),
873 expr_block(cx, false_expr, None, "..", Some(expr.span))
875 (false, true) => Some(format!(
877 snippet(cx, ex.span, "b"),
878 expr_block(cx, true_expr, None, "..", Some(expr.span))
881 let test = Sugg::hir(cx, ex, "..");
885 expr_block(cx, false_expr, None, "..", Some(expr.span))
888 (true, true) => None,
891 if let Some(sugg) = sugg {
892 diag.span_suggestion(
894 "consider using an `if`/`else` expression",
896 Applicability::HasPlaceholders,
906 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
907 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
908 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
909 let type_ranges = type_ranges(&ranges);
910 if !type_ranges.is_empty() {
911 if let Some((start, end)) = overlapping(&type_ranges) {
914 MATCH_OVERLAPPING_ARM,
916 "some ranges overlap",
918 "overlaps with this",
925 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
926 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
927 if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
929 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
930 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
931 if path_str == "Err" {
932 let mut matching_wild = inner.iter().any(is_wild);
933 let mut ident_bind_name = String::from("_");
935 // Looking for unused bindings (i.e.: `_e`)
936 for pat in inner.iter() {
937 if let PatKind::Binding(_, id, ident, None) = pat.kind {
938 if ident.as_str().starts_with('_')
939 && !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
941 ident_bind_name = (&ident.name.as_str()).to_string();
942 matching_wild = true;
949 if let ExprKind::Block(block, _) = arm.body.kind;
950 if is_panic_block(block);
952 // `Err(_)` or `Err(_e)` arm with `panic!` found
953 span_lint_and_note(cx,
956 &format!("`Err({})` matches all errors", &ident_bind_name),
958 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
968 enum CommonPrefixSearcher<'a> {
970 Path(&'a [PathSegment<'a>]),
973 impl CommonPrefixSearcher<'a> {
974 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
976 [path @ .., _] => self.with_prefix(path),
981 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
983 Self::None => *self = Self::Path(path),
984 Self::Path(self_path)
987 .map(|p| p.ident.name)
988 .eq(self_path.iter().map(|p| p.ident.name)) => {},
989 Self::Path(_) => *self = Self::Mixed,
995 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
996 let attrs = cx.tcx.get_attrs(variant_def.def_id);
997 clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
1000 #[allow(clippy::too_many_lines)]
1001 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
1002 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
1003 let adt_def = match ty.kind() {
1005 if adt_def.is_enum()
1006 && !(is_type_diagnostic_item(cx, ty, sym::option_type)
1007 || is_type_diagnostic_item(cx, ty, sym::result_type)) =>
1014 // First pass - check for violation, but don't do much book-keeping because this is hopefully
1015 // the uncommon case, and the book-keeping is slightly expensive.
1016 let mut wildcard_span = None;
1017 let mut wildcard_ident = None;
1018 let mut has_non_wild = false;
1020 match peel_hir_pat_refs(arm.pat).0.kind {
1021 PatKind::Wild => wildcard_span = Some(arm.pat.span),
1022 PatKind::Binding(_, _, ident, None) => {
1023 wildcard_span = Some(arm.pat.span);
1024 wildcard_ident = Some(ident);
1026 _ => has_non_wild = true,
1029 let wildcard_span = match wildcard_span {
1030 Some(x) if has_non_wild => x,
1034 // Accumulate the variants which should be put in place of the wildcard because they're not
1036 let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
1037 let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
1039 let mut path_prefix = CommonPrefixSearcher::None;
1041 // Guards mean that this case probably isn't exhaustively covered. Technically
1042 // this is incorrect, as we should really check whether each variant is exhaustively
1043 // covered by the set of guards that cover it, but that's really hard to do.
1044 recurse_or_patterns(arm.pat, |pat| {
1045 let path = match &peel_hir_pat_refs(pat).0.kind {
1046 PatKind::Path(path) => {
1047 #[allow(clippy::match_same_arms)]
1048 let id = match cx.qpath_res(path, pat.hir_id) {
1049 Res::Def(DefKind::Const | DefKind::ConstParam | DefKind::AnonConst, _) => return,
1050 Res::Def(_, id) => id,
1053 if arm.guard.is_none() {
1054 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1058 PatKind::TupleStruct(path, patterns, ..) => {
1059 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1060 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1061 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1066 PatKind::Struct(path, patterns, ..) => {
1067 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1068 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1069 missing_variants.retain(|e| e.def_id != id);
1077 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1078 QPath::TypeRelative(
1080 kind: TyKind::Path(QPath::Resolved(_, path)),
1084 ) => path_prefix.with_prefix(path.segments),
1090 let format_suggestion = |variant: &VariantDef| {
1093 if let Some(ident) = wildcard_ident {
1094 format!("{} @ ", ident.name)
1098 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1099 let mut s = String::new();
1100 for seg in path_prefix {
1101 s.push_str(&seg.ident.as_str());
1106 let mut s = cx.tcx.def_path_str(adt_def.did);
1111 match variant.ctor_kind {
1112 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1113 CtorKind::Fn => "(..)",
1114 CtorKind::Const => "",
1115 CtorKind::Fictive => "{ .. }",
1120 match missing_variants.as_slice() {
1122 [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
1124 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1126 "wildcard matches only a single variant and will also match any future added variants",
1128 format_suggestion(x),
1129 Applicability::MaybeIncorrect,
1132 let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1133 let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
1134 suggestions.push("_".into());
1135 "wildcard matches known variants and will also match future added variants"
1137 "wildcard match will also match any future added variants"
1142 WILDCARD_ENUM_MATCH_ARM,
1146 suggestions.join(" | "),
1147 Applicability::MaybeIncorrect,
1153 // If the block contains only a `panic!` macro (as expression or statement)
1154 fn is_panic_block(block: &Block<'_>) -> bool {
1155 match (&block.expr, block.stmts.len(), block.stmts.first()) {
1156 (&Some(exp), 0, _) => is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none(),
1157 (&None, 1, Some(stmt)) => {
1158 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1164 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1165 if has_only_ref_pats(arms) {
1166 let mut suggs = Vec::with_capacity(arms.len() + 1);
1167 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1168 let span = ex.span.source_callsite();
1169 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1171 "you don't need to add `&` to both the expression and the patterns",
1175 let span = ex.span.source_callsite();
1176 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1178 "you don't need to add `&` to all patterns",
1179 "instead of prefixing all patterns with `&`, you can dereference the expression",
1183 suggs.extend(arms.iter().filter_map(|a| {
1184 if let PatKind::Ref(refp, _) = a.pat.kind {
1185 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1191 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1192 if !expr.span.from_expansion() {
1193 multispan_sugg(diag, msg, suggs);
1199 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1200 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1201 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1202 is_ref_some_arm(cx, &arms[1])
1203 } else if is_none_arm(cx, &arms[1]) {
1204 is_ref_some_arm(cx, &arms[0])
1208 if let Some(rb) = arm_ref {
1209 let suggestion = if rb == BindingAnnotation::Ref {
1215 let output_ty = cx.typeck_results().expr_ty(expr);
1216 let input_ty = cx.typeck_results().expr_ty(ex);
1218 let cast = if_chain! {
1219 if let ty::Adt(_, substs) = input_ty.kind();
1220 let input_ty = substs.type_at(0);
1221 if let ty::Adt(_, substs) = output_ty.kind();
1222 let output_ty = substs.type_at(0);
1223 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1224 if input_ty != output_ty;
1232 let mut applicability = Applicability::MachineApplicable;
1237 &format!("use `{}()` instead", suggestion),
1241 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1251 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1253 if let PatKind::Or(fields) = arm.pat.kind {
1254 // look for multiple fields in this arm that contains at least one Wild pattern
1255 if fields.len() > 1 && fields.iter().any(is_wild) {
1258 WILDCARD_IN_OR_PATTERNS,
1260 "wildcard pattern covers any other pattern as it will match anyway",
1262 "consider handling `_` separately",
1269 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1270 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1271 if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1272 match match_source {
1273 MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1274 MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1282 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1283 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1286 if cx.typeck_results().expr_ty(expr).is_bool();
1287 if let Some((b1_arm, b0_arms)) = arms.split_last();
1288 if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1289 if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1290 if is_wild(b1_arm.pat);
1292 let if_guard = &b0_arms[0].guard;
1293 if if_guard.is_none() || b0_arms.len() == 1;
1294 if cx.tcx.hir().attrs(b0_arms[0].hir_id).is_empty();
1295 if b0_arms[1..].iter()
1297 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1298 arm.guard.is_none() && cx.tcx.hir().attrs(arm.hir_id).is_empty()
1301 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1302 // evaluated into `false` and so such arms will be stripped before.
1303 let mut applicability = Applicability::MaybeIncorrect;
1305 use itertools::Itertools as _;
1307 .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1310 let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1311 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1316 // strip potential borrows (#6503), but only if the type is a reference
1317 let mut ex_new = ex;
1318 if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1319 if let ty::Ref(..) = cx.typeck_results().expr_ty(ex_inner).kind() {
1325 MATCH_LIKE_MATCHES_MACRO,
1327 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1330 "{}matches!({}, {})",
1331 if b0 { "" } else { "!" },
1332 snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1344 /// Extract a `bool` or `{ bool }`
1345 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1347 ExprKind::Lit(Spanned {
1348 node: LitKind::Bool(b), ..
1358 if let ExprKind::Lit(Spanned {
1359 node: LitKind::Bool(b), ..
1371 #[allow(clippy::too_many_lines)]
1372 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1373 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1378 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1379 // to prevent false positives as there is currently no better way to detect if code was excluded by
1380 // a macro. See PR #6435
1382 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1383 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1384 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1385 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1386 if rest_snippet.contains("=>");
1388 // The code it self contains another thick arrow "=>"
1389 // -> Either another arm or a comment
1394 let matched_vars = ex.span;
1395 let bind_names = arms[0].pat.span;
1396 let match_body = remove_blocks(arms[0].body);
1397 let mut snippet_body = if match_body.span.from_expansion() {
1398 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1400 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1403 // Do we need to add ';' to suggestion ?
1404 match match_body.kind {
1405 ExprKind::Block(block, _) => {
1406 // macro + expr_ty(body) == ()
1407 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1408 snippet_body.push(';');
1412 // expr_ty(body) == ()
1413 if cx.typeck_results().expr_ty(match_body).is_unit() {
1414 snippet_body.push(';');
1419 let mut applicability = Applicability::MaybeIncorrect;
1420 match arms[0].pat.kind {
1421 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1422 // If this match is in a local (`let`) stmt
1423 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1425 parent_let_node.span,
1427 "let {} = {};\n{}let {} = {};",
1428 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1429 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1430 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1431 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1436 // If we are in closure, we need curly braces around suggestion
1437 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1438 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1439 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1440 if let ExprKind::Closure(..) = parent_expr.kind {
1441 cbrace_end = format!("\n{}}}", indent);
1442 // Fix body indent due to the closure
1443 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1444 cbrace_start = format!("{{\n{}", indent);
1447 // If the parent is already an arm, and the body is another match statement,
1448 // we need curly braces around suggestion
1449 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1450 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1451 if let ExprKind::Match(..) = arm.body.kind {
1452 cbrace_end = format!("\n{}}}", indent);
1453 // Fix body indent due to the match
1454 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1455 cbrace_start = format!("{{\n{}", indent);
1461 "{}let {} = {};\n{}{}{}",
1463 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1464 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1473 MATCH_SINGLE_BINDING,
1475 "this match could be written as a `let` statement",
1476 "consider using `let` statement",
1482 if ex.can_have_side_effects() {
1483 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1486 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1492 MATCH_SINGLE_BINDING,
1494 "this match could be replaced by its scrutinee and body",
1495 "consider using the scrutinee and body instead",
1502 MATCH_SINGLE_BINDING,
1504 "this match could be replaced by its body itself",
1505 "consider using the match body instead",
1507 Applicability::MachineApplicable,
1515 /// Returns true if the `ex` match expression is in a local (`let`) statement
1516 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1517 let map = &cx.tcx.hir();
1519 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1520 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1522 return Some(parent_let_expr);
1528 /// Gets all arms that are unbounded `PatRange`s.
1529 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1532 if let Arm { pat, guard: None, .. } = *arm {
1533 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1534 let lhs = match lhs {
1535 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1536 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1538 let rhs = match rhs {
1539 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1540 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1542 let rhs = match range_end {
1543 RangeEnd::Included => Bound::Included(rhs),
1544 RangeEnd::Excluded => Bound::Excluded(rhs),
1546 return Some(SpannedRange {
1552 if let PatKind::Lit(value) = pat.kind {
1553 let value = constant(cx, cx.typeck_results(), value)?.0;
1554 return Some(SpannedRange {
1556 node: (value.clone(), Bound::Included(value)),
1565 #[derive(Debug, Eq, PartialEq)]
1566 pub struct SpannedRange<T> {
1568 pub node: (T, Bound<T>),
1571 type TypedRanges = Vec<SpannedRange<u128>>;
1573 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1574 /// and other types than
1575 /// `Uint` and `Int` probably don't make sense.
1576 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1579 .filter_map(|range| match range.node {
1580 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1582 node: (start, Bound::Included(end)),
1584 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1586 node: (start, Bound::Excluded(end)),
1588 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1590 node: (start, Bound::Unbounded),
1597 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1599 ExprKind::Tup(v) if v.is_empty() => true,
1600 ExprKind::Block(b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1605 // Checks if arm has the form `None => None`
1606 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1607 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1610 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1611 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1613 if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1614 if is_lang_ctor(cx, qpath, OptionSome);
1615 if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1616 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1617 if let ExprKind::Call(e, args) = remove_blocks(arm.body).kind;
1618 if let ExprKind::Path(ref some_path) = e.kind;
1619 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1620 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1621 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1629 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1634 PatKind::Ref(..) => Some(true), // &-patterns
1635 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1636 _ => None, // any other pattern is not fine
1639 .collect::<Option<Vec<bool>>>();
1640 // look for Some(v) where there's at least one true element
1641 mapped.map_or(false, |v| v.iter().any(|el| *el))
1644 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1648 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1650 Start(T, &'a SpannedRange<T>),
1651 End(Bound<T>, &'a SpannedRange<T>),
1654 impl<'a, T: Copy> Kind<'a, T> {
1655 fn range(&self) -> &'a SpannedRange<T> {
1657 Kind::Start(_, r) | Kind::End(_, r) => r,
1661 fn value(self) -> Bound<T> {
1663 Kind::Start(t, _) => Bound::Included(t),
1664 Kind::End(t, _) => t,
1669 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1670 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1671 Some(self.cmp(other))
1675 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1676 fn cmp(&self, other: &Self) -> Ordering {
1677 match (self.value(), other.value()) {
1678 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1679 // Range patterns cannot be unbounded (yet)
1680 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1681 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1682 Ordering::Equal => Ordering::Greater,
1685 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1686 Ordering::Equal => Ordering::Less,
1693 let mut values = Vec::with_capacity(2 * ranges.len());
1696 values.push(Kind::Start(r.node.0, r));
1697 values.push(Kind::End(r.node.1, r));
1702 for (a, b) in iter::zip(&values, values.iter().skip(1)) {
1704 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1705 if ra.node != rb.node {
1706 return Some((ra, rb));
1709 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1711 // skip if the range `a` is completely included into the range `b`
1712 if let Ordering::Equal | Ordering::Less = a.cmp(b) {
1713 let kind_a = Kind::End(a.range().node.1, a.range());
1714 let kind_b = Kind::End(b.range().node.1, b.range());
1715 if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1719 return Some((a.range(), b.range()));
1727 mod redundant_pattern_match {
1728 use super::REDUNDANT_PATTERN_MATCHING;
1729 use clippy_utils::diagnostics::span_lint_and_then;
1730 use clippy_utils::source::{snippet, snippet_with_applicability};
1731 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, is_type_lang_item, match_type};
1732 use clippy_utils::{is_lang_ctor, is_qpath_def_path, is_trait_method, paths};
1733 use if_chain::if_chain;
1734 use rustc_ast::ast::LitKind;
1735 use rustc_data_structures::fx::FxHashSet;
1736 use rustc_errors::Applicability;
1737 use rustc_hir::LangItem::{OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk};
1739 intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
1740 Arm, Block, Expr, ExprKind, LangItem, MatchSource, Node, PatKind, QPath,
1742 use rustc_lint::LateContext;
1743 use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
1744 use rustc_span::sym;
1746 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1747 if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1748 match match_source {
1749 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1750 MatchSource::IfLetDesugar { contains_else_clause } => {
1751 find_sugg_for_if_let(cx, expr, op, &arms[0], "if", *contains_else_clause);
1753 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, &arms[0], "while", false),
1759 /// Checks if the drop order for a type matters. Some std types implement drop solely to
1760 /// deallocate memory. For these types, and composites containing them, changing the drop order
1761 /// won't result in any observable side effects.
1762 fn type_needs_ordered_drop(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1763 type_needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
1766 fn type_needs_ordered_drop_inner(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
1767 if !seen.insert(ty) {
1770 if !ty.needs_drop(cx.tcx, cx.param_env) {
1776 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1778 // This type doesn't implement drop, so no side effects here.
1779 // Check if any component type has any.
1781 ty::Tuple(_) => ty.tuple_fields().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1782 ty::Array(ty, _) => type_needs_ordered_drop_inner(cx, ty, seen),
1783 ty::Adt(adt, subs) => adt
1785 .map(|f| f.ty(cx.tcx, subs))
1786 .any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1790 // Check for std types which implement drop, but only for memory allocation.
1791 else if is_type_diagnostic_item(cx, ty, sym::vec_type)
1792 || is_type_lang_item(cx, ty, LangItem::OwnedBox)
1793 || is_type_diagnostic_item(cx, ty, sym::Rc)
1794 || is_type_diagnostic_item(cx, ty, sym::Arc)
1795 || is_type_diagnostic_item(cx, ty, sym::cstring_type)
1796 || match_type(cx, ty, &paths::BTREEMAP)
1797 || match_type(cx, ty, &paths::LINKED_LIST)
1798 || match_type(cx, ty, &paths::WEAK_RC)
1799 || match_type(cx, ty, &paths::WEAK_ARC)
1801 // Check all of the generic arguments.
1802 if let ty::Adt(_, subs) = ty.kind() {
1803 subs.types().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen))
1812 // Extract the generic arguments out of a type
1813 fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
1815 if let ty::Adt(_, subs) = ty.kind();
1816 if let Some(sub) = subs.get(index);
1817 if let GenericArgKind::Type(sub_ty) = sub.unpack();
1826 // Checks if there are any temporaries created in the given expression for which drop order
1828 fn temporaries_need_ordered_drop(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1829 struct V<'a, 'tcx> {
1830 cx: &'a LateContext<'tcx>,
1833 impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
1834 type Map = ErasedMap<'tcx>;
1835 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1836 NestedVisitorMap::None
1839 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1841 // Taking the reference of a value leaves a temporary
1842 // e.g. In `&String::new()` the string is a temporary value.
1843 // Remaining fields are temporary values
1844 // e.g. In `(String::new(), 0).1` the string is a temporary value.
1845 ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
1846 if !matches!(expr.kind, ExprKind::Path(_)) {
1847 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
1850 self.visit_expr(expr);
1854 // the base type is alway taken by reference.
1855 // e.g. In `(vec![0])[0]` the vector is a temporary value.
1856 ExprKind::Index(base, index) => {
1857 if !matches!(base.kind, ExprKind::Path(_)) {
1858 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
1861 self.visit_expr(base);
1864 self.visit_expr(index);
1866 // Method calls can take self by reference.
1867 // e.g. In `String::new().len()` the string is a temporary value.
1868 ExprKind::MethodCall(_, _, [self_arg, args @ ..], _) => {
1869 if !matches!(self_arg.kind, ExprKind::Path(_)) {
1870 let self_by_ref = self
1873 .type_dependent_def_id(expr.hir_id)
1874 .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
1876 && type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg))
1880 self.visit_expr(self_arg);
1883 args.iter().for_each(|arg| self.visit_expr(arg));
1885 // Either explicitly drops values, or changes control flow.
1886 ExprKind::DropTemps(_)
1888 | ExprKind::Break(..)
1889 | ExprKind::Yield(..)
1890 | ExprKind::Block(Block { expr: None, .. }, _)
1891 | ExprKind::Loop(..) => (),
1893 // Only consider the final expression.
1894 ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
1896 _ => walk_expr(self, expr),
1901 let mut v = V { cx, res: false };
1906 fn find_sugg_for_if_let<'tcx>(
1907 cx: &LateContext<'tcx>,
1908 expr: &'tcx Expr<'_>,
1909 op: &'tcx Expr<'tcx>,
1911 keyword: &'static str,
1914 // also look inside refs
1915 let mut kind = &arm.pat.kind;
1916 // if we have &None for example, peel it so we can detect "if let None = x"
1917 if let PatKind::Ref(inner, _mutability) = kind {
1920 let op_ty = cx.typeck_results().expr_ty(op);
1921 // Determine which function should be used, and the type contained by the corresponding
1923 let (good_method, inner_ty) = match kind {
1924 PatKind::TupleStruct(ref path, [sub_pat], _) => {
1925 if let PatKind::Wild = sub_pat.kind {
1926 if is_lang_ctor(cx, path, ResultOk) {
1927 ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
1928 } else if is_lang_ctor(cx, path, ResultErr) {
1929 ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
1930 } else if is_lang_ctor(cx, path, OptionSome) {
1931 ("is_some()", op_ty)
1932 } else if is_lang_ctor(cx, path, PollReady) {
1933 ("is_ready()", op_ty)
1934 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V4) {
1935 ("is_ipv4()", op_ty)
1936 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V6) {
1937 ("is_ipv6()", op_ty)
1945 PatKind::Path(ref path) => {
1946 let method = if is_lang_ctor(cx, path, OptionNone) {
1948 } else if is_lang_ctor(cx, path, PollPending) {
1953 // `None` and `Pending` don't have an inner type.
1954 (method, cx.tcx.types.unit)
1959 // If this is the last expression in a block or there is an else clause then the whole
1960 // type needs to be considered, not just the inner type of the branch being matched on.
1961 // Note the last expression in a block is dropped after all local bindings.
1962 let check_ty = if has_else
1963 || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
1970 // All temporaries created in the scrutinee expression are dropped at the same time as the
1971 // scrutinee would be, so they have to be considered as well.
1972 // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
1973 // for the duration if body.
1974 let needs_drop = type_needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, op);
1976 // check that `while_let_on_iterator` lint does not trigger
1978 if keyword == "while";
1979 if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1980 if method_path.ident.name == sym::next;
1981 if is_trait_method(cx, op, sym::Iterator);
1987 let result_expr = match &op.kind {
1988 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1993 REDUNDANT_PATTERN_MATCHING,
1995 &format!("redundant pattern matching, consider using `{}`", good_method),
1997 // while let ... = ... { ... }
1998 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1999 let expr_span = expr.span;
2001 // while let ... = ... { ... }
2003 let op_span = result_expr.span.source_callsite();
2005 // while let ... = ... { ... }
2006 // ^^^^^^^^^^^^^^^^^^^
2007 let span = expr_span.until(op_span.shrink_to_hi());
2009 let mut app = if needs_drop {
2010 Applicability::MaybeIncorrect
2012 Applicability::MachineApplicable
2014 let sugg = snippet_with_applicability(cx, op_span, "_", &mut app);
2016 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
2019 diag.note("this will change drop order of the result, as well as all temporaries");
2020 diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
2026 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
2027 if arms.len() == 2 {
2028 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
2030 let found_good_method = match node_pair {
2032 PatKind::TupleStruct(ref path_left, patterns_left, _),
2033 PatKind::TupleStruct(ref path_right, patterns_right, _),
2034 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
2035 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
2036 find_good_method_for_match(
2047 find_good_method_for_match(
2062 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
2063 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
2064 if patterns.len() == 1 =>
2066 if let PatKind::Wild = patterns[0].kind {
2067 find_good_method_for_match(
2072 &paths::OPTION_SOME,
2073 &paths::OPTION_NONE,
2078 find_good_method_for_match(
2084 &paths::POLL_PENDING,
2096 if let Some(good_method) = found_good_method {
2097 let span = expr.span.to(op.span);
2098 let result_expr = match &op.kind {
2099 ExprKind::AddrOf(_, _, borrowed) => borrowed,
2104 REDUNDANT_PATTERN_MATCHING,
2106 &format!("redundant pattern matching, consider using `{}`", good_method),
2108 diag.span_suggestion(
2111 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
2112 Applicability::MaybeIncorrect, // snippet
2120 #[allow(clippy::too_many_arguments)]
2121 fn find_good_method_for_match<'a>(
2122 cx: &LateContext<'_>,
2124 path_left: &QPath<'_>,
2125 path_right: &QPath<'_>,
2126 expected_left: &[&str],
2127 expected_right: &[&str],
2128 should_be_left: &'a str,
2129 should_be_right: &'a str,
2130 ) -> Option<&'a str> {
2131 let body_node_pair = if is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_left)
2132 && is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_right)
2134 (&(*arms[0].body).kind, &(*arms[1].body).kind)
2135 } else if is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_left)
2136 && is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_right)
2138 (&(*arms[1].body).kind, &(*arms[0].body).kind)
2143 match body_node_pair {
2144 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
2145 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
2146 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
2155 fn test_overlapping() {
2156 use rustc_span::source_map::DUMMY_SP;
2158 let sp = |s, e| SpannedRange {
2163 assert_eq!(None, overlapping::<u8>(&[]));
2164 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
2167 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
2172 sp(1, Bound::Included(4)),
2173 sp(5, Bound::Included(6)),
2174 sp(10, Bound::Included(11))
2178 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
2179 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
2182 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
2184 sp(1, Bound::Included(4)),
2185 sp(5, Bound::Included(6)),
2186 sp(6, Bound::Included(11))
2191 /// Implementation of `MATCH_SAME_ARMS`.
2192 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
2193 if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
2194 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
2195 let mut h = SpanlessHash::new(cx);
2196 h.hash_expr(arm.body);
2200 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
2201 let min_index = usize::min(lindex, rindex);
2202 let max_index = usize::max(lindex, rindex);
2204 let mut local_map: HirIdMap<HirId> = HirIdMap::default();
2205 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
2207 if let Some(a_id) = path_to_local(a);
2208 if let Some(b_id) = path_to_local(b);
2209 let entry = match local_map.entry(a_id) {
2210 Entry::Vacant(entry) => entry,
2211 // check if using the same bindings as before
2212 Entry::Occupied(entry) => return *entry.get() == b_id,
2214 // the names technically don't have to match; this makes the lint more conservative
2215 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2216 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2217 if pat_contains_local(lhs.pat, a_id);
2218 if pat_contains_local(rhs.pat, b_id);
2227 // Arms with a guard are ignored, those can’t always be merged together
2228 // This is also the case for arms in-between each there is an arm with a guard
2229 (min_index..=max_index).all(|index| arms[index].guard.is_none())
2230 && SpanlessEq::new(cx)
2231 .expr_fallback(eq_fallback)
2232 .eq_expr(lhs.body, rhs.body)
2233 // these checks could be removed to allow unused bindings
2234 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2235 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2238 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2239 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2244 "this `match` has identical arm bodies",
2246 diag.span_note(i.body.span, "same as this");
2248 // Note: this does not use `span_suggestion` on purpose:
2249 // there is no clean way
2250 // to remove the other arm. Building a span and suggest to replace it to ""
2251 // makes an even more confusing error message. Also in order not to make up a
2252 // span for the whole pattern, the suggestion is only shown when there is only
2253 // one pattern. The user should know about `|` if they are already using it…
2255 let lhs = snippet(cx, i.pat.span, "<pat1>");
2256 let rhs = snippet(cx, j.pat.span, "<pat2>");
2258 if let PatKind::Wild = j.pat.kind {
2259 // if the last arm is _, then i could be integrated into _
2260 // note that i.pat cannot be _, because that would mean that we're
2261 // hiding all the subsequent arms, and rust won't compile
2265 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2270 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs,))
2271 .help("...or consider changing the match arm bodies");
2279 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2280 let mut result = false;
2281 pat.walk_short(|p| {
2282 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2288 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2289 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2290 let mut result = true;
2291 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2292 result && ids.is_empty()