1 use clippy_utils::consts::{constant, constant_full_int, miri_to_const, FullInt};
2 use clippy_utils::diagnostics::{
3 multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
5 use clippy_utils::macros::{is_panic, root_macro_call};
6 use clippy_utils::source::{expr_block, indent_of, snippet, snippet_block, snippet_opt, snippet_with_applicability};
7 use clippy_utils::sugg::Sugg;
8 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type, peel_mid_ty_refs};
9 use clippy_utils::visitors::is_local_used;
11 get_parent_expr, is_lang_ctor, is_lint_allowed, is_refutable, is_unit_expr, is_wild, meets_msrv, msrvs,
12 path_to_local, path_to_local_id, peel_blocks, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns,
15 use clippy_utils::{higher, peel_blocks_with_stmt};
16 use clippy_utils::{paths, search_same, SpanlessEq, SpanlessHash};
17 use core::iter::{once, ExactSizeIterator};
18 use if_chain::if_chain;
19 use rustc_ast::ast::{Attribute, LitKind};
20 use rustc_errors::Applicability;
21 use rustc_hir::def::{CtorKind, DefKind, Res};
22 use rustc_hir::LangItem::{OptionNone, OptionSome};
24 self as hir, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Guard, HirId, Local, MatchSource,
25 Mutability, Node, Pat, PatKind, PathSegment, QPath, RangeEnd, TyKind,
27 use rustc_hir::{HirIdMap, HirIdSet};
28 use rustc_lint::{LateContext, LateLintPass};
29 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
30 use rustc_semver::RustcVersion;
31 use rustc_session::{declare_tool_lint, impl_lint_pass};
32 use rustc_span::source_map::{Span, Spanned};
34 use std::cmp::Ordering;
35 use std::collections::hash_map::Entry;
37 declare_clippy_lint! {
39 /// Checks for matches with a single arm where an `if let`
40 /// will usually suffice.
42 /// ### Why is this bad?
43 /// Just readability – `if let` nests less than a `match`.
47 /// # fn bar(stool: &str) {}
48 /// # let x = Some("abc");
51 /// Some(ref foo) => bar(foo),
56 /// if let Some(ref foo) = x {
60 #[clippy::version = "pre 1.29.0"]
63 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
66 declare_clippy_lint! {
68 /// Checks for matches with two arms where an `if let else` will
71 /// ### Why is this bad?
72 /// Just readability – `if let` nests less than a `match`.
74 /// ### Known problems
75 /// Personal style preferences may differ.
81 /// # fn bar(foo: &usize) {}
82 /// # let other_ref: usize = 1;
83 /// # let x: Option<&usize> = Some(&1);
85 /// Some(ref foo) => bar(foo),
86 /// _ => bar(&other_ref),
90 /// Using `if let` with `else`:
93 /// # fn bar(foo: &usize) {}
94 /// # let other_ref: usize = 1;
95 /// # let x: Option<&usize> = Some(&1);
96 /// if let Some(ref foo) = x {
102 #[clippy::version = "pre 1.29.0"]
103 pub SINGLE_MATCH_ELSE,
105 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
108 declare_clippy_lint! {
110 /// Checks for matches where all arms match a reference,
111 /// suggesting to remove the reference and deref the matched expression
112 /// instead. It also checks for `if let &foo = bar` blocks.
114 /// ### Why is this bad?
115 /// It just makes the code less readable. That reference
116 /// destructuring adds nothing to the code.
122 /// &A(ref y) => foo(y),
129 /// A(ref y) => foo(y),
134 #[clippy::version = "pre 1.29.0"]
137 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
140 declare_clippy_lint! {
142 /// Checks for matches where match expression is a `bool`. It
143 /// suggests to replace the expression with an `if...else` block.
145 /// ### Why is this bad?
146 /// It makes the code less readable.
152 /// let condition: bool = true;
153 /// match condition {
158 /// Use if/else instead:
162 /// let condition: bool = true;
169 #[clippy::version = "pre 1.29.0"]
172 "a `match` on a boolean expression instead of an `if..else` block"
175 declare_clippy_lint! {
177 /// Checks for overlapping match arms.
179 /// ### Why is this bad?
180 /// It is likely to be an error and if not, makes the code
187 /// 1..=10 => println!("1 ... 10"),
188 /// 5..=15 => println!("5 ... 15"),
192 #[clippy::version = "pre 1.29.0"]
193 pub MATCH_OVERLAPPING_ARM,
195 "a `match` with overlapping arms"
198 declare_clippy_lint! {
200 /// Checks for arm which matches all errors with `Err(_)`
201 /// and take drastic actions like `panic!`.
203 /// ### Why is this bad?
204 /// It is generally a bad practice, similar to
205 /// catching all exceptions in java with `catch(Exception)`
209 /// let x: Result<i32, &str> = Ok(3);
211 /// Ok(_) => println!("ok"),
212 /// Err(_) => panic!("err"),
215 #[clippy::version = "pre 1.29.0"]
216 pub MATCH_WILD_ERR_ARM,
218 "a `match` with `Err(_)` arm and take drastic actions"
221 declare_clippy_lint! {
223 /// Checks for match which is used to add a reference to an
226 /// ### Why is this bad?
227 /// Using `as_ref()` or `as_mut()` instead is shorter.
231 /// let x: Option<()> = None;
234 /// let r: Option<&()> = match x {
236 /// Some(ref v) => Some(v),
240 /// let r: Option<&()> = x.as_ref();
242 #[clippy::version = "pre 1.29.0"]
245 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
248 declare_clippy_lint! {
250 /// Checks for wildcard enum matches using `_`.
252 /// ### Why is this bad?
253 /// New enum variants added by library updates can be missed.
255 /// ### Known problems
256 /// Suggested replacements may be incorrect if guards exhaustively cover some
257 /// variants, and also may not use correct path to enum if it's not present in the current scope.
261 /// # enum Foo { A(usize), B(usize) }
262 /// # let x = Foo::B(1);
275 #[clippy::version = "1.34.0"]
276 pub WILDCARD_ENUM_MATCH_ARM,
278 "a wildcard enum match arm using `_`"
281 declare_clippy_lint! {
283 /// Checks for wildcard enum matches for a single variant.
285 /// ### Why is this bad?
286 /// New enum variants added by library updates can be missed.
288 /// ### Known problems
289 /// Suggested replacements may not use correct path to enum
290 /// if it's not present in the current scope.
294 /// # enum Foo { A, B, C }
295 /// # let x = Foo::B;
310 #[clippy::version = "1.45.0"]
311 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
313 "a wildcard enum match for a single variant"
316 declare_clippy_lint! {
318 /// Checks for wildcard pattern used with others patterns in same match arm.
320 /// ### Why is this bad?
321 /// Wildcard pattern already covers any other pattern as it will match anyway.
322 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
338 #[clippy::version = "1.42.0"]
339 pub WILDCARD_IN_OR_PATTERNS,
341 "a wildcard pattern used with others patterns in same match arm"
344 declare_clippy_lint! {
346 /// Checks for matches being used to destructure a single-variant enum
347 /// or tuple struct where a `let` will suffice.
349 /// ### Why is this bad?
350 /// Just readability – `let` doesn't nest, whereas a `match` does.
358 /// let wrapper = Wrapper::Data(42);
360 /// let data = match wrapper {
361 /// Wrapper::Data(i) => i,
365 /// The correct use would be:
371 /// let wrapper = Wrapper::Data(42);
372 /// let Wrapper::Data(data) = wrapper;
374 #[clippy::version = "pre 1.29.0"]
375 pub INFALLIBLE_DESTRUCTURING_MATCH,
377 "a `match` statement with a single infallible arm instead of a `let`"
380 declare_clippy_lint! {
382 /// Checks for useless match that binds to only one value.
384 /// ### Why is this bad?
385 /// Readability and needless complexity.
387 /// ### Known problems
388 /// Suggested replacements may be incorrect when `match`
389 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
404 /// let (c, d) = (a, b);
406 #[clippy::version = "1.43.0"]
407 pub MATCH_SINGLE_BINDING,
409 "a match with a single binding instead of using `let` statement"
412 declare_clippy_lint! {
414 /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
416 /// ### Why is this bad?
417 /// Correctness and readability. It's like having a wildcard pattern after
418 /// matching all enum variants explicitly.
422 /// # struct A { a: i32 }
423 /// let a = A { a: 5 };
427 /// A { a: 5, .. } => {},
433 /// A { a: 5 } => {},
437 #[clippy::version = "1.43.0"]
438 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
440 "a match on a struct that binds all fields but still uses the wildcard pattern"
443 declare_clippy_lint! {
445 /// Lint for redundant pattern matching over `Result`, `Option`,
446 /// `std::task::Poll` or `std::net::IpAddr`
448 /// ### Why is this bad?
449 /// It's more concise and clear to just use the proper
452 /// ### Known problems
453 /// This will change the drop order for the matched type. Both `if let` and
454 /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
455 /// value before entering the block. For most types this change will not matter, but for a few
456 /// types this will not be an acceptable change (e.g. locks). See the
457 /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
462 /// # use std::task::Poll;
463 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
464 /// if let Ok(_) = Ok::<i32, i32>(42) {}
465 /// if let Err(_) = Err::<i32, i32>(42) {}
466 /// if let None = None::<()> {}
467 /// if let Some(_) = Some(42) {}
468 /// if let Poll::Pending = Poll::Pending::<()> {}
469 /// if let Poll::Ready(_) = Poll::Ready(42) {}
470 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
471 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
472 /// match Ok::<i32, i32>(42) {
478 /// The more idiomatic use would be:
481 /// # use std::task::Poll;
482 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
483 /// if Ok::<i32, i32>(42).is_ok() {}
484 /// if Err::<i32, i32>(42).is_err() {}
485 /// if None::<()>.is_none() {}
486 /// if Some(42).is_some() {}
487 /// if Poll::Pending::<()>.is_pending() {}
488 /// if Poll::Ready(42).is_ready() {}
489 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
490 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
491 /// Ok::<i32, i32>(42).is_ok();
493 #[clippy::version = "1.31.0"]
494 pub REDUNDANT_PATTERN_MATCHING,
496 "use the proper utility function avoiding an `if let`"
499 declare_clippy_lint! {
501 /// Checks for `match` or `if let` expressions producing a
502 /// `bool` that could be written using `matches!`
504 /// ### Why is this bad?
505 /// Readability and needless complexity.
507 /// ### Known problems
508 /// This lint falsely triggers, if there are arms with
509 /// `cfg` attributes that remove an arm evaluating to `false`.
516 /// let a = match x {
521 /// let a = if let Some(0) = x {
528 /// let a = matches!(x, Some(0));
530 #[clippy::version = "1.47.0"]
531 pub MATCH_LIKE_MATCHES_MACRO,
533 "a match that could be written with the matches! macro"
536 declare_clippy_lint! {
538 /// Checks for `match` with identical arm bodies.
540 /// ### Why is this bad?
541 /// This is probably a copy & paste error. If arm bodies
542 /// are the same on purpose, you can factor them
543 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
545 /// ### Known problems
546 /// False positive possible with order dependent `match`
548 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
555 /// Baz => bar(), // <= oops
559 /// This should probably be
564 /// Baz => baz(), // <= fixed
568 /// or if the original code was not a typo:
571 /// Bar | Baz => bar(), // <= shows the intent better
575 #[clippy::version = "pre 1.29.0"]
578 "`match` with identical arm bodies"
583 msrv: Option<RustcVersion>,
584 infallible_destructuring_match_linted: bool,
589 pub fn new(msrv: Option<RustcVersion>) -> Self {
597 impl_lint_pass!(Matches => [
602 MATCH_OVERLAPPING_ARM,
605 WILDCARD_ENUM_MATCH_ARM,
606 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
607 WILDCARD_IN_OR_PATTERNS,
608 MATCH_SINGLE_BINDING,
609 INFALLIBLE_DESTRUCTURING_MATCH,
610 REST_PAT_IN_FULLY_BOUND_STRUCTS,
611 REDUNDANT_PATTERN_MATCHING,
612 MATCH_LIKE_MATCHES_MACRO,
616 impl<'tcx> LateLintPass<'tcx> for Matches {
617 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
618 if expr.span.from_expansion() {
622 redundant_pattern_match::check(cx, expr);
624 if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
625 if !check_match_like_matches(cx, expr) {
626 lint_match_arms(cx, expr);
629 lint_match_arms(cx, expr);
632 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
633 check_single_match(cx, ex, arms, expr);
634 check_match_bool(cx, ex, arms, expr);
635 check_overlapping_arms(cx, ex, arms);
636 check_wild_err_arm(cx, ex, arms);
637 check_wild_enum_match(cx, ex, arms);
638 check_match_as_ref(cx, ex, arms, expr);
639 check_wild_in_or_pats(cx, arms);
641 if self.infallible_destructuring_match_linted {
642 self.infallible_destructuring_match_linted = false;
644 check_match_single_binding(cx, ex, arms, expr);
647 if let ExprKind::Match(ex, arms, _) = expr.kind {
648 check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
652 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
654 if !local.span.from_expansion();
655 if let Some(expr) = local.init;
656 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
657 if arms.len() == 1 && arms[0].guard.is_none();
658 if let PatKind::TupleStruct(
659 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
661 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
662 let body = peel_blocks(arms[0].body);
663 if path_to_local_id(body, arg);
666 let mut applicability = Applicability::MachineApplicable;
667 self.infallible_destructuring_match_linted = true;
670 INFALLIBLE_DESTRUCTURING_MATCH,
672 "you seem to be trying to use `match` to destructure a single infallible pattern. \
673 Consider using `let`",
677 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
678 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
679 snippet_with_applicability(cx, target.span, "..", &mut applicability),
687 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
689 if !pat.span.from_expansion();
690 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
691 if let Some(def_id) = path.res.opt_def_id();
692 let ty = cx.tcx.type_of(def_id);
693 if let ty::Adt(def, _) = ty.kind();
694 if def.is_struct() || def.is_union();
695 if fields.len() == def.non_enum_variant().fields.len();
700 REST_PAT_IN_FULLY_BOUND_STRUCTS,
702 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
704 "consider removing `..` from this binding",
710 extract_msrv_attr!(LateContext);
714 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
715 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
716 if expr.span.from_expansion() {
717 // Don't lint match expressions present in
718 // macro_rules! block
721 if let PatKind::Or(..) = arms[0].pat.kind {
722 // don't lint for or patterns for now, this makes
723 // the lint noisy in unnecessary situations
726 let els = arms[1].body;
727 let els = if is_unit_expr(peel_blocks(els)) {
729 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
730 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
731 // single statement/expr "else" block, don't lint
734 // block with 2+ statements or 1 expr and 1+ statement
737 // not a block, don't lint
741 let ty = cx.typeck_results().expr_ty(ex);
742 if *ty.kind() != ty::Bool || is_lint_allowed(cx, MATCH_BOOL, ex.hir_id) {
743 check_single_match_single_pattern(cx, ex, arms, expr, els);
744 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
749 fn check_single_match_single_pattern(
750 cx: &LateContext<'_>,
754 els: Option<&Expr<'_>>,
756 if is_wild(arms[1].pat) {
757 report_single_match_single_pattern(cx, ex, arms, expr, els);
761 fn report_single_match_single_pattern(
762 cx: &LateContext<'_>,
766 els: Option<&Expr<'_>>,
768 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
769 let els_str = els.map_or(String::new(), |els| {
770 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
773 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
774 let (msg, sugg) = if_chain! {
775 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
776 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
777 if let Some(spe_trait_id) = cx.tcx.lang_items().structural_peq_trait();
778 if let Some(pe_trait_id) = cx.tcx.lang_items().eq_trait();
779 if ty.is_integral() || ty.is_char() || ty.is_str()
780 || (implements_trait(cx, ty, spe_trait_id, &[])
781 && implements_trait(cx, ty, pe_trait_id, &[ty.into()]));
783 // scrutinee derives PartialEq and the pattern is a constant.
784 let pat_ref_count = match pat.kind {
785 // string literals are already a reference.
786 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
789 // References are only implicitly added to the pattern, so no overflow here.
790 // e.g. will work: match &Some(_) { Some(_) => () }
791 // will not: match Some(_) { &Some(_) => () }
792 let ref_count_diff = ty_ref_count - pat_ref_count;
794 // Try to remove address of expressions first.
795 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
796 let ref_count_diff = ref_count_diff - removed;
798 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
800 "if {} == {}{} {}{}",
801 snippet(cx, ex.span, ".."),
802 // PartialEq for different reference counts may not exist.
803 "&".repeat(ref_count_diff),
804 snippet(cx, arms[0].pat.span, ".."),
805 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
810 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
812 "if let {} = {} {}{}",
813 snippet(cx, arms[0].pat.span, ".."),
814 snippet(cx, ex.span, ".."),
815 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
829 Applicability::HasPlaceholders,
833 fn check_single_match_opt_like(
834 cx: &LateContext<'_>,
839 els: Option<&Expr<'_>>,
841 // list of candidate `Enum`s we know will never get any more members
843 (&paths::COW, "Borrowed"),
844 (&paths::COW, "Cow::Borrowed"),
845 (&paths::COW, "Cow::Owned"),
846 (&paths::COW, "Owned"),
847 (&paths::OPTION, "None"),
848 (&paths::RESULT, "Err"),
849 (&paths::RESULT, "Ok"),
852 let path = match arms[1].pat.kind {
853 PatKind::TupleStruct(ref path, inner, _) => {
854 // Contains any non wildcard patterns (e.g., `Err(err)`)?
855 if !inner.iter().all(is_wild) {
858 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
860 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
861 PatKind::Path(ref path) => {
862 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
867 for &(ty_path, pat_path) in candidates {
868 if path == *pat_path && match_type(cx, ty, ty_path) {
869 report_single_match_single_pattern(cx, ex, arms, expr, els);
874 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
875 // Type of expression is `bool`.
876 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
881 "you seem to be trying to match on a boolean expression",
885 let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
886 if let ExprKind::Lit(ref lit) = arm_bool.kind {
888 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
889 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
899 if let Some((true_expr, false_expr)) = exprs {
900 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
901 (false, false) => Some(format!(
903 snippet(cx, ex.span, "b"),
904 expr_block(cx, true_expr, None, "..", Some(expr.span)),
905 expr_block(cx, false_expr, None, "..", Some(expr.span))
907 (false, true) => Some(format!(
909 snippet(cx, ex.span, "b"),
910 expr_block(cx, true_expr, None, "..", Some(expr.span))
913 let test = Sugg::hir(cx, ex, "..");
917 expr_block(cx, false_expr, None, "..", Some(expr.span))
920 (true, true) => None,
923 if let Some(sugg) = sugg {
924 diag.span_suggestion(
926 "consider using an `if`/`else` expression",
928 Applicability::HasPlaceholders,
938 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
939 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
940 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
941 if !ranges.is_empty() {
942 if let Some((start, end)) = overlapping(&ranges) {
945 MATCH_OVERLAPPING_ARM,
947 "some ranges overlap",
949 "overlaps with this",
956 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
957 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
958 if is_type_diagnostic_item(cx, ex_ty, sym::Result) {
960 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
961 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
962 if path_str == "Err" {
963 let mut matching_wild = inner.iter().any(is_wild);
964 let mut ident_bind_name = String::from("_");
966 // Looking for unused bindings (i.e.: `_e`)
967 for pat in inner.iter() {
968 if let PatKind::Binding(_, id, ident, None) = pat.kind {
969 if ident.as_str().starts_with('_') && !is_local_used(cx, arm.body, id) {
970 ident_bind_name = ident.name.as_str().to_string();
971 matching_wild = true;
978 if let Some(macro_call) = root_macro_call(peel_blocks_with_stmt(arm.body).span);
979 if is_panic(cx, macro_call.def_id);
981 // `Err(_)` or `Err(_e)` arm with `panic!` found
982 span_lint_and_note(cx,
985 &format!("`Err({})` matches all errors", &ident_bind_name),
987 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
997 enum CommonPrefixSearcher<'a> {
999 Path(&'a [PathSegment<'a>]),
1002 impl<'a> CommonPrefixSearcher<'a> {
1003 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
1005 [path @ .., _] => self.with_prefix(path),
1010 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
1012 Self::None => *self = Self::Path(path),
1013 Self::Path(self_path)
1016 .map(|p| p.ident.name)
1017 .eq(self_path.iter().map(|p| p.ident.name)) => {},
1018 Self::Path(_) => *self = Self::Mixed,
1024 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
1025 let attrs = cx.tcx.get_attrs(variant_def.def_id);
1026 clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
1029 #[allow(clippy::too_many_lines)]
1030 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
1031 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
1032 let adt_def = match ty.kind() {
1034 if adt_def.is_enum()
1035 && !(is_type_diagnostic_item(cx, ty, sym::Option) || is_type_diagnostic_item(cx, ty, sym::Result)) =>
1042 // First pass - check for violation, but don't do much book-keeping because this is hopefully
1043 // the uncommon case, and the book-keeping is slightly expensive.
1044 let mut wildcard_span = None;
1045 let mut wildcard_ident = None;
1046 let mut has_non_wild = false;
1048 match peel_hir_pat_refs(arm.pat).0.kind {
1049 PatKind::Wild => wildcard_span = Some(arm.pat.span),
1050 PatKind::Binding(_, _, ident, None) => {
1051 wildcard_span = Some(arm.pat.span);
1052 wildcard_ident = Some(ident);
1054 _ => has_non_wild = true,
1057 let wildcard_span = match wildcard_span {
1058 Some(x) if has_non_wild => x,
1062 // Accumulate the variants which should be put in place of the wildcard because they're not
1064 let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
1065 let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
1067 let mut path_prefix = CommonPrefixSearcher::None;
1069 // Guards mean that this case probably isn't exhaustively covered. Technically
1070 // this is incorrect, as we should really check whether each variant is exhaustively
1071 // covered by the set of guards that cover it, but that's really hard to do.
1072 recurse_or_patterns(arm.pat, |pat| {
1073 let path = match &peel_hir_pat_refs(pat).0.kind {
1074 PatKind::Path(path) => {
1075 #[allow(clippy::match_same_arms)]
1076 let id = match cx.qpath_res(path, pat.hir_id) {
1078 DefKind::Const | DefKind::ConstParam | DefKind::AnonConst | DefKind::InlineConst,
1081 Res::Def(_, id) => id,
1084 if arm.guard.is_none() {
1085 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1089 PatKind::TupleStruct(path, patterns, ..) => {
1090 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1091 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1092 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1097 PatKind::Struct(path, patterns, ..) => {
1098 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1099 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1100 missing_variants.retain(|e| e.def_id != id);
1108 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1109 QPath::TypeRelative(
1111 kind: TyKind::Path(QPath::Resolved(_, path)),
1115 ) => path_prefix.with_prefix(path.segments),
1121 let format_suggestion = |variant: &VariantDef| {
1124 if let Some(ident) = wildcard_ident {
1125 format!("{} @ ", ident.name)
1129 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1130 let mut s = String::new();
1131 for seg in path_prefix {
1132 s.push_str(seg.ident.as_str());
1137 let mut s = cx.tcx.def_path_str(adt_def.did);
1142 match variant.ctor_kind {
1143 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1144 CtorKind::Fn => "(..)",
1145 CtorKind::Const => "",
1146 CtorKind::Fictive => "{ .. }",
1151 match missing_variants.as_slice() {
1153 [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
1155 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1157 "wildcard matches only a single variant and will also match any future added variants",
1159 format_suggestion(x),
1160 Applicability::MaybeIncorrect,
1163 let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1164 let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
1165 suggestions.push("_".into());
1166 "wildcard matches known variants and will also match future added variants"
1168 "wildcard match will also match any future added variants"
1173 WILDCARD_ENUM_MATCH_ARM,
1177 suggestions.join(" | "),
1178 Applicability::MaybeIncorrect,
1184 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
1187 I: Clone + Iterator<Item = &'a Pat<'b>>,
1189 if !has_multiple_ref_pats(pats.clone()) {
1193 let (first_sugg, msg, title);
1194 let span = ex.span.source_callsite();
1195 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = ex.kind {
1196 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1198 title = "you don't need to add `&` to both the expression and the patterns";
1200 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1201 msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
1202 title = "you don't need to add `&` to all patterns";
1205 let remaining_suggs = pats.filter_map(|pat| {
1206 if let PatKind::Ref(refp, _) = pat.kind {
1207 Some((pat.span, snippet(cx, refp.span, "..").to_string()))
1213 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1214 if !expr.span.from_expansion() {
1215 multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
1220 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1221 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1222 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1223 is_ref_some_arm(cx, &arms[1])
1224 } else if is_none_arm(cx, &arms[1]) {
1225 is_ref_some_arm(cx, &arms[0])
1229 if let Some(rb) = arm_ref {
1230 let suggestion = if rb == BindingAnnotation::Ref {
1236 let output_ty = cx.typeck_results().expr_ty(expr);
1237 let input_ty = cx.typeck_results().expr_ty(ex);
1239 let cast = if_chain! {
1240 if let ty::Adt(_, substs) = input_ty.kind();
1241 let input_ty = substs.type_at(0);
1242 if let ty::Adt(_, substs) = output_ty.kind();
1243 let output_ty = substs.type_at(0);
1244 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1245 if input_ty != output_ty;
1253 let mut applicability = Applicability::MachineApplicable;
1258 &format!("use `{}()` instead", suggestion),
1262 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1272 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1274 if let PatKind::Or(fields) = arm.pat.kind {
1275 // look for multiple fields in this arm that contains at least one Wild pattern
1276 if fields.len() > 1 && fields.iter().any(is_wild) {
1279 WILDCARD_IN_OR_PATTERNS,
1281 "wildcard pattern covers any other pattern as it will match anyway",
1283 "consider handling `_` separately",
1290 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1291 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1292 if let Some(higher::IfLet {
1296 if_else: Some(if_else),
1297 }) = higher::IfLet::hir(cx, expr)
1299 return find_matches_sugg(
1302 IntoIterator::into_iter([(&[][..], Some(let_pat), if_then, None), (&[][..], None, if_else, None)]),
1308 if let ExprKind::Match(scrut, arms, MatchSource::Normal) = expr.kind {
1309 return find_matches_sugg(
1312 arms.iter().map(|arm| {
1314 cx.tcx.hir().attrs(arm.hir_id),
1328 /// Lint a `match` or `if let` for replacement by `matches!`
1329 fn find_matches_sugg<'a, 'b, I>(
1330 cx: &LateContext<'_>,
1339 + DoubleEndedIterator
1344 Option<&'a Pat<'b>>,
1346 Option<&'a Guard<'b>>,
1352 if cx.typeck_results().expr_ty(expr).is_bool();
1353 if let Some((_, last_pat_opt, last_expr, _)) = iter.next_back();
1354 let iter_without_last = iter.clone();
1355 if let Some((first_attrs, _, first_expr, first_guard)) = iter.next();
1356 if let Some(b0) = find_bool_lit(&first_expr.kind, is_if_let);
1357 if let Some(b1) = find_bool_lit(&last_expr.kind, is_if_let);
1359 if first_guard.is_none() || iter.len() == 0;
1360 if first_attrs.is_empty();
1363 find_bool_lit(&arm.2.kind, is_if_let).map_or(false, |b| b == b0) && arm.3.is_none() && arm.0.is_empty()
1366 if let Some(last_pat) = last_pat_opt {
1367 if !is_wild(last_pat) {
1372 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1373 // evaluated into `false` and so such arms will be stripped before.
1374 let mut applicability = Applicability::MaybeIncorrect;
1376 use itertools::Itertools as _;
1379 let pat_span = arm.1?.span;
1380 Some(snippet_with_applicability(cx, pat_span, "..", &mut applicability))
1384 let pat_and_guard = if let Some(Guard::If(g)) = first_guard {
1385 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1390 // strip potential borrows (#6503), but only if the type is a reference
1391 let mut ex_new = ex;
1392 if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1393 if let ty::Ref(..) = cx.typeck_results().expr_ty(ex_inner).kind() {
1399 MATCH_LIKE_MATCHES_MACRO,
1401 &format!("{} expression looks like `matches!` macro", if is_if_let { "if let .. else" } else { "match" }),
1404 "{}matches!({}, {})",
1405 if b0 { "" } else { "!" },
1406 snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1418 /// Extract a `bool` or `{ bool }`
1419 fn find_bool_lit(ex: &ExprKind<'_>, is_if_let: bool) -> Option<bool> {
1421 ExprKind::Lit(Spanned {
1422 node: LitKind::Bool(b), ..
1432 if let ExprKind::Lit(Spanned {
1433 node: LitKind::Bool(b), ..
1445 #[allow(clippy::too_many_lines)]
1446 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1447 if expr.span.from_expansion() || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1452 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1453 // to prevent false positives as there is currently no better way to detect if code was excluded by
1454 // a macro. See PR #6435
1456 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1457 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1458 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1459 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1460 if rest_snippet.contains("=>");
1462 // The code it self contains another thick arrow "=>"
1463 // -> Either another arm or a comment
1468 let matched_vars = ex.span;
1469 let bind_names = arms[0].pat.span;
1470 let match_body = peel_blocks(arms[0].body);
1471 let mut snippet_body = if match_body.span.from_expansion() {
1472 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1474 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1477 // Do we need to add ';' to suggestion ?
1478 match match_body.kind {
1479 ExprKind::Block(block, _) => {
1480 // macro + expr_ty(body) == ()
1481 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1482 snippet_body.push(';');
1486 // expr_ty(body) == ()
1487 if cx.typeck_results().expr_ty(match_body).is_unit() {
1488 snippet_body.push(';');
1493 let mut applicability = Applicability::MaybeIncorrect;
1494 match arms[0].pat.kind {
1495 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1496 // If this match is in a local (`let`) stmt
1497 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1499 parent_let_node.span,
1501 "let {} = {};\n{}let {} = {};",
1502 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1503 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1504 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1505 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1510 // If we are in closure, we need curly braces around suggestion
1511 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1512 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1513 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1514 if let ExprKind::Closure(..) = parent_expr.kind {
1515 cbrace_end = format!("\n{}}}", indent);
1516 // Fix body indent due to the closure
1517 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1518 cbrace_start = format!("{{\n{}", indent);
1521 // If the parent is already an arm, and the body is another match statement,
1522 // we need curly braces around suggestion
1523 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1524 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1525 if let ExprKind::Match(..) = arm.body.kind {
1526 cbrace_end = format!("\n{}}}", indent);
1527 // Fix body indent due to the match
1528 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1529 cbrace_start = format!("{{\n{}", indent);
1535 "{}let {} = {};\n{}{}{}",
1537 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1538 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1547 MATCH_SINGLE_BINDING,
1549 "this match could be written as a `let` statement",
1550 "consider using `let` statement",
1556 if ex.can_have_side_effects() {
1557 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1560 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1566 MATCH_SINGLE_BINDING,
1568 "this match could be replaced by its scrutinee and body",
1569 "consider using the scrutinee and body instead",
1576 MATCH_SINGLE_BINDING,
1578 "this match could be replaced by its body itself",
1579 "consider using the match body instead",
1581 Applicability::MachineApplicable,
1589 /// Returns true if the `ex` match expression is in a local (`let`) statement
1590 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1591 let map = &cx.tcx.hir();
1593 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1594 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1596 return Some(parent_let_expr);
1602 /// Gets the ranges for each range pattern arm. Applies `ty` bounds for open ranges.
1603 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<FullInt>> {
1606 if let Arm { pat, guard: None, .. } = *arm {
1607 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1608 let lhs_const = match lhs {
1609 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1610 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1612 let rhs_const = match rhs {
1613 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1614 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1617 let lhs_val = lhs_const.int_value(cx, ty)?;
1618 let rhs_val = rhs_const.int_value(cx, ty)?;
1620 let rhs_bound = match range_end {
1621 RangeEnd::Included => EndBound::Included(rhs_val),
1622 RangeEnd::Excluded => EndBound::Excluded(rhs_val),
1624 return Some(SpannedRange {
1626 node: (lhs_val, rhs_bound),
1630 if let PatKind::Lit(value) = pat.kind {
1631 let value = constant_full_int(cx, cx.typeck_results(), value)?;
1632 return Some(SpannedRange {
1634 node: (value, EndBound::Included(value)),
1643 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1644 pub enum EndBound<T> {
1649 #[derive(Debug, Eq, PartialEq)]
1650 struct SpannedRange<T> {
1652 pub node: (T, EndBound<T>),
1655 // Checks if arm has the form `None => None`
1656 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1657 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1660 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1661 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1663 if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1664 if is_lang_ctor(cx, qpath, OptionSome);
1665 if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1666 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1667 if let ExprKind::Call(e, args) = peel_blocks(arm.body).kind;
1668 if let ExprKind::Path(ref some_path) = e.kind;
1669 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1670 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1671 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1679 fn has_multiple_ref_pats<'a, 'b, I>(pats: I) -> bool
1682 I: Iterator<Item = &'a Pat<'b>>,
1684 let mut ref_count = 0;
1685 for opt in pats.map(|pat| match pat.kind {
1686 PatKind::Ref(..) => Some(true), // &-patterns
1687 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1688 _ => None, // any other pattern is not fine
1690 if let Some(inner) = opt {
1701 fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1705 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
1712 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1713 struct RangeBound<'a, T>(T, BoundKind, &'a SpannedRange<T>);
1715 impl<'a, T: Copy + Ord> PartialOrd for RangeBound<'a, T> {
1716 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1717 Some(self.cmp(other))
1721 impl<'a, T: Copy + Ord> Ord for RangeBound<'a, T> {
1722 fn cmp(&self, RangeBound(other_value, other_kind, _): &Self) -> Ordering {
1723 let RangeBound(self_value, self_kind, _) = *self;
1724 (self_value, self_kind).cmp(&(*other_value, *other_kind))
1728 let mut values = Vec::with_capacity(2 * ranges.len());
1730 for r @ SpannedRange { node: (start, end), .. } in ranges {
1731 values.push(RangeBound(*start, BoundKind::Start, r));
1732 values.push(match end {
1733 EndBound::Excluded(val) => RangeBound(*val, BoundKind::EndExcluded, r),
1734 EndBound::Included(val) => RangeBound(*val, BoundKind::EndIncluded, r),
1740 let mut started = vec![];
1742 for RangeBound(_, kind, range) in values {
1744 BoundKind::Start => started.push(range),
1745 BoundKind::EndExcluded | BoundKind::EndIncluded => {
1746 let mut overlap = None;
1748 while let Some(last_started) = started.pop() {
1749 if last_started == range {
1752 overlap = Some(last_started);
1755 if let Some(first_overlapping) = overlap {
1756 return Some((range, first_overlapping));
1765 mod redundant_pattern_match {
1766 use super::REDUNDANT_PATTERN_MATCHING;
1767 use clippy_utils::diagnostics::span_lint_and_then;
1768 use clippy_utils::higher;
1769 use clippy_utils::source::snippet;
1770 use clippy_utils::sugg::Sugg;
1771 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, is_type_lang_item, match_type};
1772 use clippy_utils::{is_lang_ctor, is_qpath_def_path, is_trait_method, paths};
1773 use if_chain::if_chain;
1774 use rustc_ast::ast::LitKind;
1775 use rustc_data_structures::fx::FxHashSet;
1776 use rustc_errors::Applicability;
1777 use rustc_hir::LangItem::{OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk};
1779 intravisit::{walk_expr, Visitor},
1780 Arm, Block, Expr, ExprKind, LangItem, MatchSource, Node, Pat, PatKind, QPath, UnOp,
1782 use rustc_lint::LateContext;
1783 use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
1784 use rustc_span::sym;
1786 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1787 if let Some(higher::IfLet {
1792 }) = higher::IfLet::hir(cx, expr)
1794 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "if", if_else.is_some());
1796 if let ExprKind::Match(op, arms, MatchSource::Normal) = &expr.kind {
1797 find_sugg_for_match(cx, expr, op, arms);
1799 if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) {
1800 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "while", false);
1804 /// Checks if the drop order for a type matters. Some std types implement drop solely to
1805 /// deallocate memory. For these types, and composites containing them, changing the drop order
1806 /// won't result in any observable side effects.
1807 fn type_needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1808 type_needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
1811 fn type_needs_ordered_drop_inner<'tcx>(
1812 cx: &LateContext<'tcx>,
1814 seen: &mut FxHashSet<Ty<'tcx>>,
1816 if !seen.insert(ty) {
1819 if !ty.needs_drop(cx.tcx, cx.param_env) {
1825 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1827 // This type doesn't implement drop, so no side effects here.
1828 // Check if any component type has any.
1830 ty::Tuple(_) => ty.tuple_fields().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1831 ty::Array(ty, _) => type_needs_ordered_drop_inner(cx, ty, seen),
1832 ty::Adt(adt, subs) => adt
1834 .map(|f| f.ty(cx.tcx, subs))
1835 .any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1839 // Check for std types which implement drop, but only for memory allocation.
1840 else if is_type_diagnostic_item(cx, ty, sym::Vec)
1841 || is_type_lang_item(cx, ty, LangItem::OwnedBox)
1842 || is_type_diagnostic_item(cx, ty, sym::Rc)
1843 || is_type_diagnostic_item(cx, ty, sym::Arc)
1844 || is_type_diagnostic_item(cx, ty, sym::cstring_type)
1845 || is_type_diagnostic_item(cx, ty, sym::BTreeMap)
1846 || is_type_diagnostic_item(cx, ty, sym::LinkedList)
1847 || match_type(cx, ty, &paths::WEAK_RC)
1848 || match_type(cx, ty, &paths::WEAK_ARC)
1850 // Check all of the generic arguments.
1851 if let ty::Adt(_, subs) = ty.kind() {
1852 subs.types().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen))
1861 // Extract the generic arguments out of a type
1862 fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
1864 if let ty::Adt(_, subs) = ty.kind();
1865 if let Some(sub) = subs.get(index);
1866 if let GenericArgKind::Type(sub_ty) = sub.unpack();
1875 // Checks if there are any temporaries created in the given expression for which drop order
1877 fn temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1878 struct V<'a, 'tcx> {
1879 cx: &'a LateContext<'tcx>,
1882 impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
1883 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1885 // Taking the reference of a value leaves a temporary
1886 // e.g. In `&String::new()` the string is a temporary value.
1887 // Remaining fields are temporary values
1888 // e.g. In `(String::new(), 0).1` the string is a temporary value.
1889 ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
1890 if !matches!(expr.kind, ExprKind::Path(_)) {
1891 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
1894 self.visit_expr(expr);
1898 // the base type is alway taken by reference.
1899 // e.g. In `(vec![0])[0]` the vector is a temporary value.
1900 ExprKind::Index(base, index) => {
1901 if !matches!(base.kind, ExprKind::Path(_)) {
1902 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
1905 self.visit_expr(base);
1908 self.visit_expr(index);
1910 // Method calls can take self by reference.
1911 // e.g. In `String::new().len()` the string is a temporary value.
1912 ExprKind::MethodCall(_, [self_arg, args @ ..], _) => {
1913 if !matches!(self_arg.kind, ExprKind::Path(_)) {
1914 let self_by_ref = self
1917 .type_dependent_def_id(expr.hir_id)
1918 .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
1920 && type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg))
1924 self.visit_expr(self_arg);
1927 args.iter().for_each(|arg| self.visit_expr(arg));
1929 // Either explicitly drops values, or changes control flow.
1930 ExprKind::DropTemps(_)
1932 | ExprKind::Break(..)
1933 | ExprKind::Yield(..)
1934 | ExprKind::Block(Block { expr: None, .. }, _)
1935 | ExprKind::Loop(..) => (),
1937 // Only consider the final expression.
1938 ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
1940 _ => walk_expr(self, expr),
1945 let mut v = V { cx, res: false };
1950 fn find_sugg_for_if_let<'tcx>(
1951 cx: &LateContext<'tcx>,
1952 expr: &'tcx Expr<'_>,
1954 let_expr: &'tcx Expr<'_>,
1955 keyword: &'static str,
1958 // also look inside refs
1959 let mut kind = &let_pat.kind;
1960 // if we have &None for example, peel it so we can detect "if let None = x"
1961 if let PatKind::Ref(inner, _mutability) = kind {
1964 let op_ty = cx.typeck_results().expr_ty(let_expr);
1965 // Determine which function should be used, and the type contained by the corresponding
1967 let (good_method, inner_ty) = match kind {
1968 PatKind::TupleStruct(ref path, [sub_pat], _) => {
1969 if let PatKind::Wild = sub_pat.kind {
1970 if is_lang_ctor(cx, path, ResultOk) {
1971 ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
1972 } else if is_lang_ctor(cx, path, ResultErr) {
1973 ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
1974 } else if is_lang_ctor(cx, path, OptionSome) {
1975 ("is_some()", op_ty)
1976 } else if is_lang_ctor(cx, path, PollReady) {
1977 ("is_ready()", op_ty)
1978 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V4) {
1979 ("is_ipv4()", op_ty)
1980 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V6) {
1981 ("is_ipv6()", op_ty)
1989 PatKind::Path(ref path) => {
1990 let method = if is_lang_ctor(cx, path, OptionNone) {
1992 } else if is_lang_ctor(cx, path, PollPending) {
1997 // `None` and `Pending` don't have an inner type.
1998 (method, cx.tcx.types.unit)
2003 // If this is the last expression in a block or there is an else clause then the whole
2004 // type needs to be considered, not just the inner type of the branch being matched on.
2005 // Note the last expression in a block is dropped after all local bindings.
2006 let check_ty = if has_else
2007 || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
2014 // All temporaries created in the scrutinee expression are dropped at the same time as the
2015 // scrutinee would be, so they have to be considered as well.
2016 // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
2017 // for the duration if body.
2018 let needs_drop = type_needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
2020 // check that `while_let_on_iterator` lint does not trigger
2022 if keyword == "while";
2023 if let ExprKind::MethodCall(method_path, _, _) = let_expr.kind;
2024 if method_path.ident.name == sym::next;
2025 if is_trait_method(cx, let_expr, sym::Iterator);
2031 let result_expr = match &let_expr.kind {
2032 ExprKind::AddrOf(_, _, borrowed) => borrowed,
2033 ExprKind::Unary(UnOp::Deref, deref) => deref,
2039 REDUNDANT_PATTERN_MATCHING,
2041 &format!("redundant pattern matching, consider using `{}`", good_method),
2043 // if/while let ... = ... { ... }
2044 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2045 let expr_span = expr.span;
2047 // if/while let ... = ... { ... }
2049 let op_span = result_expr.span.source_callsite();
2051 // if/while let ... = ... { ... }
2052 // ^^^^^^^^^^^^^^^^^^^
2053 let span = expr_span.until(op_span.shrink_to_hi());
2055 let app = if needs_drop {
2056 Applicability::MaybeIncorrect
2058 Applicability::MachineApplicable
2061 let sugg = Sugg::hir_with_macro_callsite(cx, result_expr, "_")
2065 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
2068 diag.note("this will change drop order of the result, as well as all temporaries");
2069 diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
2075 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
2076 if arms.len() == 2 {
2077 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
2079 let found_good_method = match node_pair {
2081 PatKind::TupleStruct(ref path_left, patterns_left, _),
2082 PatKind::TupleStruct(ref path_right, patterns_right, _),
2083 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
2084 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
2085 find_good_method_for_match(
2096 find_good_method_for_match(
2111 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
2112 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
2113 if patterns.len() == 1 =>
2115 if let PatKind::Wild = patterns[0].kind {
2116 find_good_method_for_match(
2121 &paths::OPTION_SOME,
2122 &paths::OPTION_NONE,
2127 find_good_method_for_match(
2133 &paths::POLL_PENDING,
2145 if let Some(good_method) = found_good_method {
2146 let span = expr.span.to(op.span);
2147 let result_expr = match &op.kind {
2148 ExprKind::AddrOf(_, _, borrowed) => borrowed,
2153 REDUNDANT_PATTERN_MATCHING,
2155 &format!("redundant pattern matching, consider using `{}`", good_method),
2157 diag.span_suggestion(
2160 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
2161 Applicability::MaybeIncorrect, // snippet
2169 #[allow(clippy::too_many_arguments)]
2170 fn find_good_method_for_match<'a>(
2171 cx: &LateContext<'_>,
2173 path_left: &QPath<'_>,
2174 path_right: &QPath<'_>,
2175 expected_left: &[&str],
2176 expected_right: &[&str],
2177 should_be_left: &'a str,
2178 should_be_right: &'a str,
2179 ) -> Option<&'a str> {
2180 let body_node_pair = if is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_left)
2181 && is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_right)
2183 (&(*arms[0].body).kind, &(*arms[1].body).kind)
2184 } else if is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_left)
2185 && is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_right)
2187 (&(*arms[1].body).kind, &(*arms[0].body).kind)
2192 match body_node_pair {
2193 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
2194 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
2195 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
2204 fn test_overlapping() {
2205 use rustc_span::source_map::DUMMY_SP;
2207 let sp = |s, e| SpannedRange {
2212 assert_eq!(None, overlapping::<u8>(&[]));
2213 assert_eq!(None, overlapping(&[sp(1, EndBound::Included(4))]));
2216 overlapping(&[sp(1, EndBound::Included(4)), sp(5, EndBound::Included(6))])
2221 sp(1, EndBound::Included(4)),
2222 sp(5, EndBound::Included(6)),
2223 sp(10, EndBound::Included(11))
2227 Some((&sp(1, EndBound::Included(4)), &sp(3, EndBound::Included(6)))),
2228 overlapping(&[sp(1, EndBound::Included(4)), sp(3, EndBound::Included(6))])
2231 Some((&sp(5, EndBound::Included(6)), &sp(6, EndBound::Included(11)))),
2233 sp(1, EndBound::Included(4)),
2234 sp(5, EndBound::Included(6)),
2235 sp(6, EndBound::Included(11))
2240 /// Implementation of `MATCH_SAME_ARMS`.
2241 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
2242 if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
2243 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
2244 let mut h = SpanlessHash::new(cx);
2245 h.hash_expr(arm.body);
2249 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
2250 let min_index = usize::min(lindex, rindex);
2251 let max_index = usize::max(lindex, rindex);
2253 let mut local_map: HirIdMap<HirId> = HirIdMap::default();
2254 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
2256 if let Some(a_id) = path_to_local(a);
2257 if let Some(b_id) = path_to_local(b);
2258 let entry = match local_map.entry(a_id) {
2259 Entry::Vacant(entry) => entry,
2260 // check if using the same bindings as before
2261 Entry::Occupied(entry) => return *entry.get() == b_id,
2263 // the names technically don't have to match; this makes the lint more conservative
2264 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2265 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2266 if pat_contains_local(lhs.pat, a_id);
2267 if pat_contains_local(rhs.pat, b_id);
2276 // Arms with a guard are ignored, those can’t always be merged together
2277 // This is also the case for arms in-between each there is an arm with a guard
2278 (min_index..=max_index).all(|index| arms[index].guard.is_none())
2279 && SpanlessEq::new(cx)
2280 .expr_fallback(eq_fallback)
2281 .eq_expr(lhs.body, rhs.body)
2282 // these checks could be removed to allow unused bindings
2283 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2284 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2287 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2288 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2293 "this `match` has identical arm bodies",
2295 diag.span_note(i.body.span, "same as this");
2297 // Note: this does not use `span_suggestion` on purpose:
2298 // there is no clean way
2299 // to remove the other arm. Building a span and suggest to replace it to ""
2300 // makes an even more confusing error message. Also in order not to make up a
2301 // span for the whole pattern, the suggestion is only shown when there is only
2302 // one pattern. The user should know about `|` if they are already using it…
2304 let lhs = snippet(cx, i.pat.span, "<pat1>");
2305 let rhs = snippet(cx, j.pat.span, "<pat2>");
2307 if let PatKind::Wild = j.pat.kind {
2308 // if the last arm is _, then i could be integrated into _
2309 // note that i.pat cannot be _, because that would mean that we're
2310 // hiding all the subsequent arms, and rust won't compile
2314 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2319 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs,))
2320 .help("...or consider changing the match arm bodies");
2328 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2329 let mut result = false;
2330 pat.walk_short(|p| {
2331 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2337 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2338 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2339 let mut result = true;
2340 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2341 result && ids.is_empty()