1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::usage::is_unused;
6 expr_block, get_arg_name, get_parent_expr, in_macro, indent_of, is_allowed, is_expn_of, is_refutable,
7 is_type_diagnostic_item, is_wild, match_qpath, match_type, match_var, multispan_sugg, remove_blocks, snippet,
8 snippet_block, snippet_with_applicability, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
9 span_lint_and_then, walk_ptrs_ty,
11 use if_chain::if_chain;
12 use rustc_ast::ast::LitKind;
13 use rustc_errors::Applicability;
14 use rustc_hir::def::CtorKind;
16 Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Local, MatchSource, Mutability, Node, Pat, PatKind,
19 use rustc_lint::{LateContext, LateLintPass, LintContext};
20 use rustc_middle::lint::in_external_macro;
21 use rustc_middle::ty::{self, Ty};
22 use rustc_session::{declare_tool_lint, impl_lint_pass};
23 use rustc_span::source_map::Span;
24 use std::cmp::Ordering;
25 use std::collections::Bound;
27 declare_clippy_lint! {
28 /// **What it does:** Checks for matches with a single arm where an `if let`
29 /// will usually suffice.
31 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
33 /// **Known problems:** None.
37 /// # fn bar(stool: &str) {}
38 /// # let x = Some("abc");
40 /// Some(ref foo) => bar(foo),
46 "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
49 declare_clippy_lint! {
50 /// **What it does:** Checks for matches with two arms where an `if let else` will
53 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
55 /// **Known problems:** Personal style preferences may differ.
62 /// # fn bar(foo: &usize) {}
63 /// # let other_ref: usize = 1;
64 /// # let x: Option<&usize> = Some(&1);
66 /// Some(ref foo) => bar(foo),
67 /// _ => bar(&other_ref),
71 /// Using `if let` with `else`:
74 /// # fn bar(foo: &usize) {}
75 /// # let other_ref: usize = 1;
76 /// # let x: Option<&usize> = Some(&1);
77 /// if let Some(ref foo) = x {
83 pub SINGLE_MATCH_ELSE,
85 "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
88 declare_clippy_lint! {
89 /// **What it does:** Checks for matches where all arms match a reference,
90 /// suggesting to remove the reference and deref the matched expression
91 /// instead. It also checks for `if let &foo = bar` blocks.
93 /// **Why is this bad?** It just makes the code less readable. That reference
94 /// destructuring adds nothing to the code.
96 /// **Known problems:** None.
101 /// &A(ref y) => foo(y),
108 "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
111 declare_clippy_lint! {
112 /// **What it does:** Checks for matches where match expression is a `bool`. It
113 /// suggests to replace the expression with an `if...else` block.
115 /// **Why is this bad?** It makes the code less readable.
117 /// **Known problems:** None.
123 /// let condition: bool = true;
124 /// match condition {
129 /// Use if/else instead:
133 /// let condition: bool = true;
142 "a `match` on a boolean expression instead of an `if..else` block"
145 declare_clippy_lint! {
146 /// **What it does:** Checks for overlapping match arms.
148 /// **Why is this bad?** It is likely to be an error and if not, makes the code
151 /// **Known problems:** None.
157 /// 1...10 => println!("1 ... 10"),
158 /// 5...15 => println!("5 ... 15"),
162 pub MATCH_OVERLAPPING_ARM,
164 "a `match` with overlapping arms"
167 declare_clippy_lint! {
168 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
169 /// and take drastic actions like `panic!`.
171 /// **Why is this bad?** It is generally a bad practice, just like
172 /// catching all exceptions in java with `catch(Exception)`
174 /// **Known problems:** None.
178 /// let x: Result<i32, &str> = Ok(3);
180 /// Ok(_) => println!("ok"),
181 /// Err(_) => panic!("err"),
184 pub MATCH_WILD_ERR_ARM,
186 "a `match` with `Err(_)` arm and take drastic actions"
189 declare_clippy_lint! {
190 /// **What it does:** Checks for match which is used to add a reference to an
193 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
195 /// **Known problems:** None.
199 /// let x: Option<()> = None;
200 /// let r: Option<&()> = match x {
202 /// Some(ref v) => Some(v),
207 "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
210 declare_clippy_lint! {
211 /// **What it does:** Checks for wildcard enum matches using `_`.
213 /// **Why is this bad?** New enum variants added by library updates can be missed.
215 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
216 /// variants, and also may not use correct path to enum if it's not present in the current scope.
220 /// # enum Foo { A(usize), B(usize) }
221 /// # let x = Foo::B(1);
227 pub WILDCARD_ENUM_MATCH_ARM,
229 "a wildcard enum match arm using `_`"
232 declare_clippy_lint! {
233 /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
235 /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
236 /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
238 /// **Known problems:** None.
247 pub WILDCARD_IN_OR_PATTERNS,
249 "a wildcard pattern used with others patterns in same match arm"
252 declare_clippy_lint! {
253 /// **What it does:** Checks for matches being used to destructure a single-variant enum
254 /// or tuple struct where a `let` will suffice.
256 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
258 /// **Known problems:** None.
266 /// let wrapper = Wrapper::Data(42);
268 /// let data = match wrapper {
269 /// Wrapper::Data(i) => i,
273 /// The correct use would be:
279 /// let wrapper = Wrapper::Data(42);
280 /// let Wrapper::Data(data) = wrapper;
282 pub INFALLIBLE_DESTRUCTURING_MATCH,
284 "a `match` statement with a single infallible arm instead of a `let`"
287 declare_clippy_lint! {
288 /// **What it does:** Checks for useless match that binds to only one value.
290 /// **Why is this bad?** Readability and needless complexity.
292 /// **Known problems:** Suggested replacements may be incorrect when `match`
293 /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
308 /// let (c, d) = (a, b);
310 pub MATCH_SINGLE_BINDING,
312 "a match with a single binding instead of using `let` statement"
315 declare_clippy_lint! {
316 /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
318 /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
319 /// matching all enum variants explicitly.
321 /// **Known problems:** None.
325 /// # struct A { a: i32 }
326 /// let a = A { a: 5 };
330 /// A { a: 5, .. } => {},
336 /// A { a: 5 } => {},
340 pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
342 "a match on a struct that binds all fields but still uses the wildcard pattern"
347 infallible_destructuring_match_linted: bool,
350 impl_lint_pass!(Matches => [
355 MATCH_OVERLAPPING_ARM,
358 WILDCARD_ENUM_MATCH_ARM,
359 WILDCARD_IN_OR_PATTERNS,
360 MATCH_SINGLE_BINDING,
361 INFALLIBLE_DESTRUCTURING_MATCH,
362 REST_PAT_IN_FULLY_BOUND_STRUCTS
365 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
366 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
367 if in_external_macro(cx.sess(), expr.span) {
370 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
371 check_single_match(cx, ex, arms, expr);
372 check_match_bool(cx, ex, arms, expr);
373 check_overlapping_arms(cx, ex, arms);
374 check_wild_err_arm(cx, ex, arms);
375 check_wild_enum_match(cx, ex, arms);
376 check_match_as_ref(cx, ex, arms, expr);
377 check_wild_in_or_pats(cx, arms);
379 if self.infallible_destructuring_match_linted {
380 self.infallible_destructuring_match_linted = false;
382 check_match_single_binding(cx, ex, arms, expr);
385 if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
386 check_match_ref_pats(cx, ex, arms, expr);
390 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
392 if !in_external_macro(cx.sess(), local.span);
393 if !in_macro(local.span);
394 if let Some(ref expr) = local.init;
395 if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
396 if arms.len() == 1 && arms[0].guard.is_none();
397 if let PatKind::TupleStruct(
398 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
400 if let Some(arg) = get_arg_name(&args[0]);
401 let body = remove_blocks(&arms[0].body);
402 if match_var(body, arg);
405 let mut applicability = Applicability::MachineApplicable;
406 self.infallible_destructuring_match_linted = true;
409 INFALLIBLE_DESTRUCTURING_MATCH,
411 "you seem to be trying to use `match` to destructure a single infallible pattern. \
412 Consider using `let`",
416 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
417 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
418 snippet_with_applicability(cx, target.span, "..", &mut applicability),
426 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat<'_>) {
428 if !in_external_macro(cx.sess(), pat.span);
429 if !in_macro(pat.span);
430 if let PatKind::Struct(ref qpath, fields, true) = pat.kind;
431 if let QPath::Resolved(_, ref path) = qpath;
432 if let Some(def_id) = path.res.opt_def_id();
433 let ty = cx.tcx.type_of(def_id);
434 if let ty::Adt(def, _) = ty.kind;
435 if def.is_struct() || def.is_union();
436 if fields.len() == def.non_enum_variant().fields.len();
441 REST_PAT_IN_FULLY_BOUND_STRUCTS,
443 "unnecessary use of `..` pattern in struct binding. All fields were already bound",
444 "consider removing `..` from this binding",
452 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
453 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
454 if in_macro(expr.span) {
455 // Don't lint match expressions present in
456 // macro_rules! block
459 if let PatKind::Or(..) = arms[0].pat.kind {
460 // don't lint for or patterns for now, this makes
461 // the lint noisy in unnecessary situations
464 let els = remove_blocks(&arms[1].body);
465 let els = if is_unit_expr(els) {
467 } else if let ExprKind::Block(_, _) = els.kind {
468 // matches with blocks that contain statements are prettier as `if let + else`
471 // allow match arms with just expressions
474 let ty = cx.tables.expr_ty(ex);
475 if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
476 check_single_match_single_pattern(cx, ex, arms, expr, els);
477 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
482 fn check_single_match_single_pattern(
483 cx: &LateContext<'_, '_>,
487 els: Option<&Expr<'_>>,
489 if is_wild(&arms[1].pat) {
490 report_single_match_single_pattern(cx, ex, arms, expr, els);
494 fn report_single_match_single_pattern(
495 cx: &LateContext<'_, '_>,
499 els: Option<&Expr<'_>>,
501 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
502 let els_str = els.map_or(String::new(), |els| {
503 format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
509 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
513 "if let {} = {} {}{}",
514 snippet(cx, arms[0].pat.span, ".."),
515 snippet(cx, ex.span, ".."),
516 expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
519 Applicability::HasPlaceholders,
523 fn check_single_match_opt_like(
524 cx: &LateContext<'_, '_>,
529 els: Option<&Expr<'_>>,
531 // list of candidate `Enum`s we know will never get any more members
533 (&paths::COW, "Borrowed"),
534 (&paths::COW, "Cow::Borrowed"),
535 (&paths::COW, "Cow::Owned"),
536 (&paths::COW, "Owned"),
537 (&paths::OPTION, "None"),
538 (&paths::RESULT, "Err"),
539 (&paths::RESULT, "Ok"),
542 let path = match arms[1].pat.kind {
543 PatKind::TupleStruct(ref path, ref inner, _) => {
544 // Contains any non wildcard patterns (e.g., `Err(err)`)?
545 if !inner.iter().all(is_wild) {
548 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
550 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
551 PatKind::Path(ref path) => {
552 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
557 for &(ty_path, pat_path) in candidates {
558 if path == *pat_path && match_type(cx, ty, ty_path) {
559 report_single_match_single_pattern(cx, ex, arms, expr, els);
564 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
565 // Type of expression is `bool`.
566 if cx.tables.expr_ty(ex).kind == ty::Bool {
571 "you seem to be trying to match on a boolean expression",
575 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
576 if let ExprKind::Lit(ref lit) = arm_bool.kind {
578 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
579 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
589 if let Some((true_expr, false_expr)) = exprs {
590 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
591 (false, false) => Some(format!(
593 snippet(cx, ex.span, "b"),
594 expr_block(cx, true_expr, None, "..", Some(expr.span)),
595 expr_block(cx, false_expr, None, "..", Some(expr.span))
597 (false, true) => Some(format!(
599 snippet(cx, ex.span, "b"),
600 expr_block(cx, true_expr, None, "..", Some(expr.span))
603 let test = Sugg::hir(cx, ex, "..");
607 expr_block(cx, false_expr, None, "..", Some(expr.span))
610 (true, true) => None,
613 if let Some(sugg) = sugg {
616 "consider using an `if`/`else` expression",
618 Applicability::HasPlaceholders,
628 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
629 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
630 let ranges = all_ranges(cx, arms, cx.tables.expr_ty(ex));
631 let type_ranges = type_ranges(&ranges);
632 if !type_ranges.is_empty() {
633 if let Some((start, end)) = overlapping(&type_ranges) {
636 MATCH_OVERLAPPING_ARM,
638 "some ranges overlap",
640 "overlaps with this",
647 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
648 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
649 if is_type_diagnostic_item(cx, ex_ty, sym!(result_type)) {
651 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
652 let path_str = rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false));
653 if path_str == "Err" {
654 let mut matching_wild = inner.iter().any(is_wild);
655 let mut ident_bind_name = String::from("_");
657 // Looking for unused bindings (i.e.: `_e`)
658 inner.iter().for_each(|pat| {
659 if let PatKind::Binding(.., ident, None) = &pat.kind {
660 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
661 ident_bind_name = (&ident.name.as_str()).to_string();
662 matching_wild = true;
669 if let ExprKind::Block(ref block, _) = arm.body.kind;
670 if is_panic_block(block);
672 // `Err(_)` or `Err(_e)` arm with `panic!` found
673 span_lint_and_note(cx,
676 &format!("`Err({})` matches all errors", &ident_bind_name),
678 "match each error separately or use the error output",
688 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
689 let ty = cx.tables.expr_ty(ex);
691 // If there isn't a nice closed set of possible values that can be conveniently enumerated,
692 // don't complain about not enumerating the mall.
696 // First pass - check for violation, but don't do much book-keeping because this is hopefully
697 // the uncommon case, and the book-keeping is slightly expensive.
698 let mut wildcard_span = None;
699 let mut wildcard_ident = None;
701 if let PatKind::Wild = arm.pat.kind {
702 wildcard_span = Some(arm.pat.span);
703 } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
704 wildcard_span = Some(arm.pat.span);
705 wildcard_ident = Some(ident);
709 if let Some(wildcard_span) = wildcard_span {
710 // Accumulate the variants which should be put in place of the wildcard because they're not
713 let mut missing_variants = vec![];
714 if let ty::Adt(def, _) = ty.kind {
715 for variant in &def.variants {
716 missing_variants.push(variant);
721 if arm.guard.is_some() {
722 // Guards mean that this case probably isn't exhaustively covered. Technically
723 // this is incorrect, as we should really check whether each variant is exhaustively
724 // covered by the set of guards that cover it, but that's really hard to do.
727 if let PatKind::Path(ref path) = arm.pat.kind {
728 if let QPath::Resolved(_, p) = path {
729 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
731 } else if let PatKind::TupleStruct(ref path, ..) = arm.pat.kind {
732 if let QPath::Resolved(_, p) = path {
733 missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
738 let mut suggestion: Vec<String> = missing_variants
741 let suffix = match v.ctor_kind {
742 CtorKind::Fn => "(..)",
743 CtorKind::Const | CtorKind::Fictive => "",
745 let ident_str = if let Some(ident) = wildcard_ident {
746 format!("{} @ ", ident.name)
750 // This path assumes that the enum type is imported into scope.
751 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
755 if suggestion.is_empty() {
759 let mut message = "wildcard match will miss any future added variants";
761 if let ty::Adt(def, _) = ty.kind {
762 if def.is_variant_list_non_exhaustive() {
763 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
764 suggestion.push(String::from("_"));
770 WILDCARD_ENUM_MATCH_ARM,
774 suggestion.join(" | "),
775 Applicability::MachineApplicable,
780 // If the block contains only a `panic!` macro (as expression or statement)
781 fn is_panic_block(block: &Block<'_>) -> bool {
782 match (&block.expr, block.stmts.len(), block.stmts.first()) {
783 (&Some(ref exp), 0, _) => {
784 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
786 (&None, 1, Some(stmt)) => {
787 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
793 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
794 if has_only_ref_pats(arms) {
795 let mut suggs = Vec::with_capacity(arms.len() + 1);
796 let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
797 let span = ex.span.source_callsite();
798 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
800 "you don't need to add `&` to both the expression and the patterns",
804 let span = ex.span.source_callsite();
805 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
807 "you don't need to add `&` to all patterns",
808 "instead of prefixing all patterns with `&`, you can dereference the expression",
812 suggs.extend(arms.iter().filter_map(|a| {
813 if let PatKind::Ref(ref refp, _) = a.pat.kind {
814 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
820 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
821 if !expr.span.from_expansion() {
822 multispan_sugg(db, msg.to_owned(), suggs);
828 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
829 if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
830 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
831 is_ref_some_arm(&arms[1])
832 } else if is_none_arm(&arms[1]) {
833 is_ref_some_arm(&arms[0])
837 if let Some(rb) = arm_ref {
838 let suggestion = if rb == BindingAnnotation::Ref {
844 let output_ty = cx.tables.expr_ty(expr);
845 let input_ty = cx.tables.expr_ty(ex);
847 let cast = if_chain! {
848 if let ty::Adt(_, substs) = input_ty.kind;
849 let input_ty = substs.type_at(0);
850 if let ty::Adt(_, substs) = output_ty.kind;
851 let output_ty = substs.type_at(0);
852 if let ty::Ref(_, output_ty, _) = output_ty.kind;
853 if input_ty != output_ty;
861 let mut applicability = Applicability::MachineApplicable;
866 &format!("use `{}()` instead", suggestion),
870 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
880 fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
882 if let PatKind::Or(ref fields) = arm.pat.kind {
883 // look for multiple fields in this arm that contains at least one Wild pattern
884 if fields.len() > 1 && fields.iter().any(is_wild) {
887 WILDCARD_IN_OR_PATTERNS,
889 "wildcard pattern covers any other pattern as it will match anyway.",
890 "Consider handling `_` separately.",
897 fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
898 if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
901 let matched_vars = ex.span;
902 let bind_names = arms[0].pat.span;
903 let match_body = remove_blocks(&arms[0].body);
904 let mut snippet_body = if match_body.span.from_expansion() {
905 Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
907 snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
910 // Do we need to add ';' to suggestion ?
911 match match_body.kind {
912 ExprKind::Block(block, _) => {
913 // macro + expr_ty(body) == ()
914 if block.span.from_expansion() && cx.tables.expr_ty(&match_body).is_unit() {
915 snippet_body.push(';');
919 // expr_ty(body) == ()
920 if cx.tables.expr_ty(&match_body).is_unit() {
921 snippet_body.push(';');
926 let mut applicability = Applicability::MaybeIncorrect;
927 match arms[0].pat.kind {
928 PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
929 // If this match is in a local (`let`) stmt
930 let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
932 parent_let_node.span,
934 "let {} = {};\n{}let {} = {};",
935 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
936 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
937 " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
938 snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
943 // If we are in closure, we need curly braces around suggestion
944 let mut indent = " ".repeat(indent_of(cx, ex.span).unwrap_or(0));
945 let (mut cbrace_start, mut cbrace_end) = ("".to_string(), "".to_string());
946 if let Some(parent_expr) = get_parent_expr(cx, expr) {
947 if let ExprKind::Closure(..) = parent_expr.kind {
948 cbrace_end = format!("\n{}}}", indent);
949 // Fix body indent due to the closure
950 indent = " ".repeat(indent_of(cx, bind_names).unwrap_or(0));
951 cbrace_start = format!("{{\n{}", indent);
957 "{}let {} = {};\n{}{}{}",
959 snippet_with_applicability(cx, bind_names, "..", &mut applicability),
960 snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
969 MATCH_SINGLE_BINDING,
971 "this match could be written as a `let` statement",
972 "consider using `let` statement",
980 MATCH_SINGLE_BINDING,
982 "this match could be replaced by its body itself",
983 "consider using the match body instead",
985 Applicability::MachineApplicable,
992 /// Returns true if the `ex` match expression is in a local (`let`) statement
993 fn opt_parent_let<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
995 let map = &cx.tcx.hir();
996 if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
997 if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
999 return Some(parent_let_expr);
1005 /// Gets all arms that are unbounded `PatRange`s.
1006 fn all_ranges<'a, 'tcx>(
1007 cx: &LateContext<'a, 'tcx>,
1008 arms: &'tcx [Arm<'_>],
1010 ) -> Vec<SpannedRange<Constant>> {
1014 ref pat, guard: None, ..
1017 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
1018 let lhs = match lhs {
1019 Some(lhs) => constant(cx, cx.tables, lhs)?.0,
1020 None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
1022 let rhs = match rhs {
1023 Some(rhs) => constant(cx, cx.tables, rhs)?.0,
1024 None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1026 let rhs = match range_end {
1027 RangeEnd::Included => Bound::Included(rhs),
1028 RangeEnd::Excluded => Bound::Excluded(rhs),
1030 return Some(SpannedRange {
1036 if let PatKind::Lit(ref value) = pat.kind {
1037 let value = constant(cx, cx.tables, value)?.0;
1038 return Some(SpannedRange {
1040 node: (value.clone(), Bound::Included(value)),
1049 #[derive(Debug, Eq, PartialEq)]
1050 pub struct SpannedRange<T> {
1052 pub node: (T, Bound<T>),
1055 type TypedRanges = Vec<SpannedRange<u128>>;
1057 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1058 /// and other types than
1059 /// `Uint` and `Int` probably don't make sense.
1060 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1063 .filter_map(|range| match range.node {
1064 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1066 node: (start, Bound::Included(end)),
1068 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1070 node: (start, Bound::Excluded(end)),
1072 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1074 node: (start, Bound::Unbounded),
1081 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1083 ExprKind::Tup(ref v) if v.is_empty() => true,
1084 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1089 // Checks if arm has the form `None => None`
1090 fn is_none_arm(arm: &Arm<'_>) -> bool {
1091 match arm.pat.kind {
1092 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
1097 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1098 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1100 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1101 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1102 if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1103 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1104 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1105 if let ExprKind::Path(ref some_path) = e.kind;
1106 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1107 if let ExprKind::Path(ref qpath) = args[0].kind;
1108 if let &QPath::Resolved(_, ref path2) = qpath;
1109 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1117 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1122 PatKind::Ref(..) => Some(true), // &-patterns
1123 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
1124 _ => None, // any other pattern is not fine
1127 .collect::<Option<Vec<bool>>>();
1128 // look for Some(v) where there's at least one true element
1129 mapped.map_or(false, |v| v.iter().any(|el| *el))
1132 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1136 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1138 Start(T, &'a SpannedRange<T>),
1139 End(Bound<T>, &'a SpannedRange<T>),
1142 impl<'a, T: Copy> Kind<'a, T> {
1143 fn range(&self) -> &'a SpannedRange<T> {
1145 Kind::Start(_, r) | Kind::End(_, r) => r,
1149 fn value(self) -> Bound<T> {
1151 Kind::Start(t, _) => Bound::Included(t),
1152 Kind::End(t, _) => t,
1157 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1158 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1159 Some(self.cmp(other))
1163 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1164 fn cmp(&self, other: &Self) -> Ordering {
1165 match (self.value(), other.value()) {
1166 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1167 // Range patterns cannot be unbounded (yet)
1168 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1169 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1170 Ordering::Equal => Ordering::Greater,
1173 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1174 Ordering::Equal => Ordering::Less,
1181 let mut values = Vec::with_capacity(2 * ranges.len());
1184 values.push(Kind::Start(r.node.0, r));
1185 values.push(Kind::End(r.node.1, r));
1190 for (a, b) in values.iter().zip(values.iter().skip(1)) {
1192 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1193 if ra.node != rb.node {
1194 return Some((ra, rb));
1197 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1198 _ => return Some((a.range(), b.range())),
1206 fn test_overlapping() {
1207 use rustc_span::source_map::DUMMY_SP;
1209 let sp = |s, e| SpannedRange {
1214 assert_eq!(None, overlapping::<u8>(&[]));
1215 assert_eq!(None, overlapping(&[sp(1, Bound::Included(4))]));
1218 overlapping(&[sp(1, Bound::Included(4)), sp(5, Bound::Included(6))])
1223 sp(1, Bound::Included(4)),
1224 sp(5, Bound::Included(6)),
1225 sp(10, Bound::Included(11))
1229 Some((&sp(1, Bound::Included(4)), &sp(3, Bound::Included(6)))),
1230 overlapping(&[sp(1, Bound::Included(4)), sp(3, Bound::Included(6))])
1233 Some((&sp(5, Bound::Included(6)), &sp(6, Bound::Included(11)))),
1235 sp(1, Bound::Included(4)),
1236 sp(5, Bound::Included(6)),
1237 sp(6, Bound::Included(11))