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;
10 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
11 use rustc::ty::{self, Ty};
12 use rustc::{declare_tool_lint, lint_array};
13 use rustc_errors::Applicability;
14 use std::cmp::Ordering;
15 use std::collections::Bound;
16 use syntax::ast::LitKind;
17 use syntax::source_map::Span;
19 /// **What it does:** Checks for matches with a single arm where an `if let`
20 /// will usually suffice.
22 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
24 /// **Known problems:** None.
29 /// Some(ref foo) => bar(foo),
33 declare_clippy_lint! {
36 "a match statement with a single nontrivial arm (i.e. where the other arm is `_ => {}`) instead of `if let`"
39 /// **What it does:** Checks for matches with a two arms where an `if let else` will
42 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
44 /// **Known problems:** Personal style preferences may differ.
52 /// Some(ref foo) => bar(foo),
53 /// _ => bar(other_ref),
57 /// Using `if let` with `else`:
60 /// if let Some(ref foo) = x {
66 declare_clippy_lint! {
67 pub SINGLE_MATCH_ELSE,
69 "a match statement with a two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
72 /// **What it does:** Checks for matches where all arms match a reference,
73 /// suggesting to remove the reference and deref the matched expression
74 /// instead. It also checks for `if let &foo = bar` blocks.
76 /// **Why is this bad?** It just makes the code less readable. That reference
77 /// destructuring adds nothing to the code.
79 /// **Known problems:** None.
84 /// &A(ref y) => foo(y),
89 declare_clippy_lint! {
92 "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
95 /// **What it does:** Checks for matches where match expression is a `bool`. It
96 /// suggests to replace the expression with an `if...else` block.
98 /// **Why is this bad?** It makes the code less readable.
100 /// **Known problems:** None.
104 /// let condition: bool = true;
105 /// match condition {
110 /// Use if/else instead:
112 /// let condition: bool = true;
119 declare_clippy_lint! {
122 "a match on a boolean expression instead of an `if..else` block"
125 /// **What it does:** Checks for overlapping match arms.
127 /// **Why is this bad?** It is likely to be an error and if not, makes the code
130 /// **Known problems:** None.
136 /// 1...10 => println!("1 ... 10"),
137 /// 5...15 => println!("5 ... 15"),
141 declare_clippy_lint! {
142 pub MATCH_OVERLAPPING_ARM,
144 "a match with overlapping arms"
147 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
148 /// and take drastic actions like `panic!`.
150 /// **Why is this bad?** It is generally a bad practice, just like
151 /// catching all exceptions in java with `catch(Exception)`
153 /// **Known problems:** None.
157 /// let x: Result(i32, &str) = Ok(3);
159 /// Ok(_) => println!("ok"),
160 /// Err(_) => panic!("err"),
163 declare_clippy_lint! {
164 pub MATCH_WILD_ERR_ARM,
166 "a match with `Err(_)` arm and take drastic actions"
169 /// **What it does:** Checks for match which is used to add a reference to an
172 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
174 /// **Known problems:** None.
178 /// let x: Option<()> = None;
179 /// let r: Option<&()> = match x {
181 /// Some(ref v) => Some(v),
184 declare_clippy_lint! {
187 "a match on an Option value instead of using `as_ref()` or `as_mut`"
190 #[allow(missing_copy_implementations)]
191 pub struct MatchPass;
193 impl LintPass for MatchPass {
194 fn get_lints(&self) -> LintArray {
200 MATCH_OVERLAPPING_ARM,
206 fn name(&self) -> &'static str {
211 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
212 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
213 if in_external_macro(cx.sess(), expr.span) {
216 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
217 check_single_match(cx, ex, arms, expr);
218 check_match_bool(cx, ex, arms, expr);
219 check_overlapping_arms(cx, ex, arms);
220 check_wild_err_arm(cx, ex, arms);
221 check_match_as_ref(cx, ex, arms, expr);
223 if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
224 check_match_ref_pats(cx, ex, arms, expr);
230 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
231 if arms.len() == 2 &&
232 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
233 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
234 let els = remove_blocks(&arms[1].body);
235 let els = if is_unit_expr(els) {
237 } else if let ExprKind::Block(_, _) = els.node {
238 // matches with blocks that contain statements are prettier as `if let + else`
241 // allow match arms with just expressions
244 let ty = cx.tables.expr_ty(ex);
245 if ty.sty != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.id) {
246 check_single_match_single_pattern(cx, ex, arms, expr, els);
247 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
252 fn check_single_match_single_pattern(
253 cx: &LateContext<'_, '_>,
259 if is_wild(&arms[1].pats[0]) {
260 report_single_match_single_pattern(cx, ex, arms, expr, els);
264 fn report_single_match_single_pattern(
265 cx: &LateContext<'_, '_>,
271 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
272 let els_str = els.map_or(String::new(), |els| {
273 format!(" else {}", expr_block(cx, els, None, ".."))
279 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
283 "if let {} = {} {}{}",
284 snippet(cx, arms[0].pats[0].span, ".."),
285 snippet(cx, ex.span, ".."),
286 expr_block(cx, &arms[0].body, None, ".."),
289 Applicability::HasPlaceholders,
293 fn check_single_match_opt_like(
294 cx: &LateContext<'_, '_>,
301 // list of candidate Enums we know will never get any more members
303 (&paths::COW, "Borrowed"),
304 (&paths::COW, "Cow::Borrowed"),
305 (&paths::COW, "Cow::Owned"),
306 (&paths::COW, "Owned"),
307 (&paths::OPTION, "None"),
308 (&paths::RESULT, "Err"),
309 (&paths::RESULT, "Ok"),
312 let path = match arms[1].pats[0].node {
313 PatKind::TupleStruct(ref path, ref inner, _) => {
314 // contains any non wildcard patterns? e.g. Err(err)
315 if !inner.iter().all(is_wild) {
318 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
320 PatKind::Binding(BindingAnnotation::Unannotated, _, ident, None) => ident.to_string(),
321 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
325 for &(ty_path, pat_path) in candidates {
326 if path == *pat_path && match_type(cx, ty, ty_path) {
327 report_single_match_single_pattern(cx, ex, arms, expr, els);
332 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
333 // type of expression == bool
334 if cx.tables.expr_ty(ex).sty == ty::Bool {
339 "you seem to be trying to match on a boolean expression",
341 if arms.len() == 2 && arms[0].pats.len() == 1 {
343 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
344 if let ExprKind::Lit(ref lit) = arm_bool.node {
346 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
347 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
357 if let Some((true_expr, false_expr)) = exprs {
358 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
359 (false, false) => Some(format!(
361 snippet(cx, ex.span, "b"),
362 expr_block(cx, true_expr, None, ".."),
363 expr_block(cx, false_expr, None, "..")
365 (false, true) => Some(format!(
367 snippet(cx, ex.span, "b"),
368 expr_block(cx, true_expr, None, "..")
371 let test = Sugg::hir(cx, ex, "..");
372 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
374 (true, true) => None,
377 if let Some(sugg) = sugg {
378 db.span_suggestion_with_applicability(
380 "consider using an if/else expression",
382 Applicability::HasPlaceholders,
392 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
393 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
394 let ranges = all_ranges(cx, arms);
395 let type_ranges = type_ranges(&ranges);
396 if !type_ranges.is_empty() {
397 if let Some((start, end)) = overlapping(&type_ranges) {
400 MATCH_OVERLAPPING_ARM,
402 "some ranges overlap",
404 "overlaps with this",
411 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
413 PatKind::Wild => true,
418 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
419 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
420 if match_type(cx, ex_ty, &paths::RESULT) {
422 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
423 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
425 if path_str == "Err";
426 if inner.iter().any(is_wild);
427 if let ExprKind::Block(ref block, _) = arm.body.node;
428 if is_panic_block(block);
430 // `Err(_)` arm with `panic!` found
431 span_note_and_lint(cx,
434 "Err(_) will match all errors, maybe not a good idea",
436 "to remove this warning, match each error separately \
437 or use unreachable macro");
445 // If the block contains only a `panic!` macro (as expression or statement)
446 fn is_panic_block(block: &Block) -> bool {
447 match (&block.expr, block.stmts.len(), block.stmts.first()) {
448 (&Some(ref exp), 0, _) => {
449 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
451 (&None, 1, Some(stmt)) => {
452 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
458 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
459 if has_only_ref_pats(arms) {
460 let mut suggs = Vec::new();
461 let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
462 suggs.push((ex.span, Sugg::hir(cx, inner, "..").to_string()));
464 "you don't need to add `&` to both the expression and the patterns",
468 suggs.push((ex.span, Sugg::hir(cx, ex, "..").deref().to_string()));
470 "you don't need to add `&` to all patterns",
471 "instead of prefixing all patterns with `&`, you can dereference the expression",
475 suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
476 if let PatKind::Ref(ref refp, _) = p.node {
477 Some((p.span, snippet(cx, refp.span, "..").to_string()))
483 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
484 if !in_macro(expr.span) {
485 multispan_sugg(db, msg.to_owned(), suggs);
491 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
493 && arms[0].pats.len() == 1
494 && arms[0].guard.is_none()
495 && arms[1].pats.len() == 1
496 && arms[1].guard.is_none()
498 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
499 is_ref_some_arm(&arms[1])
500 } else if is_none_arm(&arms[1]) {
501 is_ref_some_arm(&arms[0])
505 if let Some(rb) = arm_ref {
506 let suggestion = if rb == BindingAnnotation::Ref {
511 let mut applicability = Applicability::MachineApplicable;
516 &format!("use {}() instead", suggestion),
520 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
529 /// Get all arms that are unbounded `PatRange`s.
530 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
534 ref pats, guard: None, ..
542 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
543 let lhs = constant(cx, cx.tables, lhs)?.0;
544 let rhs = constant(cx, cx.tables, rhs)?.0;
545 let rhs = match *range_end {
546 RangeEnd::Included => Bound::Included(rhs),
547 RangeEnd::Excluded => Bound::Excluded(rhs),
549 return Some(SpannedRange {
555 if let PatKind::Lit(ref value) = pat.node {
556 let value = constant(cx, cx.tables, value)?.0;
557 return Some(SpannedRange {
559 node: (value.clone(), Bound::Included(value)),
569 #[derive(Debug, Eq, PartialEq)]
570 pub struct SpannedRange<T> {
572 pub node: (T, Bound<T>),
575 type TypedRanges = Vec<SpannedRange<u128>>;
577 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
578 /// and other types than
579 /// `Uint` and `Int` probably don't make sense.
580 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
583 .filter_map(|range| match range.node {
584 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
586 node: (start, Bound::Included(end)),
588 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
590 node: (start, Bound::Excluded(end)),
592 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
594 node: (start, Bound::Unbounded),
601 fn is_unit_expr(expr: &Expr) -> bool {
603 ExprKind::Tup(ref v) if v.is_empty() => true,
604 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
609 // Checks if arm has the form `None => None`
610 fn is_none_arm(arm: &Arm) -> bool {
611 match arm.pats[0].node {
612 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
617 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
618 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
620 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
621 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
622 if let PatKind::Binding(rb, _, ident, _) = pats[0].node;
623 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
624 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
625 if let ExprKind::Path(ref some_path) = e.node;
626 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
627 if let ExprKind::Path(ref qpath) = args[0].node;
628 if let &QPath::Resolved(_, ref path2) = qpath;
629 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
637 fn has_only_ref_pats(arms: &[Arm]) -> bool {
640 .flat_map(|a| &a.pats)
643 PatKind::Ref(..) => Some(true), // &-patterns
644 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
645 _ => None, // any other pattern is not fine
648 .collect::<Option<Vec<bool>>>();
649 // look for Some(v) where there's at least one true element
650 mapped.map_or(false, |v| v.iter().any(|el| *el))
653 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
657 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
658 enum Kind<'a, T: 'a> {
659 Start(T, &'a SpannedRange<T>),
660 End(Bound<T>, &'a SpannedRange<T>),
663 impl<'a, T: Copy> Kind<'a, T> {
664 fn range(&self) -> &'a SpannedRange<T> {
666 Kind::Start(_, r) | Kind::End(_, r) => r,
670 fn value(self) -> Bound<T> {
672 Kind::Start(t, _) => Bound::Included(t),
673 Kind::End(t, _) => t,
678 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
679 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
680 Some(self.cmp(other))
684 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
685 fn cmp(&self, other: &Self) -> Ordering {
686 match (self.value(), other.value()) {
687 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
688 // Range patterns cannot be unbounded (yet)
689 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
690 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
691 Ordering::Equal => Ordering::Greater,
694 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
695 Ordering::Equal => Ordering::Less,
702 let mut values = Vec::with_capacity(2 * ranges.len());
705 values.push(Kind::Start(r.node.0, r));
706 values.push(Kind::End(r.node.1, r));
711 for (a, b) in values.iter().zip(values.iter().skip(1)) {
713 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
714 if ra.node != rb.node {
715 return Some((ra, rb));
718 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
719 _ => return Some((a.range(), b.range())),