1 use clippy_utils::consts::{constant, miri_to_const, Constant};
2 use clippy_utils::diagnostics::{
3 multispan_sugg, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then,
5 use clippy_utils::higher;
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::LocalUsedVisitor;
11 get_parent_expr, in_macro, is_expn_of, is_lang_ctor, is_lint_allowed, is_refutable, is_wild, meets_msrv, msrvs,
12 path_to_local, path_to_local_id, peel_hir_pat_refs, peel_n_hir_expr_refs, recurse_or_patterns, remove_blocks,
15 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, LintContext};
29 use rustc_middle::lint::in_external_macro;
30 use rustc_middle::ty::{self, Ty, TyS, VariantDef};
31 use rustc_semver::RustcVersion;
32 use rustc_session::{declare_tool_lint, impl_lint_pass};
33 use rustc_span::source_map::{Span, Spanned};
35 use std::cmp::Ordering;
36 use std::collections::hash_map::Entry;
40 declare_clippy_lint! {
42 /// Checks for matches with a single arm where an `if let`
43 /// will usually suffice.
45 /// ### Why is this bad?
46 /// Just readability – `if let` nests less than a `match`.
50 /// # fn bar(stool: &str) {}
51 /// # let x = Some("abc");
54 /// Some(ref foo) => bar(foo),
59 /// if let Some(ref foo) = x {
65 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
68 declare_clippy_lint! {
70 /// Checks for matches with two arms where an `if let else` will
73 /// ### Why is this bad?
74 /// Just readability – `if let` nests less than a `match`.
76 /// ### Known problems
77 /// Personal style preferences may differ.
83 /// # fn bar(foo: &usize) {}
84 /// # let other_ref: usize = 1;
85 /// # let x: Option<&usize> = Some(&1);
87 /// Some(ref foo) => bar(foo),
88 /// _ => bar(&other_ref),
92 /// Using `if let` with `else`:
95 /// # fn bar(foo: &usize) {}
96 /// # let other_ref: usize = 1;
97 /// # let x: Option<&usize> = Some(&1);
98 /// if let Some(ref foo) = x {
104 pub SINGLE_MATCH_ELSE,
106 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
109 declare_clippy_lint! {
111 /// Checks for matches where all arms match a reference,
112 /// suggesting to remove the reference and deref the matched expression
113 /// instead. It also checks for `if let &foo = bar` blocks.
115 /// ### Why is this bad?
116 /// It just makes the code less readable. That reference
117 /// destructuring adds nothing to the code.
123 /// &A(ref y) => foo(y),
130 /// A(ref y) => foo(y),
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;
171 "a `match` on a boolean expression instead of an `if..else` block"
174 declare_clippy_lint! {
176 /// Checks for overlapping match arms.
178 /// ### Why is this bad?
179 /// It is likely to be an error and if not, makes the code
186 /// 1...10 => println!("1 ... 10"),
187 /// 5...15 => println!("5 ... 15"),
191 pub MATCH_OVERLAPPING_ARM,
193 "a `match` with overlapping arms"
196 declare_clippy_lint! {
198 /// Checks for arm which matches all errors with `Err(_)`
199 /// and take drastic actions like `panic!`.
201 /// ### Why is this bad?
202 /// It is generally a bad practice, similar to
203 /// catching all exceptions in java with `catch(Exception)`
207 /// let x: Result<i32, &str> = Ok(3);
209 /// Ok(_) => println!("ok"),
210 /// Err(_) => panic!("err"),
213 pub MATCH_WILD_ERR_ARM,
215 "a `match` with `Err(_)` arm and take drastic actions"
218 declare_clippy_lint! {
220 /// Checks for match which is used to add a reference to an
223 /// ### Why is this bad?
224 /// Using `as_ref()` or `as_mut()` instead is shorter.
228 /// let x: Option<()> = None;
231 /// let r: Option<&()> = match x {
233 /// Some(ref v) => Some(v),
237 /// let r: Option<&()> = x.as_ref();
241 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
244 declare_clippy_lint! {
246 /// Checks for wildcard enum matches using `_`.
248 /// ### Why is this bad?
249 /// New enum variants added by library updates can be missed.
251 /// ### Known problems
252 /// Suggested replacements may be incorrect if guards exhaustively cover some
253 /// variants, and also may not use correct path to enum if it's not present in the current scope.
257 /// # enum Foo { A(usize), B(usize) }
258 /// # let x = Foo::B(1);
271 pub WILDCARD_ENUM_MATCH_ARM,
273 "a wildcard enum match arm using `_`"
276 declare_clippy_lint! {
278 /// Checks for wildcard enum matches for a single variant.
280 /// ### Why is this bad?
281 /// New enum variants added by library updates can be missed.
283 /// ### Known problems
284 /// Suggested replacements may not use correct path to enum
285 /// if it's not present in the current scope.
289 /// # enum Foo { A, B, C }
290 /// # let x = Foo::B;
305 pub MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
307 "a wildcard enum match for a single variant"
310 declare_clippy_lint! {
312 /// Checks for wildcard pattern used with others patterns in same match arm.
314 /// ### Why is this bad?
315 /// Wildcard pattern already covers any other pattern as it will match anyway.
316 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
332 pub WILDCARD_IN_OR_PATTERNS,
334 "a wildcard pattern used with others patterns in same match arm"
337 declare_clippy_lint! {
339 /// Checks for matches being used to destructure a single-variant enum
340 /// or tuple struct where a `let` will suffice.
342 /// ### Why is this bad?
343 /// Just readability – `let` doesn't nest, whereas a `match` does.
351 /// let wrapper = Wrapper::Data(42);
353 /// let data = match wrapper {
354 /// Wrapper::Data(i) => i,
358 /// The correct use would be:
364 /// let wrapper = Wrapper::Data(42);
365 /// let Wrapper::Data(data) = wrapper;
367 pub INFALLIBLE_DESTRUCTURING_MATCH,
369 "a `match` statement with a single infallible arm instead of a `let`"
372 declare_clippy_lint! {
374 /// Checks for useless match that binds to only one value.
376 /// ### Why is this bad?
377 /// Readability and needless complexity.
379 /// ### Known problems
380 /// Suggested replacements may be incorrect when `match`
381 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
396 /// let (c, d) = (a, b);
398 pub MATCH_SINGLE_BINDING,
400 "a match with a single binding instead of using `let` statement"
403 declare_clippy_lint! {
405 /// Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
407 /// ### Why is this bad?
408 /// Correctness and readability. It's like having a wildcard pattern after
409 /// matching all enum variants explicitly.
413 /// # struct A { a: i32 }
414 /// let a = A { a: 5 };
418 /// A { a: 5, .. } => {},
424 /// A { a: 5 } => {},
428 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
430 "a match on a struct that binds all fields but still uses the wildcard pattern"
433 declare_clippy_lint! {
435 /// Lint for redundant pattern matching over `Result`, `Option`,
436 /// `std::task::Poll` or `std::net::IpAddr`
438 /// ### Why is this bad?
439 /// It's more concise and clear to just use the proper
442 /// ### Known problems
443 /// This will change the drop order for the matched type. Both `if let` and
444 /// `while let` will drop the value at the end of the block, both `if` and `while` will drop the
445 /// value before entering the block. For most types this change will not matter, but for a few
446 /// types this will not be an acceptable change (e.g. locks). See the
447 /// [reference](https://doc.rust-lang.org/reference/destructors.html#drop-scopes) for more about
452 /// # use std::task::Poll;
453 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
454 /// if let Ok(_) = Ok::<i32, i32>(42) {}
455 /// if let Err(_) = Err::<i32, i32>(42) {}
456 /// if let None = None::<()> {}
457 /// if let Some(_) = Some(42) {}
458 /// if let Poll::Pending = Poll::Pending::<()> {}
459 /// if let Poll::Ready(_) = Poll::Ready(42) {}
460 /// if let IpAddr::V4(_) = IpAddr::V4(Ipv4Addr::LOCALHOST) {}
461 /// if let IpAddr::V6(_) = IpAddr::V6(Ipv6Addr::LOCALHOST) {}
462 /// match Ok::<i32, i32>(42) {
468 /// The more idiomatic use would be:
471 /// # use std::task::Poll;
472 /// # use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
473 /// if Ok::<i32, i32>(42).is_ok() {}
474 /// if Err::<i32, i32>(42).is_err() {}
475 /// if None::<()>.is_none() {}
476 /// if Some(42).is_some() {}
477 /// if Poll::Pending::<()>.is_pending() {}
478 /// if Poll::Ready(42).is_ready() {}
479 /// if IpAddr::V4(Ipv4Addr::LOCALHOST).is_ipv4() {}
480 /// if IpAddr::V6(Ipv6Addr::LOCALHOST).is_ipv6() {}
481 /// Ok::<i32, i32>(42).is_ok();
483 pub REDUNDANT_PATTERN_MATCHING,
485 "use the proper utility function avoiding an `if let`"
488 declare_clippy_lint! {
490 /// Checks for `match` or `if let` expressions producing a
491 /// `bool` that could be written using `matches!`
493 /// ### Why is this bad?
494 /// Readability and needless complexity.
496 /// ### Known problems
497 /// This lint falsely triggers, if there are arms with
498 /// `cfg` attributes that remove an arm evaluating to `false`.
505 /// let a = match x {
510 /// let a = if let Some(0) = x {
517 /// let a = matches!(x, Some(0));
519 pub MATCH_LIKE_MATCHES_MACRO,
521 "a match that could be written with the matches! macro"
524 declare_clippy_lint! {
526 /// Checks for `match` with identical arm bodies.
528 /// ### Why is this bad?
529 /// This is probably a copy & paste error. If arm bodies
530 /// are the same on purpose, you can factor them
531 /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
533 /// ### Known problems
534 /// False positive possible with order dependent `match`
536 /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
543 /// Baz => bar(), // <= oops
547 /// This should probably be
552 /// Baz => baz(), // <= fixed
556 /// or if the original code was not a typo:
559 /// Bar | Baz => bar(), // <= shows the intent better
565 "`match` with identical arm bodies"
570 msrv: Option<RustcVersion>,
571 infallible_destructuring_match_linted: bool,
576 pub fn new(msrv: Option<RustcVersion>) -> Self {
584 impl_lint_pass!(Matches => [
589 MATCH_OVERLAPPING_ARM,
592 WILDCARD_ENUM_MATCH_ARM,
593 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
594 WILDCARD_IN_OR_PATTERNS,
595 MATCH_SINGLE_BINDING,
596 INFALLIBLE_DESTRUCTURING_MATCH,
597 REST_PAT_IN_FULLY_BOUND_STRUCTS,
598 REDUNDANT_PATTERN_MATCHING,
599 MATCH_LIKE_MATCHES_MACRO,
603 impl<'tcx> LateLintPass<'tcx> for Matches {
604 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
605 if in_external_macro(cx.sess(), expr.span) || in_macro(expr.span) {
609 redundant_pattern_match::check(cx, expr);
611 if meets_msrv(self.msrv.as_ref(), &msrvs::MATCHES_MACRO) {
612 if !check_match_like_matches(cx, expr) {
613 lint_match_arms(cx, expr);
616 lint_match_arms(cx, expr);
619 if let ExprKind::Match(ex, arms, MatchSource::Normal) = expr.kind {
620 check_single_match(cx, ex, arms, expr);
621 check_match_bool(cx, ex, arms, expr);
622 check_overlapping_arms(cx, ex, arms);
623 check_wild_err_arm(cx, ex, arms);
624 check_wild_enum_match(cx, ex, arms);
625 check_match_as_ref(cx, ex, arms, expr);
626 check_wild_in_or_pats(cx, arms);
628 if self.infallible_destructuring_match_linted {
629 self.infallible_destructuring_match_linted = false;
631 check_match_single_binding(cx, ex, arms, expr);
634 if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
635 check_match_ref_pats(cx, ex, arms.iter().map(|el| el.pat), expr);
637 if let Some(higher::IfLet { let_pat, let_expr, .. }) = higher::IfLet::hir(expr) {
638 check_match_ref_pats(cx, let_expr, once(let_pat), expr);
642 fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx Local<'_>) {
644 if !in_external_macro(cx.sess(), local.span);
645 if !in_macro(local.span);
646 if let Some(expr) = local.init;
647 if let ExprKind::Match(target, arms, MatchSource::Normal) = expr.kind;
648 if arms.len() == 1 && arms[0].guard.is_none();
649 if let PatKind::TupleStruct(
650 QPath::Resolved(None, variant_name), args, _) = arms[0].pat.kind;
652 if let PatKind::Binding(_, arg, ..) = strip_pat_refs(&args[0]).kind;
653 let body = remove_blocks(arms[0].body);
654 if path_to_local_id(body, arg);
657 let mut applicability = Applicability::MachineApplicable;
658 self.infallible_destructuring_match_linted = true;
661 INFALLIBLE_DESTRUCTURING_MATCH,
663 "you seem to be trying to use `match` to destructure a single infallible pattern. \
664 Consider using `let`",
668 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
669 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
670 snippet_with_applicability(cx, target.span, "..", &mut applicability),
678 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
680 if !in_external_macro(cx.sess(), pat.span);
681 if !in_macro(pat.span);
682 if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind;
683 if let Some(def_id) = path.res.opt_def_id();
684 let ty = cx.tcx.type_of(def_id);
685 if let ty::Adt(def, _) = ty.kind();
686 if def.is_struct() || def.is_union();
687 if fields.len() == def.non_enum_variant().fields.len();
692 REST_PAT_IN_FULLY_BOUND_STRUCTS,
694 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
696 "consider removing `..` from this binding",
702 extract_msrv_attr!(LateContext);
706 fn check_single_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
707 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
708 if in_macro(expr.span) {
709 // Don't lint match expressions present in
710 // macro_rules! block
713 if let PatKind::Or(..) = arms[0].pat.kind {
714 // don't lint for or patterns for now, this makes
715 // the lint noisy in unnecessary situations
718 let els = arms[1].body;
719 let els = if is_unit_expr(remove_blocks(els)) {
721 } else if let ExprKind::Block(Block { stmts, expr: block_expr, .. }, _) = els.kind {
722 if stmts.len() == 1 && block_expr.is_none() || stmts.is_empty() && block_expr.is_some() {
723 // single statement/expr "else" block, don't lint
726 // block with 2+ statements or 1 expr and 1+ statement
729 // not a block, don't lint
733 let ty = cx.typeck_results().expr_ty(ex);
734 if *ty.kind() != ty::Bool || is_lint_allowed(cx, MATCH_BOOL, ex.hir_id) {
735 check_single_match_single_pattern(cx, ex, arms, expr, els);
736 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
741 fn check_single_match_single_pattern(
742 cx: &LateContext<'_>,
746 els: Option<&Expr<'_>>,
748 if is_wild(arms[1].pat) {
749 report_single_match_single_pattern(cx, ex, arms, expr, els);
753 fn report_single_match_single_pattern(
754 cx: &LateContext<'_>,
758 els: Option<&Expr<'_>>,
760 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
761 let els_str = els.map_or(String::new(), |els| {
762 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
765 let (pat, pat_ref_count) = peel_hir_pat_refs(arms[0].pat);
766 let (msg, sugg) = if_chain! {
767 if let PatKind::Path(_) | PatKind::Lit(_) = pat.kind;
768 let (ty, ty_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(ex));
769 if let Some(spe_trait_id) = cx.tcx.lang_items().structural_peq_trait();
770 if let Some(pe_trait_id) = cx.tcx.lang_items().eq_trait();
771 if ty.is_integral() || ty.is_char() || ty.is_str()
772 || (implements_trait(cx, ty, spe_trait_id, &[])
773 && implements_trait(cx, ty, pe_trait_id, &[ty.into()]));
775 // scrutinee derives PartialEq and the pattern is a constant.
776 let pat_ref_count = match pat.kind {
777 // string literals are already a reference.
778 PatKind::Lit(Expr { kind: ExprKind::Lit(lit), .. }) if lit.node.is_str() => pat_ref_count + 1,
781 // References are only implicitly added to the pattern, so no overflow here.
782 // e.g. will work: match &Some(_) { Some(_) => () }
783 // will not: match Some(_) { &Some(_) => () }
784 let ref_count_diff = ty_ref_count - pat_ref_count;
786 // Try to remove address of expressions first.
787 let (ex, removed) = peel_n_hir_expr_refs(ex, ref_count_diff);
788 let ref_count_diff = ref_count_diff - removed;
790 let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
792 "if {} == {}{} {}{}",
793 snippet(cx, ex.span, ".."),
794 // PartialEq for different reference counts may not exist.
795 "&".repeat(ref_count_diff),
796 snippet(cx, arms[0].pat.span, ".."),
797 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
802 let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
804 "if let {} = {} {}{}",
805 snippet(cx, arms[0].pat.span, ".."),
806 snippet(cx, ex.span, ".."),
807 expr_block(cx, arms[0].body, None, "..", Some(expr.span)),
821 Applicability::HasPlaceholders,
825 fn check_single_match_opt_like(
826 cx: &LateContext<'_>,
831 els: Option<&Expr<'_>>,
833 // list of candidate `Enum`s we know will never get any more members
835 (&paths::COW, "Borrowed"),
836 (&paths::COW, "Cow::Borrowed"),
837 (&paths::COW, "Cow::Owned"),
838 (&paths::COW, "Owned"),
839 (&paths::OPTION, "None"),
840 (&paths::RESULT, "Err"),
841 (&paths::RESULT, "Ok"),
844 let path = match arms[1].pat.kind {
845 PatKind::TupleStruct(ref path, inner, _) => {
846 // Contains any non wildcard patterns (e.g., `Err(err)`)?
847 if !inner.iter().all(is_wild) {
850 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
852 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
853 PatKind::Path(ref path) => {
854 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
859 for &(ty_path, pat_path) in candidates {
860 if path == *pat_path && match_type(cx, ty, ty_path) {
861 report_single_match_single_pattern(cx, ex, arms, expr, els);
866 fn check_match_bool(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
867 // Type of expression is `bool`.
868 if *cx.typeck_results().expr_ty(ex).kind() == ty::Bool {
873 "you seem to be trying to match on a boolean expression",
877 let exprs = if let PatKind::Lit(arm_bool) = arms[0].pat.kind {
878 if let ExprKind::Lit(ref lit) = arm_bool.kind {
880 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
881 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
891 if let Some((true_expr, false_expr)) = exprs {
892 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
893 (false, false) => Some(format!(
895 snippet(cx, ex.span, "b"),
896 expr_block(cx, true_expr, None, "..", Some(expr.span)),
897 expr_block(cx, false_expr, None, "..", Some(expr.span))
899 (false, true) => Some(format!(
901 snippet(cx, ex.span, "b"),
902 expr_block(cx, true_expr, None, "..", Some(expr.span))
905 let test = Sugg::hir(cx, ex, "..");
909 expr_block(cx, false_expr, None, "..", Some(expr.span))
912 (true, true) => None,
915 if let Some(sugg) = sugg {
916 diag.span_suggestion(
918 "consider using an `if`/`else` expression",
920 Applicability::HasPlaceholders,
930 fn check_overlapping_arms<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
931 if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() {
932 let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex));
933 let type_ranges = type_ranges(&ranges);
934 if !type_ranges.is_empty() {
935 if let Some((start, end)) = overlapping(&type_ranges) {
938 MATCH_OVERLAPPING_ARM,
940 "some ranges overlap",
942 "overlaps with this",
949 fn check_wild_err_arm<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'tcx>, arms: &[Arm<'tcx>]) {
950 let ex_ty = cx.typeck_results().expr_ty(ex).peel_refs();
951 if is_type_diagnostic_item(cx, ex_ty, sym::result_type) {
953 if let PatKind::TupleStruct(ref path, inner, _) = arm.pat.kind {
954 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
955 if path_str == "Err" {
956 let mut matching_wild = inner.iter().any(is_wild);
957 let mut ident_bind_name = String::from("_");
959 // Looking for unused bindings (i.e.: `_e`)
960 for pat in inner.iter() {
961 if let PatKind::Binding(_, id, ident, None) = pat.kind {
962 if ident.as_str().starts_with('_')
963 && !LocalUsedVisitor::new(cx, id).check_expr(arm.body)
965 ident_bind_name = (&ident.name.as_str()).to_string();
966 matching_wild = true;
973 if let ExprKind::Block(block, _) = arm.body.kind;
974 if is_panic_block(block);
976 // `Err(_)` or `Err(_e)` arm with `panic!` found
977 span_lint_and_note(cx,
980 &format!("`Err({})` matches all errors", &ident_bind_name),
982 "match each error separately or use the error output, or use `.except(msg)` if the error case is unreachable",
992 enum CommonPrefixSearcher<'a> {
994 Path(&'a [PathSegment<'a>]),
997 impl CommonPrefixSearcher<'a> {
998 fn with_path(&mut self, path: &'a [PathSegment<'a>]) {
1000 [path @ .., _] => self.with_prefix(path),
1005 fn with_prefix(&mut self, path: &'a [PathSegment<'a>]) {
1007 Self::None => *self = Self::Path(path),
1008 Self::Path(self_path)
1011 .map(|p| p.ident.name)
1012 .eq(self_path.iter().map(|p| p.ident.name)) => {},
1013 Self::Path(_) => *self = Self::Mixed,
1019 fn is_hidden(cx: &LateContext<'_>, variant_def: &VariantDef) -> bool {
1020 let attrs = cx.tcx.get_attrs(variant_def.def_id);
1021 clippy_utils::attrs::is_doc_hidden(attrs) || clippy_utils::attrs::is_unstable(attrs)
1024 #[allow(clippy::too_many_lines)]
1025 fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
1026 let ty = cx.typeck_results().expr_ty(ex).peel_refs();
1027 let adt_def = match ty.kind() {
1029 if adt_def.is_enum()
1030 && !(is_type_diagnostic_item(cx, ty, sym::option_type)
1031 || is_type_diagnostic_item(cx, ty, sym::result_type)) =>
1038 // First pass - check for violation, but don't do much book-keeping because this is hopefully
1039 // the uncommon case, and the book-keeping is slightly expensive.
1040 let mut wildcard_span = None;
1041 let mut wildcard_ident = None;
1042 let mut has_non_wild = false;
1044 match peel_hir_pat_refs(arm.pat).0.kind {
1045 PatKind::Wild => wildcard_span = Some(arm.pat.span),
1046 PatKind::Binding(_, _, ident, None) => {
1047 wildcard_span = Some(arm.pat.span);
1048 wildcard_ident = Some(ident);
1050 _ => has_non_wild = true,
1053 let wildcard_span = match wildcard_span {
1054 Some(x) if has_non_wild => x,
1058 // Accumulate the variants which should be put in place of the wildcard because they're not
1060 let has_hidden = adt_def.variants.iter().any(|x| is_hidden(cx, x));
1061 let mut missing_variants: Vec<_> = adt_def.variants.iter().filter(|x| !is_hidden(cx, x)).collect();
1063 let mut path_prefix = CommonPrefixSearcher::None;
1065 // Guards mean that this case probably isn't exhaustively covered. Technically
1066 // this is incorrect, as we should really check whether each variant is exhaustively
1067 // covered by the set of guards that cover it, but that's really hard to do.
1068 recurse_or_patterns(arm.pat, |pat| {
1069 let path = match &peel_hir_pat_refs(pat).0.kind {
1070 PatKind::Path(path) => {
1071 #[allow(clippy::match_same_arms)]
1072 let id = match cx.qpath_res(path, pat.hir_id) {
1073 Res::Def(DefKind::Const | DefKind::ConstParam | DefKind::AnonConst, _) => return,
1074 Res::Def(_, id) => id,
1077 if arm.guard.is_none() {
1078 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1082 PatKind::TupleStruct(path, patterns, ..) => {
1083 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1084 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p)) {
1085 missing_variants.retain(|e| e.ctor_def_id != Some(id));
1090 PatKind::Struct(path, patterns, ..) => {
1091 if let Some(id) = cx.qpath_res(path, pat.hir_id).opt_def_id() {
1092 if arm.guard.is_none() && patterns.iter().all(|p| !is_refutable(cx, p.pat)) {
1093 missing_variants.retain(|e| e.def_id != id);
1101 QPath::Resolved(_, path) => path_prefix.with_path(path.segments),
1102 QPath::TypeRelative(
1104 kind: TyKind::Path(QPath::Resolved(_, path)),
1108 ) => path_prefix.with_prefix(path.segments),
1114 let format_suggestion = |variant: &VariantDef| {
1117 if let Some(ident) = wildcard_ident {
1118 format!("{} @ ", ident.name)
1122 if let CommonPrefixSearcher::Path(path_prefix) = path_prefix {
1123 let mut s = String::new();
1124 for seg in path_prefix {
1125 s.push_str(&seg.ident.as_str());
1130 let mut s = cx.tcx.def_path_str(adt_def.did);
1135 match variant.ctor_kind {
1136 CtorKind::Fn if variant.fields.len() == 1 => "(_)",
1137 CtorKind::Fn => "(..)",
1138 CtorKind::Const => "",
1139 CtorKind::Fictive => "{ .. }",
1144 match missing_variants.as_slice() {
1146 [x] if !adt_def.is_variant_list_non_exhaustive() && !has_hidden => span_lint_and_sugg(
1148 MATCH_WILDCARD_FOR_SINGLE_VARIANTS,
1150 "wildcard matches only a single variant and will also match any future added variants",
1152 format_suggestion(x),
1153 Applicability::MaybeIncorrect,
1156 let mut suggestions: Vec<_> = variants.iter().copied().map(format_suggestion).collect();
1157 let message = if adt_def.is_variant_list_non_exhaustive() || has_hidden {
1158 suggestions.push("_".into());
1159 "wildcard matches known variants and will also match future added variants"
1161 "wildcard match will also match any future added variants"
1166 WILDCARD_ENUM_MATCH_ARM,
1170 suggestions.join(" | "),
1171 Applicability::MaybeIncorrect,
1177 // If the block contains only a `panic!` macro (as expression or statement)
1178 fn is_panic_block(block: &Block<'_>) -> bool {
1179 match (&block.expr, block.stmts.len(), block.stmts.first()) {
1180 (&Some(exp), 0, _) => is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none(),
1181 (&None, 1, Some(stmt)) => {
1182 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
1188 fn check_match_ref_pats<'a, 'b, I>(cx: &LateContext<'_>, ex: &Expr<'_>, pats: I, expr: &Expr<'_>)
1191 I: Clone + Iterator<Item = &'a Pat<'b>>,
1193 if !has_only_ref_pats(pats.clone()) {
1197 let (first_sugg, msg, title);
1198 let span = ex.span.source_callsite();
1199 if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
1200 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
1202 title = "you don't need to add `&` to both the expression and the patterns";
1204 first_sugg = once((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
1205 msg = "instead of prefixing all patterns with `&`, you can dereference the expression";
1206 title = "you don't need to add `&` to all patterns";
1209 let remaining_suggs = pats.filter_map(|pat| {
1210 if let PatKind::Ref(ref refp, _) = pat.kind {
1211 Some((pat.span, snippet(cx, refp.span, "..").to_string()))
1217 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |diag| {
1218 if !expr.span.from_expansion() {
1219 multispan_sugg(diag, msg, first_sugg.chain(remaining_suggs));
1224 fn check_match_as_ref(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1225 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
1226 let arm_ref: Option<BindingAnnotation> = if is_none_arm(cx, &arms[0]) {
1227 is_ref_some_arm(cx, &arms[1])
1228 } else if is_none_arm(cx, &arms[1]) {
1229 is_ref_some_arm(cx, &arms[0])
1233 if let Some(rb) = arm_ref {
1234 let suggestion = if rb == BindingAnnotation::Ref {
1240 let output_ty = cx.typeck_results().expr_ty(expr);
1241 let input_ty = cx.typeck_results().expr_ty(ex);
1243 let cast = if_chain! {
1244 if let ty::Adt(_, substs) = input_ty.kind();
1245 let input_ty = substs.type_at(0);
1246 if let ty::Adt(_, substs) = output_ty.kind();
1247 let output_ty = substs.type_at(0);
1248 if let ty::Ref(_, output_ty, _) = *output_ty.kind();
1249 if input_ty != output_ty;
1257 let mut applicability = Applicability::MachineApplicable;
1262 &format!("use `{}()` instead", suggestion),
1266 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
1276 fn check_wild_in_or_pats(cx: &LateContext<'_>, arms: &[Arm<'_>]) {
1278 if let PatKind::Or(fields) = arm.pat.kind {
1279 // look for multiple fields in this arm that contains at least one Wild pattern
1280 if fields.len() > 1 && fields.iter().any(is_wild) {
1283 WILDCARD_IN_OR_PATTERNS,
1285 "wildcard pattern covers any other pattern as it will match anyway",
1287 "consider handling `_` separately",
1294 /// Lint a `match` or `if let .. { .. } else { .. }` expr that could be replaced by `matches!`
1295 fn check_match_like_matches<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
1296 if let Some(higher::IfLet {
1300 if_else: Some(if_else),
1301 }) = higher::IfLet::hir(expr)
1303 return find_matches_sugg(
1306 array::IntoIter::new([(&[][..], Some(let_pat), if_then, None), (&[][..], None, if_else, None)]),
1312 if let ExprKind::Match(scrut, arms, MatchSource::Normal) = expr.kind {
1313 return find_matches_sugg(
1316 arms.iter().map(|arm| {
1318 cx.tcx.hir().attrs(arm.hir_id),
1332 /// Lint a `match` or `if let` for replacement by `matches!`
1333 fn find_matches_sugg<'a, 'b, I>(
1334 cx: &LateContext<'_>,
1343 + DoubleEndedIterator
1348 Option<&'a Pat<'b>>,
1350 Option<&'a Guard<'b>>,
1356 if cx.typeck_results().expr_ty(expr).is_bool();
1357 if let Some((_, last_pat_opt, last_expr, _)) = iter.next_back();
1358 let iter_without_last = iter.clone();
1359 if let Some((first_attrs, _, first_expr, first_guard)) = iter.next();
1360 if let Some(b0) = find_bool_lit(&first_expr.kind, is_if_let);
1361 if let Some(b1) = find_bool_lit(&last_expr.kind, is_if_let);
1363 if first_guard.is_none() || iter.len() == 0;
1364 if first_attrs.is_empty();
1367 find_bool_lit(&arm.2.kind, is_if_let).map_or(false, |b| b == b0) && arm.3.is_none() && arm.0.is_empty()
1370 if let Some(ref last_pat) = last_pat_opt {
1371 if !is_wild(last_pat) {
1376 // The suggestion may be incorrect, because some arms can have `cfg` attributes
1377 // evaluated into `false` and so such arms will be stripped before.
1378 let mut applicability = Applicability::MaybeIncorrect;
1380 use itertools::Itertools as _;
1383 let pat_span = arm.1?.span;
1384 Some(snippet_with_applicability(cx, pat_span, "..", &mut applicability))
1388 let pat_and_guard = if let Some(Guard::If(g)) = first_guard {
1389 format!("{} if {}", pat, snippet_with_applicability(cx, g.span, "..", &mut applicability))
1394 // strip potential borrows (#6503), but only if the type is a reference
1395 let mut ex_new = ex;
1396 if let ExprKind::AddrOf(BorrowKind::Ref, .., ex_inner) = ex.kind {
1397 if let ty::Ref(..) = cx.typeck_results().expr_ty(ex_inner).kind() {
1403 MATCH_LIKE_MATCHES_MACRO,
1405 &format!("{} expression looks like `matches!` macro", if is_if_let { "if let .. else" } else { "match" }),
1408 "{}matches!({}, {})",
1409 if b0 { "" } else { "!" },
1410 snippet_with_applicability(cx, ex_new.span, "..", &mut applicability),
1422 /// Extract a `bool` or `{ bool }`
1423 fn find_bool_lit(ex: &ExprKind<'_>, is_if_let: bool) -> Option<bool> {
1425 ExprKind::Lit(Spanned {
1426 node: LitKind::Bool(b), ..
1436 if let ExprKind::Lit(Spanned {
1437 node: LitKind::Bool(b), ..
1449 #[allow(clippy::too_many_lines)]
1450 fn check_match_single_binding<'a>(cx: &LateContext<'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
1451 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
1456 // This is a hack to deal with arms that are excluded by macros like `#[cfg]`. It is only used here
1457 // to prevent false positives as there is currently no better way to detect if code was excluded by
1458 // a macro. See PR #6435
1460 if let Some(match_snippet) = snippet_opt(cx, expr.span);
1461 if let Some(arm_snippet) = snippet_opt(cx, arms[0].span);
1462 if let Some(ex_snippet) = snippet_opt(cx, ex.span);
1463 let rest_snippet = match_snippet.replace(&arm_snippet, "").replace(&ex_snippet, "");
1464 if rest_snippet.contains("=>");
1466 // The code it self contains another thick arrow "=>"
1467 // -> Either another arm or a comment
1472 let matched_vars = ex.span;
1473 let bind_names = arms[0].pat.span;
1474 let match_body = remove_blocks(arms[0].body);
1475 let mut snippet_body = if match_body.span.from_expansion() {
1476 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
1478 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
1481 // Do we need to add ';' to suggestion ?
1482 match match_body.kind {
1483 ExprKind::Block(block, _) => {
1484 // macro + expr_ty(body) == ()
1485 if block.span.from_expansion() && cx.typeck_results().expr_ty(match_body).is_unit() {
1486 snippet_body.push(';');
1490 // expr_ty(body) == ()
1491 if cx.typeck_results().expr_ty(match_body).is_unit() {
1492 snippet_body.push(';');
1497 let mut applicability = Applicability::MaybeIncorrect;
1498 match arms[0].pat.kind {
1499 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
1500 // If this match is in a local (`let`) stmt
1501 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
1503 parent_let_node.span,
1505 "let {} = {};\n{}let {} = {};",
1506 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1507 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1508 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
1509 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
1514 // If we are in closure, we need curly braces around suggestion
1515 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
1516 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
1517 if let Some(parent_expr) = get_parent_expr(cx, expr) {
1518 if let ExprKind::Closure(..) = parent_expr.kind {
1519 cbrace_end = format!("\n{}}}", indent);
1520 // Fix body indent due to the closure
1521 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1522 cbrace_start = format!("{{\n{}", indent);
1525 // If the parent is already an arm, and the body is another match statement,
1526 // we need curly braces around suggestion
1527 let parent_node_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1528 if let Node::Arm(arm) = &cx.tcx.hir().get(parent_node_id) {
1529 if let ExprKind::Match(..) = arm.body.kind {
1530 cbrace_end = format!("\n{}}}", indent);
1531 // Fix body indent due to the match
1532 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
1533 cbrace_start = format!("{{\n{}", indent);
1539 "{}let {} = {};\n{}{}{}",
1541 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
1542 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
1551 MATCH_SINGLE_BINDING,
1553 "this match could be written as a `let` statement",
1554 "consider using `let` statement",
1560 if ex.can_have_side_effects() {
1561 let indent = " ".repeat(indent_of(cx, expr.span).unwrap_or(0));
1564 snippet_with_applicability(cx, ex.span, "..", &mut applicability),
1570 MATCH_SINGLE_BINDING,
1572 "this match could be replaced by its scrutinee and body",
1573 "consider using the scrutinee and body instead",
1580 MATCH_SINGLE_BINDING,
1582 "this match could be replaced by its body itself",
1583 "consider using the match body instead",
1585 Applicability::MachineApplicable,
1593 /// Returns true if the `ex` match expression is in a local (`let`) statement
1594 fn opt_parent_let<'a>(cx: &LateContext<'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
1595 let map = &cx.tcx.hir();
1597 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
1598 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
1600 return Some(parent_let_expr);
1606 /// Gets all arms that are unbounded `PatRange`s.
1607 fn all_ranges<'tcx>(cx: &LateContext<'tcx>, arms: &'tcx [Arm<'_>], ty: Ty<'tcx>) -> Vec<SpannedRange<Constant>> {
1610 if let Arm { pat, guard: None, .. } = *arm {
1611 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1612 let lhs = match lhs {
1613 Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0,
1614 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1616 let rhs = match rhs {
1617 Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0,
1618 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1620 let rhs = match range_end {
1621 RangeEnd::Included => Bound::Included(rhs),
1622 RangeEnd::Excluded => Bound::Excluded(rhs),
1624 return Some(SpannedRange {
1630 if let PatKind::Lit(value) = pat.kind {
1631 let value = constant(cx, cx.typeck_results(), value)?.0;
1632 return Some(SpannedRange {
1634 node: (value.clone(), Bound::Included(value)),
1643 #[derive(Debug, Eq, PartialEq)]
1644 pub struct SpannedRange<T> {
1646 pub node: (T, Bound<T>),
1649 type TypedRanges = Vec<SpannedRange<u128>>;
1651 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1652 /// and other types than
1653 /// `Uint` and `Int` probably don't make sense.
1654 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1657 .filter_map(|range| match range.node {
1658 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1660 node: (start, Bound::Included(end)),
1662 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1664 node: (start, Bound::Excluded(end)),
1666 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1668 node: (start, Bound::Unbounded),
1675 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1677 ExprKind::Tup(v) if v.is_empty() => true,
1678 ExprKind::Block(b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1683 // Checks if arm has the form `None => None`
1684 fn is_none_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool {
1685 matches!(arm.pat.kind, PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone))
1688 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1689 fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotation> {
1691 if let PatKind::TupleStruct(ref qpath, [first_pat, ..], _) = arm.pat.kind;
1692 if is_lang_ctor(cx, qpath, OptionSome);
1693 if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
1694 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1695 if let ExprKind::Call(e, args) = remove_blocks(arm.body).kind;
1696 if let ExprKind::Path(ref some_path) = e.kind;
1697 if is_lang_ctor(cx, some_path, OptionSome) && args.len() == 1;
1698 if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
1699 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1707 fn has_only_ref_pats<'a, 'b, I>(pats: I) -> bool
1710 I: Iterator<Item = &'a Pat<'b>>,
1712 let mut at_least_one_is_true = false;
1713 for opt in pats.map(|pat| match pat.kind {
1714 PatKind::Ref(..) => Some(true), // &-patterns
1715 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1716 _ => None, // any other pattern is not fine
1718 if let Some(inner) = opt {
1720 at_least_one_is_true = true;
1726 at_least_one_is_true
1729 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1733 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1735 Start(T, &'a SpannedRange<T>),
1736 End(Bound<T>, &'a SpannedRange<T>),
1739 impl<'a, T: Copy> Kind<'a, T> {
1740 fn range(&self) -> &'a SpannedRange<T> {
1742 Kind::Start(_, r) | Kind::End(_, r) => r,
1746 fn value(self) -> Bound<T> {
1748 Kind::Start(t, _) => Bound::Included(t),
1749 Kind::End(t, _) => t,
1754 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1755 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1756 Some(self.cmp(other))
1760 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1761 fn cmp(&self, other: &Self) -> Ordering {
1762 match (self.value(), other.value()) {
1763 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1764 // Range patterns cannot be unbounded (yet)
1765 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1766 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1767 Ordering::Equal => Ordering::Greater,
1770 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1771 Ordering::Equal => Ordering::Less,
1778 let mut values = Vec::with_capacity(2 * ranges.len());
1781 values.push(Kind::Start(r.node.0, r));
1782 values.push(Kind::End(r.node.1, r));
1787 for (a, b) in iter::zip(&values, values.iter().skip(1)) {
1789 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1790 if ra.node != rb.node {
1791 return Some((ra, rb));
1794 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1796 // skip if the range `a` is completely included into the range `b`
1797 if let Ordering::Equal | Ordering::Less = a.cmp(b) {
1798 let kind_a = Kind::End(a.range().node.1, a.range());
1799 let kind_b = Kind::End(b.range().node.1, b.range());
1800 if let Ordering::Equal | Ordering::Greater = kind_a.cmp(&kind_b) {
1804 return Some((a.range(), b.range()));
1812 mod redundant_pattern_match {
1813 use super::REDUNDANT_PATTERN_MATCHING;
1814 use clippy_utils::diagnostics::span_lint_and_then;
1815 use clippy_utils::higher;
1816 use clippy_utils::source::{snippet, snippet_with_applicability};
1817 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, is_type_lang_item, match_type};
1818 use clippy_utils::{is_lang_ctor, is_qpath_def_path, is_trait_method, paths};
1819 use if_chain::if_chain;
1820 use rustc_ast::ast::LitKind;
1821 use rustc_data_structures::fx::FxHashSet;
1822 use rustc_errors::Applicability;
1823 use rustc_hir::LangItem::{OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk};
1825 intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
1826 Arm, Block, Expr, ExprKind, LangItem, MatchSource, Node, Pat, PatKind, QPath,
1828 use rustc_lint::LateContext;
1829 use rustc_middle::ty::{self, subst::GenericArgKind, Ty};
1830 use rustc_span::sym;
1832 pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1833 if let Some(higher::IfLet {
1838 }) = higher::IfLet::ast(cx, expr)
1840 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "if", if_else.is_some())
1842 if let ExprKind::Match(op, arms, MatchSource::Normal) = &expr.kind {
1843 find_sugg_for_match(cx, expr, op, arms)
1845 if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) {
1846 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "while", false)
1850 /// Checks if the drop order for a type matters. Some std types implement drop solely to
1851 /// deallocate memory. For these types, and composites containing them, changing the drop order
1852 /// won't result in any observable side effects.
1853 fn type_needs_ordered_drop(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1854 type_needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
1857 fn type_needs_ordered_drop_inner(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
1858 if !seen.insert(ty) {
1861 if !ty.needs_drop(cx.tcx, cx.param_env) {
1867 .map_or(false, |id| implements_trait(cx, ty, id, &[]))
1869 // This type doesn't implement drop, so no side effects here.
1870 // Check if any component type has any.
1872 ty::Tuple(_) => ty.tuple_fields().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1873 ty::Array(ty, _) => type_needs_ordered_drop_inner(cx, ty, seen),
1874 ty::Adt(adt, subs) => adt
1876 .map(|f| f.ty(cx.tcx, subs))
1877 .any(|ty| type_needs_ordered_drop_inner(cx, ty, seen)),
1881 // Check for std types which implement drop, but only for memory allocation.
1882 else if is_type_diagnostic_item(cx, ty, sym::vec_type)
1883 || is_type_lang_item(cx, ty, LangItem::OwnedBox)
1884 || is_type_diagnostic_item(cx, ty, sym::Rc)
1885 || is_type_diagnostic_item(cx, ty, sym::Arc)
1886 || is_type_diagnostic_item(cx, ty, sym::cstring_type)
1887 || is_type_diagnostic_item(cx, ty, sym::BTreeMap)
1888 || is_type_diagnostic_item(cx, ty, sym::LinkedList)
1889 || match_type(cx, ty, &paths::WEAK_RC)
1890 || match_type(cx, ty, &paths::WEAK_ARC)
1892 // Check all of the generic arguments.
1893 if let ty::Adt(_, subs) = ty.kind() {
1894 subs.types().any(|ty| type_needs_ordered_drop_inner(cx, ty, seen))
1903 // Extract the generic arguments out of a type
1904 fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
1906 if let ty::Adt(_, subs) = ty.kind();
1907 if let Some(sub) = subs.get(index);
1908 if let GenericArgKind::Type(sub_ty) = sub.unpack();
1917 // Checks if there are any temporaries created in the given expression for which drop order
1919 fn temporaries_need_ordered_drop(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1920 struct V<'a, 'tcx> {
1921 cx: &'a LateContext<'tcx>,
1924 impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
1925 type Map = ErasedMap<'tcx>;
1926 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1927 NestedVisitorMap::None
1930 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
1932 // Taking the reference of a value leaves a temporary
1933 // e.g. In `&String::new()` the string is a temporary value.
1934 // Remaining fields are temporary values
1935 // e.g. In `(String::new(), 0).1` the string is a temporary value.
1936 ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
1937 if !matches!(expr.kind, ExprKind::Path(_)) {
1938 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
1941 self.visit_expr(expr);
1945 // the base type is alway taken by reference.
1946 // e.g. In `(vec![0])[0]` the vector is a temporary value.
1947 ExprKind::Index(base, index) => {
1948 if !matches!(base.kind, ExprKind::Path(_)) {
1949 if type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
1952 self.visit_expr(base);
1955 self.visit_expr(index);
1957 // Method calls can take self by reference.
1958 // e.g. In `String::new().len()` the string is a temporary value.
1959 ExprKind::MethodCall(_, _, [self_arg, args @ ..], _) => {
1960 if !matches!(self_arg.kind, ExprKind::Path(_)) {
1961 let self_by_ref = self
1964 .type_dependent_def_id(expr.hir_id)
1965 .map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
1967 && type_needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg))
1971 self.visit_expr(self_arg);
1974 args.iter().for_each(|arg| self.visit_expr(arg));
1976 // Either explicitly drops values, or changes control flow.
1977 ExprKind::DropTemps(_)
1979 | ExprKind::Break(..)
1980 | ExprKind::Yield(..)
1981 | ExprKind::Block(Block { expr: None, .. }, _)
1982 | ExprKind::Loop(..) => (),
1984 // Only consider the final expression.
1985 ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
1987 _ => walk_expr(self, expr),
1992 let mut v = V { cx, res: false };
1997 fn find_sugg_for_if_let<'tcx>(
1998 cx: &LateContext<'tcx>,
1999 expr: &'tcx Expr<'_>,
2001 let_expr: &'tcx Expr<'_>,
2002 keyword: &'static str,
2005 // also look inside refs
2006 let mut kind = &let_pat.kind;
2007 // if we have &None for example, peel it so we can detect "if let None = x"
2008 if let PatKind::Ref(inner, _mutability) = kind {
2011 let op_ty = cx.typeck_results().expr_ty(let_expr);
2012 // Determine which function should be used, and the type contained by the corresponding
2014 let (good_method, inner_ty) = match kind {
2015 PatKind::TupleStruct(ref path, [sub_pat], _) => {
2016 if let PatKind::Wild = sub_pat.kind {
2017 if is_lang_ctor(cx, path, ResultOk) {
2018 ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
2019 } else if is_lang_ctor(cx, path, ResultErr) {
2020 ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
2021 } else if is_lang_ctor(cx, path, OptionSome) {
2022 ("is_some()", op_ty)
2023 } else if is_lang_ctor(cx, path, PollReady) {
2024 ("is_ready()", op_ty)
2025 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V4) {
2026 ("is_ipv4()", op_ty)
2027 } else if is_qpath_def_path(cx, path, sub_pat.hir_id, &paths::IPADDR_V6) {
2028 ("is_ipv6()", op_ty)
2036 PatKind::Path(ref path) => {
2037 let method = if is_lang_ctor(cx, path, OptionNone) {
2039 } else if is_lang_ctor(cx, path, PollPending) {
2044 // `None` and `Pending` don't have an inner type.
2045 (method, cx.tcx.types.unit)
2050 // If this is the last expression in a block or there is an else clause then the whole
2051 // type needs to be considered, not just the inner type of the branch being matched on.
2052 // Note the last expression in a block is dropped after all local bindings.
2053 let check_ty = if has_else
2054 || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
2061 // All temporaries created in the scrutinee expression are dropped at the same time as the
2062 // scrutinee would be, so they have to be considered as well.
2063 // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
2064 // for the duration if body.
2065 let needs_drop = type_needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
2067 // check that `while_let_on_iterator` lint does not trigger
2069 if keyword == "while";
2070 if let ExprKind::MethodCall(method_path, _, _, _) = let_expr.kind;
2071 if method_path.ident.name == sym::next;
2072 if is_trait_method(cx, let_expr, sym::Iterator);
2078 let result_expr = match &let_expr.kind {
2079 ExprKind::AddrOf(_, _, borrowed) => borrowed,
2084 REDUNDANT_PATTERN_MATCHING,
2086 &format!("redundant pattern matching, consider using `{}`", good_method),
2088 // if/while let ... = ... { ... }
2089 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2090 let expr_span = expr.span;
2092 // if/while let ... = ... { ... }
2094 let op_span = result_expr.span.source_callsite();
2096 // if/while let ... = ... { ... }
2097 // ^^^^^^^^^^^^^^^^^^^
2098 let span = expr_span.until(op_span.shrink_to_hi());
2100 let mut app = if needs_drop {
2101 Applicability::MaybeIncorrect
2103 Applicability::MachineApplicable
2105 let sugg = snippet_with_applicability(cx, op_span, "_", &mut app);
2107 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
2110 diag.note("this will change drop order of the result, as well as all temporaries");
2111 diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
2117 fn find_sugg_for_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
2118 if arms.len() == 2 {
2119 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
2121 let found_good_method = match node_pair {
2123 PatKind::TupleStruct(ref path_left, patterns_left, _),
2124 PatKind::TupleStruct(ref path_right, patterns_right, _),
2125 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
2126 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
2127 find_good_method_for_match(
2138 find_good_method_for_match(
2153 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
2154 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
2155 if patterns.len() == 1 =>
2157 if let PatKind::Wild = patterns[0].kind {
2158 find_good_method_for_match(
2163 &paths::OPTION_SOME,
2164 &paths::OPTION_NONE,
2169 find_good_method_for_match(
2175 &paths::POLL_PENDING,
2187 if let Some(good_method) = found_good_method {
2188 let span = expr.span.to(op.span);
2189 let result_expr = match &op.kind {
2190 ExprKind::AddrOf(_, _, borrowed) => borrowed,
2195 REDUNDANT_PATTERN_MATCHING,
2197 &format!("redundant pattern matching, consider using `{}`", good_method),
2199 diag.span_suggestion(
2202 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
2203 Applicability::MaybeIncorrect, // snippet
2211 #[allow(clippy::too_many_arguments)]
2212 fn find_good_method_for_match<'a>(
2213 cx: &LateContext<'_>,
2215 path_left: &QPath<'_>,
2216 path_right: &QPath<'_>,
2217 expected_left: &[&str],
2218 expected_right: &[&str],
2219 should_be_left: &'a str,
2220 should_be_right: &'a str,
2221 ) -> Option<&'a str> {
2222 let body_node_pair = if is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_left)
2223 && is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_right)
2225 (&(*arms[0].body).kind, &(*arms[1].body).kind)
2226 } else if is_qpath_def_path(cx, path_right, arms[1].pat.hir_id, expected_left)
2227 && is_qpath_def_path(cx, path_left, arms[0].pat.hir_id, expected_right)
2229 (&(*arms[1].body).kind, &(*arms[0].body).kind)
2234 match body_node_pair {
2235 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
2236 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
2237 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),
2246 fn test_overlapping() {
2247 use rustc_span::source_map::DUMMY_SP;
2249 let sp = |s, e| SpannedRange {
2254 assert_eq!(None, overlapping::<u8>(&[]));
2255 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
2258 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
2263 sp(1, Bound::Included(4)),
2264 sp(5, Bound::Included(6)),
2265 sp(10, Bound::Included(11))
2269 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
2270 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
2273 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
2275 sp(1, Bound::Included(4)),
2276 sp(5, Bound::Included(6)),
2277 sp(6, Bound::Included(11))
2282 /// Implementation of `MATCH_SAME_ARMS`.
2283 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
2284 if let ExprKind::Match(_, arms, MatchSource::Normal) = expr.kind {
2285 let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
2286 let mut h = SpanlessHash::new(cx);
2287 h.hash_expr(arm.body);
2291 let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
2292 let min_index = usize::min(lindex, rindex);
2293 let max_index = usize::max(lindex, rindex);
2295 let mut local_map: HirIdMap<HirId> = HirIdMap::default();
2296 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
2298 if let Some(a_id) = path_to_local(a);
2299 if let Some(b_id) = path_to_local(b);
2300 let entry = match local_map.entry(a_id) {
2301 Entry::Vacant(entry) => entry,
2302 // check if using the same bindings as before
2303 Entry::Occupied(entry) => return *entry.get() == b_id,
2305 // the names technically don't have to match; this makes the lint more conservative
2306 if cx.tcx.hir().name(a_id) == cx.tcx.hir().name(b_id);
2307 if TyS::same_type(cx.typeck_results().expr_ty(a), cx.typeck_results().expr_ty(b));
2308 if pat_contains_local(lhs.pat, a_id);
2309 if pat_contains_local(rhs.pat, b_id);
2318 // Arms with a guard are ignored, those can’t always be merged together
2319 // This is also the case for arms in-between each there is an arm with a guard
2320 (min_index..=max_index).all(|index| arms[index].guard.is_none())
2321 && SpanlessEq::new(cx)
2322 .expr_fallback(eq_fallback)
2323 .eq_expr(lhs.body, rhs.body)
2324 // these checks could be removed to allow unused bindings
2325 && bindings_eq(lhs.pat, local_map.keys().copied().collect())
2326 && bindings_eq(rhs.pat, local_map.values().copied().collect())
2329 let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
2330 for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
2335 "this `match` has identical arm bodies",
2337 diag.span_note(i.body.span, "same as this");
2339 // Note: this does not use `span_suggestion` on purpose:
2340 // there is no clean way
2341 // to remove the other arm. Building a span and suggest to replace it to ""
2342 // makes an even more confusing error message. Also in order not to make up a
2343 // span for the whole pattern, the suggestion is only shown when there is only
2344 // one pattern. The user should know about `|` if they are already using it…
2346 let lhs = snippet(cx, i.pat.span, "<pat1>");
2347 let rhs = snippet(cx, j.pat.span, "<pat2>");
2349 if let PatKind::Wild = j.pat.kind {
2350 // if the last arm is _, then i could be integrated into _
2351 // note that i.pat cannot be _, because that would mean that we're
2352 // hiding all the subsequent arms, and rust won't compile
2356 "`{}` has the same arm body as the `_` wildcard, consider removing it",
2361 diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs,))
2362 .help("...or consider changing the match arm bodies");
2370 fn pat_contains_local(pat: &Pat<'_>, id: HirId) -> bool {
2371 let mut result = false;
2372 pat.walk_short(|p| {
2373 result |= matches!(p.kind, PatKind::Binding(_, binding_id, ..) if binding_id == id);
2379 /// Returns true if all the bindings in the `Pat` are in `ids` and vice versa
2380 fn bindings_eq(pat: &Pat<'_>, mut ids: HirIdSet) -> bool {
2381 let mut result = true;
2382 pat.each_binding_or_first(&mut |_, id, _, _| result &= ids.remove(&id));
2383 result && ids.is_empty()