1 use crate::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_allowed, is_expn_of, is_lang_ctor, is_refutable, is_wild, meets_msrv, path_to_local,
11 path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks, strip_pat_refs,
13 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
14 use if_chain::if_chain;
15 use rustc_ast::ast::LitKind;
16 use rustc_errors::Applicability;
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::LangItem::{OptionNone, OptionSome};
20 self as hir, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource,
21 Mutability, Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
23 use rustc_hir::{HirIdMap, HirIdSet};
24 use rustc_lint::{LateContext, LateLintPass, LintContext};
25 use rustc_middle::lint::in_external_macro;
26 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
27 use rustc_semver::RustcVersion;
28 use rustc_session::{declare_tool_lint, impl_lint_pass};
29 use rustc_span::source_map::{Span, Spanned};
31 use std::cmp::Ordering;
32 use std::collections::hash_map::Entry;
36 declare_clippy_lint! {
37 /// **What it does:** Checks for matches with a single arm where an `if let`
38 /// will usually suffice.
40 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
42 /// **Known problems:** None.
46 /// # fn bar(stool: &str) {}
47 /// # let x = Some("abc");
50 /// Some(ref foo) => bar(foo),
55 /// if let Some(ref foo) = x {
61 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
64 declare_clippy_lint! {
65 /// **What it does:** Checks for matches with two arms where an `if let else` will
68 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
70 /// **Known problems:** Personal style preferences may differ.
77 /// # fn bar(foo: &usize) {}
78 /// # let other_ref: usize = 1;
79 /// # let x: Option<&usize> = Some(&1);
81 /// Some(ref foo) => bar(foo),
82 /// _ => bar(&other_ref),
86 /// Using `if let` with `else`:
89 /// # fn bar(foo: &usize) {}
90 /// # let other_ref: usize = 1;
91 /// # let x: Option<&usize> = Some(&1);
92 /// if let Some(ref foo) = x {
98 pub SINGLE_MATCH_ELSE,
100 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
103 declare_clippy_lint! {
104 /// **What it does:** Checks for matches where all arms match a reference,
105 /// suggesting to remove the reference and deref the matched expression
106 /// instead. It also checks for `if let &foo = bar` blocks.
108 /// **Why is this bad?** It just makes the code less readable. That reference
109 /// destructuring adds nothing to the code.
111 /// **Known problems:** None.
117 /// &A(ref y) => foo(y),
124 /// A(ref y) => foo(y),
131 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
134 declare_clippy_lint! {
135 /// **What it does:** Checks for matches where match expression is a `bool`. It
136 /// suggests to replace the expression with an `if...else` block.
138 /// **Why is this bad?** It makes the code less readable.
140 /// **Known problems:** None.
146 /// let condition: bool = true;
147 /// match condition {
152 /// Use if/else instead:
156 /// let condition: bool = true;
165 "a `match` on a boolean expression instead of an `if..else` block"
168 declare_clippy_lint! {
169 /// **What it does:** Checks for overlapping match arms.
171 /// **Why is this bad?** It is likely to be an error and if not, makes the code
174 /// **Known problems:** None.
180 /// 1...10 => println!("1 ... 10"),
181 /// 5...15 => println!("5 ... 15"),
185 pub MATCH_OVERLAPPING_ARM,
187 "a `match` with overlapping arms"
190 declare_clippy_lint! {
191 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
192 /// and take drastic actions like `panic!`.
194 /// **Why is this bad?** It is generally a bad practice, similar to
195 /// catching all exceptions in java with `catch(Exception)`
197 /// **Known problems:** None.
201 /// let x: Result<i32, &str> = Ok(3);
203 /// Ok(_) => println!("ok"),
204 /// Err(_) => panic!("err"),
207 pub MATCH_WILD_ERR_ARM,
209 "a `match` with `Err(_)` arm and take drastic actions"
212 declare_clippy_lint! {
213 /// **What it does:** Checks for match which is used to add a reference to an
216 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
218 /// **Known problems:** None.
222 /// let x: Option<()> = None;
225 /// let r: Option<&()> = match x {
227 /// Some(ref v) => Some(v),
231 /// let r: Option<&()> = x.as_ref();
235 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
238 declare_clippy_lint! {
239 /// **What it does:** Checks for wildcard enum matches using `_`.
241 /// **Why is this bad?** New enum variants added by library updates can be missed.
243 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
244 /// variants, and also may not use correct path to enum if it's not present in the current scope.
248 /// # enum Foo { A(usize), B(usize) }
249 /// # let x = Foo::B(1);
262 pub WILDCARD_ENUM_MATCH_ARM,
264 "a wildcard enum match arm using `_`"
267 declare_clippy_lint! {
268 /// **What it does:** Checks for wildcard enum matches for a single variant.
270 /// **Why is this bad?** New enum variants added by library updates can be missed.
272 /// **Known problems:** Suggested replacements may not use correct path to enum
273 /// if it's not present in the current scope.
278 /// # enum Foo { A, B, C }
279 /// # let x = Foo::B;
294 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
296 "a wildcard enum match for a single variant"
299 declare_clippy_lint! {
300 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
302 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
303 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
305 /// **Known problems:** None.
321 pub WILDCARD_IN_OR_PATTERNS,
323 "a wildcard pattern used with others patterns in same match arm"
326 declare_clippy_lint! {
327 /// **What it does:** Checks for matches being used to destructure a single-variant enum
328 /// or tuple struct where a `let` will suffice.
330 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
332 /// **Known problems:** None.
340 /// let wrapper = Wrapper::Data(42);
342 /// let data = match wrapper {
343 /// Wrapper::Data(i) => i,
347 /// The correct use would be:
353 /// let wrapper = Wrapper::Data(42);
354 /// let Wrapper::Data(data) = wrapper;
356 pub INFALLIBLE_DESTRUCTURING_MATCH,
358 "a `match` statement with a single infallible arm instead of a `let`"
361 declare_clippy_lint! {
362 /// **What it does:** Checks for useless match that binds to only one value.
364 /// **Why is this bad?** Readability and needless complexity.
366 /// **Known problems:** Suggested replacements may be incorrect when `match`
367 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
382 /// let (c, d) = (a, b);
384 pub MATCH_SINGLE_BINDING,
386 "a match with a single binding instead of using `let` statement"
389 declare_clippy_lint! {
390 /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
392 /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
393 /// matching all enum variants explicitly.
395 /// **Known problems:** None.
399 /// # struct A { a: i32 }
400 /// let a = A { a: 5 };
404 /// A { a: 5, .. } => {},
410 /// A { a: 5 } => {},
414 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
416 "a match on a struct that binds all fields but still uses the wildcard pattern"
419 declare_clippy_lint! {
420 /// **What it does:** Lint for redundant pattern matching over `Result`, `Option`,
421 /// `std::task::Poll` or `std::net::IpAddr`
423 /// **Why is this bad?** It's more concise and clear to just use the proper
426 /// **Known problems:** None.
431 /// # use std::task::Poll;
432 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
433 /// if let Ok(_) = Ok::<i32, i32>(42) {}
434 /// if let Err(_) = Err::<i32, i32>(42) {}
435 /// if let None = None::<()> {}
436 /// if let Some(_) = Some(42) {}
437 /// if let Poll::Pending = Poll::Pending::<()> {}
438 /// if let Poll::Ready(_) = Poll::Ready(42) {}
439 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
440 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
441 /// match Ok::<i32, i32>(42) {
447 /// The more idiomatic use would be:
450 /// # use std::task::Poll;
451 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
452 /// if Ok::<i32, i32>(42).is_ok() {}
453 /// if Err::<i32, i32>(42).is_err() {}
454 /// if None::<()>.is_none() {}
455 /// if Some(42).is_some() {}
456 /// if Poll::Pending::<()>.is_pending() {}
457 /// if Poll::Ready(42).is_ready() {}
458 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
459 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
460 /// Ok::<i32, i32>(42).is_ok();
462 pub REDUNDANT_PATTERN_MATCHING,
464 "use the proper utility function avoiding an `if let`"
467 declare_clippy_lint! {
468 /// **What it does:** Checks for `match` or `if let` expressions producing a
469 /// `bool` that could be written using `matches!`
471 /// **Why is this bad?** Readability and needless complexity.
473 /// **Known problems:** This lint falsely triggers, if there are arms with
474 /// `cfg` attributes that remove an arm evaluating to `false`.
481 /// let a = match x {
486 /// let a = if let Some(0) = x {
493 /// let a = matches!(x, Some(0));
495 pub MATCH_LIKE_MATCHES_MACRO,
497 "a match that could be written with the matches! macro"
500 declare_clippy_lint! {
501 /// **What it does:** Checks for `match` with identical arm bodies.
503 /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
504 /// are the same on purpose, you can factor them
505 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
507 /// **Known problems:** False positive possible with order dependent `match`
509 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
516 /// Baz => bar(), // <= oops
520 /// This should probably be
525 /// Baz => baz(), // <= fixed
529 /// or if the original code was not a typo:
532 /// Bar | Baz => bar(), // <= shows the intent better
538 "`match` with identical arm bodies"
543 msrv: Option<RustcVersion>,
544 infallible_destructuring_match_linted: bool,
549 pub fn new(msrv: Option<RustcVersion>) -> Self {
557 impl_lint_pass!(Matches => [
562 MATCH_OVERLAPPING_ARM,
565 WILDCARD_ENUM_MATCH_ARM,
566 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
567 WILDCARD_IN_OR_PATTERNS,
568 MATCH_SINGLE_BINDING,
569 INFALLIBLE_DESTRUCTURING_MATCH,
570 REST_PAT_IN_FULLY_BOUND_STRUCTS,
571 REDUNDANT_PATTERN_MATCHING,
572 MATCH_LIKE_MATCHES_MACRO,
576 const MATCH_LIKE_MATCHES_MACRO_MSRV: RustcVersion = RustcVersion::new(1, 42, 0);
578 impl<'tcx> LateLintPass<'tcx> for Matches {
579 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
580 if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
584 redundant_pattern_match::check(cx, expr);
586 if meets_msrv(self.msrv.as_ref(), &MATCH_LIKE_MATCHES_MACRO_MSRV) {
587 if !check_match_like_matches(cx, expr) {
588 lint_match_arms(cx, expr);
591 lint_match_arms(cx, expr);
594 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
595 check_single_match(cx, ex, arms, expr);
596 check_match_bool(cx, ex, arms, expr);
597 check_overlapping_arms(cx, ex, arms);
598 check_wild_err_arm(cx, ex, arms);
599 check_wild_enum_match(cx, ex, arms);
600 check_match_as_ref(cx, ex, arms, expr);
601 check_wild_in_or_pats(cx, arms);
603 if self.infallible_destructuring_match_linted {
604 self.infallible_destructuring_match_linted = false;
606 check_match_single_binding(cx, ex, arms, expr);
609 if let ExprKind::Match(ex, arms, _) = expr.kind {
610 check_match_ref_pats(cx, ex, arms, expr);
614 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
616 if !in_external_macro(cx.sess(), local.span);
617 if !in_macro(local.span);
618 if let Some(expr) = local.init;
619 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
620 if arms.len() == 1 && arms[0].guard.is_none();
621 if let PatKind::TupleStruct(
622 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
624 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(args[0]).kind;
625 let body = remove_blocks(arms[0].body);
626 if path_to_local_id(body, arg);
629 let mut applicability = Applicability::MachineApplicable;
630 self.infallible_destructuring_match_linted = true;
633 INFALLIBLE_DESTRUCTURING_MATCH,
635 "you seem to be trying to use `match` to destructure a single infallible pattern. \
636 Consider using `let`",
640 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
641 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
642 snippet_with_applicability(cx, target.span, "..", &mut applicability),
650 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
652 if !in_external_macro(cx.sess(), pat.span);
653 if !in_macro(pat.span);
654 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
655 if let Some(def_id) = path.res.opt_def_id();
656 let ty = cx.tcx.type_of(def_id);
657 if let ty::Adt(def, _) = ty.kind();
658 if def.is_struct() || def.is_union();
659 if fields.len() == def.non_enum_variant().fields.len();
664 REST_PAT_IN_FULLY_BOUND_STRUCTS,
666 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
668 "consider removing `..` from this binding",
674 extract_msrv_attr!(LateContext);
678 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
679 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
680 if in_macro(expr.span) {
681 // Don't lint match expressions present in
682 // macro_rules! block
685 if let PatKind::Or(..) = arms[0].pat.kind {
686 // don't lint for or patterns for now, this makes
687 // the lint noisy in unnecessary situations
690 let els = arms[1].body;
691 let els = if is_unit_expr(remove_blocks(els)) {
693 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
694 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
695 // single statement/expr "else" block, don't lint
698 // block with 2+ statements or 1 expr and 1+ statement
701 // not a block, don't lint
705 let ty = cx.typeck_results().expr_ty(ex);
706 if *ty.kind() != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
707 check_single_match_single_pattern(cx, ex, arms, expr, els);
708 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
713 fn check_single_match_single_pattern(
714 cx: &LateContext<'_>,
718 els: Option<&Expr<'_>>,
720 if is_wild(&arms[1].pat) {
721 report_single_match_single_pattern(cx, ex, arms, expr, els);
725 fn report_single_match_single_pattern(
726 cx: &LateContext<'_>,
730 els: Option<&Expr<'_>>,
732 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
733 let els_str = els.map_or(String::new(), |els| {
734 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
737 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
738 let (msg, sugg) = if_chain! {
739 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
740 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
741 if let Some(trait_id) = cx.tcx.lang_items().structural_peq_trait();
742 if ty.is_integral() || ty.is_char() || ty.is_str() || implements_trait(cx, ty, trait_id, &[]);
744 // scrutinee derives PartialEq and the pattern is a constant.
745 let pat_ref_count = match pat.kind {
746 // string literals are already a reference.
747 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
750 // References are only implicitly added to the pattern, so no overflow here.
751 // e.g. will work: match &Some(_) { Some(_) => () }
752 // will not: match Some(_) { &Some(_) => () }
753 let ref_count_diff = ty_ref_count - pat_ref_count;
755 // Try to remove address of expressions first.
756 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
757 let ref_count_diff = ref_count_diff - removed;
759 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
761 "if {} == {}{} {}{}",
762 snippet(cx, ex.span, ".."),
763 // PartialEq for different reference counts may not exist.
764 "&".repeat(ref_count_diff),
765 snippet(cx, arms[0].pat.span, ".."),
766 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
771 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
773 "if let {} = {} {}{}",
774 snippet(cx, arms[0].pat.span, ".."),
775 snippet(cx, ex.span, ".."),
776 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
790 Applicability::HasPlaceholders,
794 fn check_single_match_opt_like(
795 cx: &LateContext<'_>,
800 els: Option<&Expr<'_>>,
802 // list of candidate `Enum`s we know will never get any more members
804 (&paths::COW, "Borrowed"),
805 (&paths::COW, "Cow::Borrowed"),
806 (&paths::COW, "Cow::Owned"),
807 (&paths::COW, "Owned"),
808 (&paths::OPTION, "None"),
809 (&paths::RESULT, "Err"),
810 (&paths::RESULT, "Ok"),
813 let path = match arms[1].pat.kind {
814 PatKind::TupleStruct(ref path, inner, _) => {
815 // Contains any non wildcard patterns (e.g., `Err(err)`)?
816 if !inner.iter().all(is_wild) {
819 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
821 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
822 PatKind::Path(ref path) => {
823 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
828 for &(ty_path, pat_path) in candidates {
829 if path == *pat_path && match_type(cx, ty, ty_path) {
830 report_single_match_single_pattern(cx, ex, arms, expr, els);
835 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
836 // Type of expression is `bool`.
837 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
842 "you seem to be trying to match on a boolean expression",
846 let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
847 if let ExprKind::Lit(ref lit) = arm_bool.kind {
849 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
850 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
860 if let Some((true_expr, false_expr)) = exprs {
861 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
862 (false, false) => Some(format!(
864 snippet(cx, ex.span, "b"),
865 expr_block(cx, true_expr, None, "..", Some(expr.span)),
866 expr_block(cx, false_expr, None, "..", Some(expr.span))
868 (false, true) => Some(format!(
870 snippet(cx, ex.span, "b"),
871 expr_block(cx, true_expr, None, "..", Some(expr.span))
874 let test = Sugg::hir(cx, ex, "..");
878 expr_block(cx, false_expr, None, "..", Some(expr.span))
881 (true, true) => None,
884 if let Some(sugg) = sugg {
885 diag.span_suggestion(
887 "consider using an `if`/`else` expression",
889 Applicability::HasPlaceholders,
899 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
900 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
901 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
902 let type_ranges = type_ranges(&ranges);
903 if !type_ranges.is_empty() {
904 if let Some((start, end)) = overlapping(&type_ranges) {
907 MATCH_OVERLAPPING_ARM,
909 "some ranges overlap",
911 "overlaps with this",
918 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
919 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
920 if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
922 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
923 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
924 if path_str == "Err" {
925 let mut matching_wild = inner.iter().any(is_wild);
926 let mut ident_bind_name = String::from("_");
928 // Looking for unused bindings (i.e.: `_e`)
929 for pat in inner.iter() {
930 if let PatKind::Binding(_, id, ident, None) = pat.kind {
931 if ident.as_str().starts_with('_')
932 && !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
934 ident_bind_name = (&ident.name.as_str()).to_string();
935 matching_wild = true;
942 if let ExprKind::Block(block, _) = arm.body.kind;
943 if is_panic_block(block);
945 // `Err(_)` or `Err(_e)` arm with `panic!` found
946 span_lint_and_note(cx,
949 &format!("`Err({})` matches all errors", &ident_bind_name),
951 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
961 enum CommonPrefixSearcher<'a> {
963 Path(&'a [PathSegment<'a>]),
966 impl CommonPrefixSearcher<'a> {
967 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
969 [path @ .., _] => self.with_prefix(path),
974 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
976 Self::None => *self = Self::Path(path),
977 Self::Path(self_path)
980 .map(|p| p.ident.name)
981 .eq(self_path.iter().map(|p| p.ident.name)) => {},
982 Self::Path(_) => *self = Self::Mixed,
988 fn is_doc_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
989 let attrs = cx.tcx.get_attrs(variant_def.def_id);
990 clippy_utils::attrs::is_doc_hidden(attrs)
993 #[allow(clippy::too_many_lines)]
994 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
995 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
996 let adt_def = match ty.kind() {
999 && !(is_type_diagnostic_item(cx, ty, sym::option_type)
1000 || is_type_diagnostic_item(cx, ty, sym::result_type)) =>
1007 // First pass - check for violation, but don't do much book-keeping because this is hopefully
1008 // the uncommon case, and the book-keeping is slightly expensive.
1009 let mut wildcard_span = None;
1010 let mut wildcard_ident = None;
1011 let mut has_non_wild = false;
1013 match peel_hir_pat_refs(arm.pat).0.kind {
1014 PatKind::Wild => wildcard_span = Some(arm.pat.span),
1015 PatKind::Binding(_, _, ident, None) => {
1016 wildcard_span = Some(arm.pat.span);
1017 wildcard_ident = Some(ident);
1019 _ => has_non_wild = true,
1022 let wildcard_span = match wildcard_span {
1023 Some(x) if has_non_wild => x,
1027 // Accumulate the variants which should be put in place of the wildcard because they're not
1029 let mut missing_variants: Vec<_> = adt_def.variants.iter().collect();
1031 let mut path_prefix = CommonPrefixSearcher::None;
1033 // Guards mean that this case probably isn't exhaustively covered. Technically
1034 // this is incorrect, as we should really check whether each variant is exhaustively
1035 // covered by the set of guards that cover it, but that's really hard to do.
1036 recurse_or_patterns(arm.pat, |pat| {
1037 let path = match &peel_hir_pat_refs(pat).0.kind {
1038 PatKind::Path(path) => {
1039 #[allow(clippy::match_same_arms)]
1040 let id = match cx.qpath_res(path, pat.hir_id) {
1041 Res::Def(DefKind::Const | DefKind::ConstParam | DefKind::AnonConst, _) => return,
1042 Res::Def(_, id) => id,
1045 if arm.guard.is_none() {
1046 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1050 PatKind::TupleStruct(path, patterns, ..) => {
1051 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1052 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1053 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1058 PatKind::Struct(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.pat)) {
1061 missing_variants.retain(|e| e.def_id != id);
1069 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1070 QPath::TypeRelative(
1072 kind: TyKind::Path(QPath::Resolved(_, path)),
1076 ) => path_prefix.with_prefix(path.segments),
1082 let format_suggestion = |variant: &VariantDef| {
1085 if let Some(ident) = wildcard_ident {
1086 format!("{} @ ", ident.name)
1090 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1091 let mut s = String::new();
1092 for seg in path_prefix {
1093 s.push_str(&seg.ident.as_str());
1098 let mut s = cx.tcx.def_path_str(adt_def.did);
1103 match variant.ctor_kind {
1104 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1105 CtorKind::Fn => "(..)",
1106 CtorKind::Const => "",
1107 CtorKind::Fictive => "{ .. }",
1112 match missing_variants.as_slice() {
1114 [x] if !adt_def.is_variant_list_non_exhaustive() && !is_doc_hidden(cx, x) => span_lint_and_sugg(
1116 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1118 "wildcard matches only a single variant and will also match any future added variants",
1120 format_suggestion(x),
1121 Applicability::MaybeIncorrect,
1124 let mut suggestions: Vec<_> = variants.iter().cloned().map(format_suggestion).collect();
1125 let message = if adt_def.is_variant_list_non_exhaustive() {
1126 suggestions.push("_".into());
1127 "wildcard matches known variants and will also match future added variants"
1129 "wildcard match will also match any future added variants"
1134 WILDCARD_ENUM_MATCH_ARM,
1138 suggestions.join(" | "),
1139 Applicability::MaybeIncorrect,
1145 // If the block contains only a `panic!` macro (as expression or statement)
1146 fn is_panic_block(block: &Block<'_>) -> bool {
1147 match (&block.expr, block.stmts.len(), block.stmts.first()) {
1148 (&Some(exp), 0, _) => is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none(),
1149 (&None, 1, Some(stmt)) => {
1150 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1156 fn check_match_ref_pats(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1157 if has_only_ref_pats(arms) {
1158 let mut suggs = Vec::with_capacity(arms.len() + 1);
1159 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1160 let span = ex.span.source_callsite();
1161 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1163 "you don't need to add `&` to both the expression and the patterns",
1167 let span = ex.span.source_callsite();
1168 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1170 "you don't need to add `&` to all patterns",
1171 "instead of prefixing all patterns with `&`, you can dereference the expression",
1175 suggs.extend(arms.iter().filter_map(|a| {
1176 if let PatKind::Ref(refp, _) = a.pat.kind {
1177 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
1183 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1184 if !expr.span.from_expansion() {
1185 multispan_sugg(diag, msg, suggs);
1191 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1192 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1193 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1194 is_ref_some_arm(cx, &arms[1])
1195 } else if is_none_arm(cx, &arms[1]) {
1196 is_ref_some_arm(cx, &arms[0])
1200 if let Some(rb) = arm_ref {
1201 let suggestion = if rb == BindingAnnotation::Ref {
1207 let output_ty = cx.typeck_results().expr_ty(expr);
1208 let input_ty = cx.typeck_results().expr_ty(ex);
1210 let cast = if_chain! {
1211 if let ty::Adt(_, substs) = input_ty.kind();
1212 let input_ty = substs.type_at(0);
1213 if let ty::Adt(_, substs) = output_ty.kind();
1214 let output_ty = substs.type_at(0);
1215 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1216 if input_ty != output_ty;
1224 let mut applicability = Applicability::MachineApplicable;
1229 &format!("use `{}()` instead", suggestion),
1233 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1243 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1245 if let PatKind::Or(fields) = arm.pat.kind {
1246 // look for multiple fields in this arm that contains at least one Wild pattern
1247 if fields.len() > 1 && fields.iter().any(is_wild) {
1250 WILDCARD_IN_OR_PATTERNS,
1252 "wildcard pattern covers any other pattern as it will match anyway",
1254 "consider handling `_` separately",
1261 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1262 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1263 if let ExprKind::Match(ex, arms, ref match_source) = &expr.kind {
1264 match match_source {
1265 MatchSource::Normal => find_matches_sugg(cx, ex, arms, expr, false),
1266 MatchSource::IfLetDesugar { .. } => find_matches_sugg(cx, ex, arms, expr, true),
1274 /// Lint a `match` or desugared `if let` for replacement by `matches!`
1275 fn find_matches_sugg(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>, desugared: bool) -> bool {
1278 if cx.typeck_results().expr_ty(expr).is_bool();
1279 if let Some((b1_arm, b0_arms)) = arms.split_last();
1280 if let Some(b0) = find_bool_lit(&b0_arms[0].body.kind, desugared);
1281 if let Some(b1) = find_bool_lit(&b1_arm.body.kind, desugared);
1282 if is_wild(&b1_arm.pat);
1284 let if_guard = &b0_arms[0].guard;
1285 if if_guard.is_none() || b0_arms.len() == 1;
1286 if cx.tcx.hir().attrs(b0_arms[0].hir_id).is_empty();
1287 if b0_arms[1..].iter()
1289 find_bool_lit(&arm.body.kind, desugared).map_or(false, |b| b == b0) &&
1290 arm.guard.is_none() && cx.tcx.hir().attrs(arm.hir_id).is_empty()
1293 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1294 // evaluated into `false` and so such arms will be stripped before.
1295 let mut applicability = Applicability::MaybeIncorrect;
1297 use itertools::Itertools as _;
1299 .map(|arm| snippet_with_applicability(cx, arm.pat.span, "..", &mut applicability))
1302 let pat_and_guard = if let Some(Guard::If(g)) = if_guard {
1303 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1308 // strip potential borrows (#6503), but only if the type is a reference
1309 let mut ex_new = ex;
1310 if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1311 if let ty::Ref(..) = cx.typeck_results().expr_ty(ex_inner).kind() {
1317 MATCH_LIKE_MATCHES_MACRO,
1319 &format!("{} expression looks like `matches!` macro", if desugared { "if let .. else" } else { "match" }),
1322 "{}matches!({}, {})",
1323 if b0 { "" } else { "!" },
1324 snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1336 /// Extract a `bool` or `{ bool }`
1337 fn find_bool_lit(ex: &ExprKind<'_>, desugared: bool) -> Option<bool> {
1339 ExprKind::Lit(Spanned {
1340 node: LitKind::Bool(b), ..
1350 if let ExprKind::Lit(Spanned {
1351 node: LitKind::Bool(b), ..
1363 #[allow(clippy::too_many_lines)]
1364 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1365 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1370 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1371 // to prevent false positives as there is currently no better way to detect if code was excluded by
1372 // a macro. See PR #6435
1374 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1375 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1376 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1377 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1378 if rest_snippet.contains("=>");
1380 // The code it self contains another thick arrow "=>"
1381 // -> Either another arm or a comment
1386 let matched_vars = ex.span;
1387 let bind_names = arms[0].pat.span;
1388 let match_body = remove_blocks(arms[0].body);
1389 let mut snippet_body = if match_body.span.from_expansion() {
1390 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1392 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1395 // Do we need to add ';' to suggestion ?
1396 match match_body.kind {
1397 ExprKind::Block(block, _) => {
1398 // macro + expr_ty(body) == ()
1399 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1400 snippet_body.push(';');
1404 // expr_ty(body) == ()
1405 if cx.typeck_results().expr_ty(match_body).is_unit() {
1406 snippet_body.push(';');
1411 let mut applicability = Applicability::MaybeIncorrect;
1412 match arms[0].pat.kind {
1413 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1414 // If this match is in a local (`let`) stmt
1415 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1417 parent_let_node.span,
1419 "let {} = {};\n{}let {} = {};",
1420 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1421 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1422 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1423 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1428 // If we are in closure, we need curly braces around suggestion
1429 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1430 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1431 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1432 if let ExprKind::Closure(..) = parent_expr.kind {
1433 cbrace_end = format!("\n{}}}", indent);
1434 // Fix body indent due to the closure
1435 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1436 cbrace_start = format!("{{\n{}", indent);
1439 // If the parent is already an arm, and the body is another match statement,
1440 // we need curly braces around suggestion
1441 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1442 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1443 if let ExprKind::Match(..) = arm.body.kind {
1444 cbrace_end = format!("\n{}}}", indent);
1445 // Fix body indent due to the match
1446 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1447 cbrace_start = format!("{{\n{}", indent);
1453 "{}let {} = {};\n{}{}{}",
1455 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1456 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1465 MATCH_SINGLE_BINDING,
1467 "this match could be written as a `let` statement",
1468 "consider using `let` statement",
1476 MATCH_SINGLE_BINDING,
1478 "this match could be replaced by its body itself",
1479 "consider using the match body instead",
1481 Applicability::MachineApplicable,
1488 /// Returns true if the `ex` match expression is in a local (`let`) statement
1489 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1490 let map = &cx.tcx.hir();
1492 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1493 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1495 return Some(parent_let_expr);
1501 /// Gets all arms that are unbounded `PatRange`s.
1502 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1505 if let Arm { pat, guard: None, .. } = *arm {
1506 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1507 let lhs = match lhs {
1508 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1509 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1511 let rhs = match rhs {
1512 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1513 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1515 let rhs = match range_end {
1516 RangeEnd::Included => Bound::Included(rhs),
1517 RangeEnd::Excluded => Bound::Excluded(rhs),
1519 return Some(SpannedRange {
1525 if let PatKind::Lit(value) = pat.kind {
1526 let value = constant(cx, cx.typeck_results(), value)?.0;
1527 return Some(SpannedRange {
1529 node: (value.clone(), Bound::Included(value)),
1538 #[derive(Debug, Eq, PartialEq)]
1539 pub struct SpannedRange<T> {
1541 pub node: (T, Bound<T>),
1544 type TypedRanges = Vec<SpannedRange<u128>>;
1546 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1547 /// and other types than
1548 /// `Uint` and `Int` probably don't make sense.
1549 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1552 .filter_map(|range| match range.node {
1553 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1555 node: (start, Bound::Included(end)),
1557 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1559 node: (start, Bound::Excluded(end)),
1561 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1563 node: (start, Bound::Unbounded),
1570 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1572 ExprKind::Tup(v) if v.is_empty() => true,
1573 ExprKind::Block(b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1578 // Checks if arm has the form `None => None`
1579 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1580 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1583 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1584 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1586 if let PatKind::TupleStruct(ref qpath, pats, _) = arm.pat.kind;
1587 if is_lang_ctor(cx, qpath, OptionSome);
1588 if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1589 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1590 if let ExprKind::Call(e, args) = remove_blocks(arm.body).kind;
1591 if let ExprKind::Path(ref some_path) = e.kind;
1592 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1593 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1594 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1602 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1607 PatKind::Ref(..) => Some(true), // &-patterns
1608 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1609 _ => None, // any other pattern is not fine
1612 .collect::<Option<Vec<bool>>>();
1613 // look for Some(v) where there's at least one true element
1614 mapped.map_or(false, |v| v.iter().any(|el| *el))
1617 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1621 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1623 Start(T, &'a SpannedRange<T>),
1624 End(Bound<T>, &'a SpannedRange<T>),
1627 impl<'a, T: Copy> Kind<'a, T> {
1628 fn range(&self) -> &'a SpannedRange<T> {
1630 Kind::Start(_, r) | Kind::End(_, r) => r,
1634 fn value(self) -> Bound<T> {
1636 Kind::Start(t, _) => Bound::Included(t),
1637 Kind::End(t, _) => t,
1642 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1643 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1644 Some(self.cmp(other))
1648 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1649 fn cmp(&self, other: &Self) -> Ordering {
1650 match (self.value(), other.value()) {
1651 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1652 // Range patterns cannot be unbounded (yet)
1653 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1654 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1655 Ordering::Equal => Ordering::Greater,
1658 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1659 Ordering::Equal => Ordering::Less,
1666 let mut values = Vec::with_capacity(2 * ranges.len());
1669 values.push(Kind::Start(r.node.0, r));
1670 values.push(Kind::End(r.node.1, r));
1675 for (a, b) in iter::zip(&values, values.iter().skip(1)) {
1677 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1678 if ra.node != rb.node {
1679 return Some((ra, rb));
1682 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1684 // skip if the range `a` is completely included into the range `b`
1685 if let Ordering::Equal | Ordering::Less = a.cmp(b) {
1686 let kind_a = Kind::End(a.range().node.1, a.range());
1687 let kind_b = Kind::End(b.range().node.1, b.range());
1688 if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1692 return Some((a.range(), b.range()));
1700 mod redundant_pattern_match {
1701 use super::REDUNDANT_PATTERN_MATCHING;
1702 use clippy_utils::diagnostics::span_lint_and_then;
1703 use clippy_utils::source::snippet;
1704 use clippy_utils::{is_lang_ctor, is_qpath_def_path, is_trait_method, paths};
1705 use if_chain::if_chain;
1706 use rustc_ast::ast::LitKind;
1707 use rustc_errors::Applicability;
1708 use rustc_hir::LangItem::{OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk};
1709 use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind, QPath};
1710 use rustc_lint::LateContext;
1711 use rustc_span::sym;
1713 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1714 if let ExprKind::Match(op, arms, ref match_source) = &expr.kind {
1715 match match_source {
1716 MatchSource::Normal => find_sugg_for_match(cx, expr, op, arms),
1717 MatchSource::IfLetDesugar { .. } => find_sugg_for_if_let(cx, expr, op, arms, "if"),
1718 MatchSource::WhileLetDesugar => find_sugg_for_if_let(cx, expr, op, arms, "while"),
1724 fn find_sugg_for_if_let<'tcx>(
1725 cx: &LateContext<'tcx>,
1726 expr: &'tcx Expr<'_>,
1729 keyword: &'static str,
1731 // also look inside refs
1732 let mut kind = &arms[0].pat.kind;
1733 // if we have &None for example, peel it so we can detect "if let None = x"
1734 if let PatKind::Ref(inner, _mutability) = kind {
1737 let good_method = match kind {
1738 PatKind::TupleStruct(ref path, [sub_pat], _) => {
1739 if let PatKind::Wild = sub_pat.kind {
1740 if is_lang_ctor(cx, path, ResultOk) {
1742 } else if is_lang_ctor(cx, path, ResultErr) {
1744 } else if is_lang_ctor(cx, path, OptionSome) {
1746 } else if is_lang_ctor(cx, path, PollReady) {
1748 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V4) {
1750 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V6) {
1759 PatKind::Path(ref path) => {
1760 if is_lang_ctor(cx, path, OptionNone) {
1762 } else if is_lang_ctor(cx, path, PollPending) {
1771 // check that `while_let_on_iterator` lint does not trigger
1773 if keyword == "while";
1774 if let ExprKind::MethodCall(method_path, _, _, _) = op.kind;
1775 if method_path.ident.name == sym::next;
1776 if is_trait_method(cx, op, sym::Iterator);
1782 let result_expr = match &op.kind {
1783 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1788 REDUNDANT_PATTERN_MATCHING,
1790 &format!("redundant pattern matching, consider using `{}`", good_method),
1792 // while let ... = ... { ... }
1793 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1794 let expr_span = expr.span;
1796 // while let ... = ... { ... }
1798 let op_span = result_expr.span.source_callsite();
1800 // while let ... = ... { ... }
1801 // ^^^^^^^^^^^^^^^^^^^
1802 let span = expr_span.until(op_span.shrink_to_hi());
1803 diag.span_suggestion(
1806 format!("{} {}.{}", keyword, snippet(cx, op_span, "_"), good_method),
1807 Applicability::MachineApplicable, // snippet
1813 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
1814 if arms.len() == 2 {
1815 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
1817 let found_good_method = match node_pair {
1819 PatKind::TupleStruct(ref path_left, patterns_left, _),
1820 PatKind::TupleStruct(ref path_right, patterns_right, _),
1821 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
1822 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
1823 find_good_method_for_match(
1834 find_good_method_for_match(
1849 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
1850 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
1851 if patterns.len() == 1 =>
1853 if let PatKind::Wild = patterns[0].kind {
1854 find_good_method_for_match(
1859 &paths::OPTION_SOME,
1860 &paths::OPTION_NONE,
1865 find_good_method_for_match(
1871 &paths::POLL_PENDING,
1883 if let Some(good_method) = found_good_method {
1884 let span = expr.span.to(op.span);
1885 let result_expr = match &op.kind {
1886 ExprKind::AddrOf(_, _, borrowed) => borrowed,
1891 REDUNDANT_PATTERN_MATCHING,
1893 &format!("redundant pattern matching, consider using `{}`", good_method),
1895 diag.span_suggestion(
1898 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
1899 Applicability::MaybeIncorrect, // snippet
1907 #[allow(clippy::too_many_arguments)]
1908 fn find_good_method_for_match<'a>(
1909 cx: &LateContext<'_>,
1911 path_left: &QPath<'_>,
1912 path_right: &QPath<'_>,
1913 expected_left: &[&str],
1914 expected_right: &[&str],
1915 should_be_left: &'a str,
1916 should_be_right: &'a str,
1917 ) -> Option<&'a str> {
1918 let body_node_pair = if is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_left)
1919 && is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_right)
1921 (&(*arms[0].body).kind, &(*arms[1].body).kind)
1922 } else if is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_left)
1923 && is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_right)
1925 (&(*arms[1].body).kind, &(*arms[0].body).kind)
1930 match body_node_pair {
1931 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
1932 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
1933 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
1942 fn test_overlapping() {
1943 use rustc_span::source_map::DUMMY_SP;
1945 let sp = |s, e| SpannedRange {
1950 assert_eq!(None, overlapping::<u8>(&[]));
1951 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1954 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1959 sp(1, Bound::Included(4)),
1960 sp(5, Bound::Included(6)),
1961 sp(10, Bound::Included(11))
1965 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1966 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1969 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1971 sp(1, Bound::Included(4)),
1972 sp(5, Bound::Included(6)),
1973 sp(6, Bound::Included(11))
1978 /// Implementation of `MATCH_SAME_ARMS`.
1979 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
1980 if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
1981 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
1982 let mut h = SpanlessHash::new(cx);
1983 h.hash_expr(arm.body);
1987 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
1988 let min_index = usize::min(lindex, rindex);
1989 let max_index = usize::max(lindex, rindex);
1991 let mut local_map: HirIdMap<HirId> = HirIdMap::default();
1992 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
1994 if let Some(a_id) = path_to_local(a);
1995 if let Some(b_id) = path_to_local(b);
1996 let entry = match local_map.entry(a_id) {
1997 Entry::Vacant(entry) => entry,
1998 // check if using the same bindings as before
1999 Entry::Occupied(entry) => return *entry.get() == b_id,
2001 // the names technically don't have to match; this makes the lint more conservative
2002 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2003 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2004 if pat_contains_local(lhs.pat, a_id);
2005 if pat_contains_local(rhs.pat, b_id);
2014 // Arms with a guard are ignored, those can’t always be merged together
2015 // This is also the case for arms in-between each there is an arm with a guard
2016 (min_index..=max_index).all(|index| arms[index].guard.is_none())
2017 && SpanlessEq::new(cx)
2018 .expr_fallback(eq_fallback)
2019 .eq_expr(lhs.body, rhs.body)
2020 // these checks could be removed to allow unused bindings
2021 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2022 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2025 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2026 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2031 "this `match` has identical arm bodies",
2033 diag.span_note(i.body.span, "same as this");
2035 // Note: this does not use `span_suggestion` on purpose:
2036 // there is no clean way
2037 // to remove the other arm. Building a span and suggest to replace it to ""
2038 // makes an even more confusing error message. Also in order not to make up a
2039 // span for the whole pattern, the suggestion is only shown when there is only
2040 // one pattern. The user should know about `|` if they are already using it…
2042 let lhs = snippet(cx, i.pat.span, "<pat1>");
2043 let rhs = snippet(cx, j.pat.span, "<pat2>");
2045 if let PatKind::Wild = j.pat.kind {
2046 // if the last arm is _, then i could be integrated into _
2047 // note that i.pat cannot be _, because that would mean that we're
2048 // hiding all the subsequent arms, and rust won't compile
2052 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2057 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
2065 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2066 let mut result = false;
2067 pat.walk_short(|p| {
2068 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2074 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2075 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2076 let mut result = true;
2077 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2078 result && ids.is_empty()