1 use crate::consts::{constant, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
5 expr_block, in_macro, is_allowed, is_expn_of, match_qpath, match_type, multispan_sugg, remove_blocks, snippet,
6 snippet_with_applicability, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty,
8 use if_chain::if_chain;
9 use rustc::hir::def::CtorKind;
11 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
12 use rustc::ty::{self, Ty, TyKind};
13 use rustc::{declare_tool_lint, lint_array};
14 use rustc_errors::Applicability;
15 use std::cmp::Ordering;
16 use std::collections::Bound;
18 use syntax::ast::LitKind;
19 use syntax::source_map::Span;
21 /// **What it does:** Checks for matches with a single arm where an `if let`
22 /// will usually suffice.
24 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
26 /// **Known problems:** None.
31 /// Some(ref foo) => bar(foo),
35 declare_clippy_lint! {
38 "a match statement with a single nontrivial arm (i.e. where the other arm is `_ => {}`) instead of `if let`"
41 /// **What it does:** Checks for matches with a two arms where an `if let else` will
44 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
46 /// **Known problems:** Personal style preferences may differ.
54 /// Some(ref foo) => bar(foo),
55 /// _ => bar(other_ref),
59 /// Using `if let` with `else`:
62 /// if let Some(ref foo) = x {
68 declare_clippy_lint! {
69 pub SINGLE_MATCH_ELSE,
71 "a match statement with a two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
74 /// **What it does:** Checks for matches where all arms match a reference,
75 /// suggesting to remove the reference and deref the matched expression
76 /// instead. It also checks for `if let &foo = bar` blocks.
78 /// **Why is this bad?** It just makes the code less readable. That reference
79 /// destructuring adds nothing to the code.
81 /// **Known problems:** None.
86 /// &A(ref y) => foo(y),
91 declare_clippy_lint! {
94 "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
97 /// **What it does:** Checks for matches where match expression is a `bool`. It
98 /// suggests to replace the expression with an `if...else` block.
100 /// **Why is this bad?** It makes the code less readable.
102 /// **Known problems:** None.
106 /// let condition: bool = true;
107 /// match condition {
112 /// Use if/else instead:
114 /// let condition: bool = true;
121 declare_clippy_lint! {
124 "a match on a boolean expression instead of an `if..else` block"
127 /// **What it does:** Checks for overlapping match arms.
129 /// **Why is this bad?** It is likely to be an error and if not, makes the code
132 /// **Known problems:** None.
138 /// 1...10 => println!("1 ... 10"),
139 /// 5...15 => println!("5 ... 15"),
143 declare_clippy_lint! {
144 pub MATCH_OVERLAPPING_ARM,
146 "a match with overlapping arms"
149 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
150 /// and take drastic actions like `panic!`.
152 /// **Why is this bad?** It is generally a bad practice, just like
153 /// catching all exceptions in java with `catch(Exception)`
155 /// **Known problems:** None.
159 /// let x: Result(i32, &str) = Ok(3);
161 /// Ok(_) => println!("ok"),
162 /// Err(_) => panic!("err"),
165 declare_clippy_lint! {
166 pub MATCH_WILD_ERR_ARM,
168 "a match with `Err(_)` arm and take drastic actions"
171 /// **What it does:** Checks for match which is used to add a reference to an
174 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
176 /// **Known problems:** None.
180 /// let x: Option<()> = None;
181 /// let r: Option<&()> = match x {
183 /// Some(ref v) => Some(v),
186 declare_clippy_lint! {
189 "a match on an Option value instead of using `as_ref()` or `as_mut`"
192 /// **What it does:** Checks for wildcard enum matches using `_`.
194 /// **Why is this bad?** New enum variants added by library updates can be missed.
196 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
197 /// variants, and also may not use correct path to enum if it's not present in the current scope.
206 declare_clippy_lint! {
207 pub WILDCARD_ENUM_MATCH_ARM,
209 "a wildcard enum match arm using `_`"
212 #[allow(missing_copy_implementations)]
213 pub struct MatchPass;
215 impl LintPass for MatchPass {
216 fn get_lints(&self) -> LintArray {
222 MATCH_OVERLAPPING_ARM,
225 WILDCARD_ENUM_MATCH_ARM
229 fn name(&self) -> &'static str {
234 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
235 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
236 if in_external_macro(cx.sess(), expr.span) {
239 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
240 check_single_match(cx, ex, arms, expr);
241 check_match_bool(cx, ex, arms, expr);
242 check_overlapping_arms(cx, ex, arms);
243 check_wild_err_arm(cx, ex, arms);
244 check_wild_enum_match(cx, ex, arms);
245 check_match_as_ref(cx, ex, arms, expr);
247 if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
248 check_match_ref_pats(cx, ex, arms, expr);
254 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
255 if arms.len() == 2 &&
256 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
257 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
258 let els = remove_blocks(&arms[1].body);
259 let els = if is_unit_expr(els) {
261 } else if let ExprKind::Block(_, _) = els.node {
262 // matches with blocks that contain statements are prettier as `if let + else`
265 // allow match arms with just expressions
268 let ty = cx.tables.expr_ty(ex);
269 if ty.sty != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
270 check_single_match_single_pattern(cx, ex, arms, expr, els);
271 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
276 fn check_single_match_single_pattern(
277 cx: &LateContext<'_, '_>,
283 if is_wild(&arms[1].pats[0]) {
284 report_single_match_single_pattern(cx, ex, arms, expr, els);
288 fn report_single_match_single_pattern(
289 cx: &LateContext<'_, '_>,
295 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
296 let els_str = els.map_or(String::new(), |els| {
297 format!(" else {}", expr_block(cx, els, None, ".."))
303 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
307 "if let {} = {} {}{}",
308 snippet(cx, arms[0].pats[0].span, ".."),
309 snippet(cx, ex.span, ".."),
310 expr_block(cx, &arms[0].body, None, ".."),
313 Applicability::HasPlaceholders,
317 fn check_single_match_opt_like(
318 cx: &LateContext<'_, '_>,
325 // list of candidate Enums we know will never get any more members
327 (&paths::COW, "Borrowed"),
328 (&paths::COW, "Cow::Borrowed"),
329 (&paths::COW, "Cow::Owned"),
330 (&paths::COW, "Owned"),
331 (&paths::OPTION, "None"),
332 (&paths::RESULT, "Err"),
333 (&paths::RESULT, "Ok"),
336 let path = match arms[1].pats[0].node {
337 PatKind::TupleStruct(ref path, ref inner, _) => {
338 // contains any non wildcard patterns? e.g. Err(err)
339 if !inner.iter().all(is_wild) {
342 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
344 PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
345 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
349 for &(ty_path, pat_path) in candidates {
350 if path == *pat_path && match_type(cx, ty, ty_path) {
351 report_single_match_single_pattern(cx, ex, arms, expr, els);
356 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
357 // type of expression == bool
358 if cx.tables.expr_ty(ex).sty == ty::Bool {
363 "you seem to be trying to match on a boolean expression",
365 if arms.len() == 2 && arms[0].pats.len() == 1 {
367 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
368 if let ExprKind::Lit(ref lit) = arm_bool.node {
370 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
371 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
381 if let Some((true_expr, false_expr)) = exprs {
382 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
383 (false, false) => Some(format!(
385 snippet(cx, ex.span, "b"),
386 expr_block(cx, true_expr, None, ".."),
387 expr_block(cx, false_expr, None, "..")
389 (false, true) => Some(format!(
391 snippet(cx, ex.span, "b"),
392 expr_block(cx, true_expr, None, "..")
395 let test = Sugg::hir(cx, ex, "..");
396 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
398 (true, true) => None,
401 if let Some(sugg) = sugg {
404 "consider using an if/else expression",
406 Applicability::HasPlaceholders,
416 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
417 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
418 let ranges = all_ranges(cx, arms);
419 let type_ranges = type_ranges(&ranges);
420 if !type_ranges.is_empty() {
421 if let Some((start, end)) = overlapping(&type_ranges) {
424 MATCH_OVERLAPPING_ARM,
426 "some ranges overlap",
428 "overlaps with this",
435 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
437 PatKind::Wild => true,
442 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
443 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
444 if match_type(cx, ex_ty, &paths::RESULT) {
446 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
447 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
449 if path_str == "Err";
450 if inner.iter().any(is_wild);
451 if let ExprKind::Block(ref block, _) = arm.body.node;
452 if is_panic_block(block);
454 // `Err(_)` arm with `panic!` found
455 span_note_and_lint(cx,
458 "Err(_) will match all errors, maybe not a good idea",
460 "to remove this warning, match each error separately \
461 or use unreachable macro");
469 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
470 let ty = cx.tables.expr_ty(ex);
472 // If there isn't a nice closed set of possible values that can be conveniently enumerated,
473 // don't complain about not enumerating the mall.
477 // First pass - check for violation, but don't do much book-keeping because this is hopefully
478 // the uncommon case, and the book-keeping is slightly expensive.
479 let mut wildcard_span = None;
480 let mut wildcard_ident = None;
482 for pat in &arm.pats {
483 if let PatKind::Wild = pat.node {
484 wildcard_span = Some(pat.span);
485 } else if let PatKind::Binding(_, _, _, ident, None) = pat.node {
486 wildcard_span = Some(pat.span);
487 wildcard_ident = Some(ident);
492 if let Some(wildcard_span) = wildcard_span {
493 // Accumulate the variants which should be put in place of the wildcard because they're not
496 let mut missing_variants = vec![];
497 if let TyKind::Adt(def, _) = ty.sty {
498 for variant in &def.variants {
499 missing_variants.push(variant);
504 if arm.guard.is_some() {
505 // Guards mean that this case probably isn't exhaustively covered. Technically
506 // this is incorrect, as we should really check whether each variant is exhaustively
507 // covered by the set of guards that cover it, but that's really hard to do.
510 for pat in &arm.pats {
511 if let PatKind::Path(ref path) = pat.deref().node {
512 if let QPath::Resolved(_, p) = path {
513 missing_variants.retain(|e| e.did != p.def.def_id());
515 } else if let PatKind::TupleStruct(ref path, ..) = pat.deref().node {
516 if let QPath::Resolved(_, p) = path {
517 missing_variants.retain(|e| e.did != p.def.def_id());
523 let suggestion: Vec<String> = missing_variants
526 let suffix = match v.ctor_kind {
527 CtorKind::Fn => "(..)",
528 CtorKind::Const | CtorKind::Fictive => "",
530 let ident_str = if let Some(ident) = wildcard_ident {
531 format!("{} @ ", ident.name)
535 // This path assumes that the enum type is imported into scope.
536 format!("{}{}{}", ident_str, cx.tcx.item_path_str(v.did), suffix)
540 if suggestion.is_empty() {
546 WILDCARD_ENUM_MATCH_ARM,
548 "wildcard match will miss any future added variants.",
550 suggestion.join(" | "),
551 Applicability::MachineApplicable,
556 // If the block contains only a `panic!` macro (as expression or statement)
557 fn is_panic_block(block: &Block) -> bool {
558 match (&block.expr, block.stmts.len(), block.stmts.first()) {
559 (&Some(ref exp), 0, _) => {
560 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
562 (&None, 1, Some(stmt)) => {
563 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
569 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
570 if has_only_ref_pats(arms) {
571 let mut suggs = Vec::new();
572 let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
573 let span = ex.span.source_callsite();
574 suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
576 "you don't need to add `&` to both the expression and the patterns",
580 let span = ex.span.source_callsite();
581 suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
583 "you don't need to add `&` to all patterns",
584 "instead of prefixing all patterns with `&`, you can dereference the expression",
588 suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
589 if let PatKind::Ref(ref refp, _) = p.node {
590 Some((p.span, snippet(cx, refp.span, "..").to_string()))
596 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
597 if !in_macro(expr.span) {
598 multispan_sugg(db, msg.to_owned(), suggs);
604 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
606 && arms[0].pats.len() == 1
607 && arms[0].guard.is_none()
608 && arms[1].pats.len() == 1
609 && arms[1].guard.is_none()
611 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
612 is_ref_some_arm(&arms[1])
613 } else if is_none_arm(&arms[1]) {
614 is_ref_some_arm(&arms[0])
618 if let Some(rb) = arm_ref {
619 let suggestion = if rb == BindingAnnotation::Ref {
624 let mut applicability = Applicability::MachineApplicable;
629 &format!("use {}() instead", suggestion),
633 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
642 /// Get all arms that are unbounded `PatRange`s.
643 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
647 ref pats, guard: None, ..
655 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
656 let lhs = constant(cx, cx.tables, lhs)?.0;
657 let rhs = constant(cx, cx.tables, rhs)?.0;
658 let rhs = match *range_end {
659 RangeEnd::Included => Bound::Included(rhs),
660 RangeEnd::Excluded => Bound::Excluded(rhs),
662 return Some(SpannedRange {
668 if let PatKind::Lit(ref value) = pat.node {
669 let value = constant(cx, cx.tables, value)?.0;
670 return Some(SpannedRange {
672 node: (value.clone(), Bound::Included(value)),
682 #[derive(Debug, Eq, PartialEq)]
683 pub struct SpannedRange<T> {
685 pub node: (T, Bound<T>),
688 type TypedRanges = Vec<SpannedRange<u128>>;
690 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
691 /// and other types than
692 /// `Uint` and `Int` probably don't make sense.
693 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
696 .filter_map(|range| match range.node {
697 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
699 node: (start, Bound::Included(end)),
701 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
703 node: (start, Bound::Excluded(end)),
705 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
707 node: (start, Bound::Unbounded),
714 fn is_unit_expr(expr: &Expr) -> bool {
716 ExprKind::Tup(ref v) if v.is_empty() => true,
717 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
722 // Checks if arm has the form `None => None`
723 fn is_none_arm(arm: &Arm) -> bool {
724 match arm.pats[0].node {
725 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
730 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
731 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
733 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
734 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
735 if let PatKind::Binding(rb, .., ident, _) = pats[0].node;
736 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
737 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
738 if let ExprKind::Path(ref some_path) = e.node;
739 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
740 if let ExprKind::Path(ref qpath) = args[0].node;
741 if let &QPath::Resolved(_, ref path2) = qpath;
742 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
750 fn has_only_ref_pats(arms: &[Arm]) -> bool {
753 .flat_map(|a| &a.pats)
756 PatKind::Ref(..) => Some(true), // &-patterns
757 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
758 _ => None, // any other pattern is not fine
761 .collect::<Option<Vec<bool>>>();
762 // look for Some(v) where there's at least one true element
763 mapped.map_or(false, |v| v.iter().any(|el| *el))
766 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
770 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
771 enum Kind<'a, T: 'a> {
772 Start(T, &'a SpannedRange<T>),
773 End(Bound<T>, &'a SpannedRange<T>),
776 impl<'a, T: Copy> Kind<'a, T> {
777 fn range(&self) -> &'a SpannedRange<T> {
779 Kind::Start(_, r) | Kind::End(_, r) => r,
783 fn value(self) -> Bound<T> {
785 Kind::Start(t, _) => Bound::Included(t),
786 Kind::End(t, _) => t,
791 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
792 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
793 Some(self.cmp(other))
797 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
798 fn cmp(&self, other: &Self) -> Ordering {
799 match (self.value(), other.value()) {
800 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
801 // Range patterns cannot be unbounded (yet)
802 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
803 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
804 Ordering::Equal => Ordering::Greater,
807 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
808 Ordering::Equal => Ordering::Less,
815 let mut values = Vec::with_capacity(2 * ranges.len());
818 values.push(Kind::Start(r.node.0, r));
819 values.push(Kind::End(r.node.1, r));
824 for (a, b) in values.iter().zip(values.iter().skip(1)) {
826 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
827 if ra.node != rb.node {
828 return Some((ra, rb));
831 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
832 _ => return Some((a.range(), b.range())),