1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::consts::{constant, Constant};
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
13 use crate::rustc::ty::{self, Ty};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_errors::Applicability;
16 use crate::syntax::ast::LitKind;
17 use crate::syntax::source_map::Span;
18 use crate::utils::paths;
19 use crate::utils::sugg::Sugg;
21 expr_block, in_macro, is_allowed, is_expn_of, match_qpath, match_type, multispan_sugg, remove_blocks, snippet,
22 snippet_with_applicability, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty,
24 use if_chain::if_chain;
25 use std::cmp::Ordering;
26 use std::collections::Bound;
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.
38 /// Some(ref foo) => bar(foo),
42 declare_clippy_lint! {
45 "a match statement with a single nontrivial arm (i.e. where the other arm is `_ => {}`) instead of `if let`"
48 /// **What it does:** Checks for matches with a two arms where an `if let else` will
51 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
53 /// **Known problems:** Personal style preferences may differ.
61 /// Some(ref foo) => bar(foo),
62 /// _ => bar(other_ref),
66 /// Using `if let` with `else`:
69 /// if let Some(ref foo) = x {
75 declare_clippy_lint! {
76 pub SINGLE_MATCH_ELSE,
78 "a match statement with a two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
81 /// **What it does:** Checks for matches where all arms match a reference,
82 /// suggesting to remove the reference and deref the matched expression
83 /// instead. It also checks for `if let &foo = bar` blocks.
85 /// **Why is this bad?** It just makes the code less readable. That reference
86 /// destructuring adds nothing to the code.
88 /// **Known problems:** None.
93 /// &A(ref y) => foo(y),
98 declare_clippy_lint! {
101 "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
104 /// **What it does:** Checks for matches where match expression is a `bool`. It
105 /// suggests to replace the expression with an `if...else` block.
107 /// **Why is this bad?** It makes the code less readable.
109 /// **Known problems:** None.
113 /// let condition: bool = true;
114 /// match condition {
119 /// Use if/else instead:
121 /// let condition: bool = true;
128 declare_clippy_lint! {
131 "a match on a boolean expression instead of an `if..else` block"
134 /// **What it does:** Checks for overlapping match arms.
136 /// **Why is this bad?** It is likely to be an error and if not, makes the code
139 /// **Known problems:** None.
145 /// 1...10 => println!("1 ... 10"),
146 /// 5...15 => println!("5 ... 15"),
150 declare_clippy_lint! {
151 pub MATCH_OVERLAPPING_ARM,
153 "a match with overlapping arms"
156 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
157 /// and take drastic actions like `panic!`.
159 /// **Why is this bad?** It is generally a bad practice, just like
160 /// catching all exceptions in java with `catch(Exception)`
162 /// **Known problems:** None.
166 /// let x: Result(i32, &str) = Ok(3);
168 /// Ok(_) => println!("ok"),
169 /// Err(_) => panic!("err"),
172 declare_clippy_lint! {
173 pub MATCH_WILD_ERR_ARM,
175 "a match with `Err(_)` arm and take drastic actions"
178 /// **What it does:** Checks for match which is used to add a reference to an
181 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
183 /// **Known problems:** None.
187 /// let x: Option<()> = None;
188 /// let r: Option<&()> = match x {
190 /// Some(ref v) => Some(v),
193 declare_clippy_lint! {
196 "a match on an Option value instead of using `as_ref()` or `as_mut`"
199 #[allow(missing_copy_implementations)]
200 pub struct MatchPass;
202 impl LintPass for MatchPass {
203 fn get_lints(&self) -> LintArray {
209 MATCH_OVERLAPPING_ARM,
216 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
217 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
218 if in_external_macro(cx.sess(), expr.span) {
221 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
222 check_single_match(cx, ex, arms, expr);
223 check_match_bool(cx, ex, arms, expr);
224 check_overlapping_arms(cx, ex, arms);
225 check_wild_err_arm(cx, ex, arms);
226 check_match_as_ref(cx, ex, arms, expr);
228 if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
229 check_match_ref_pats(cx, ex, arms, expr);
235 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
236 if arms.len() == 2 &&
237 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
238 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
239 let els = remove_blocks(&arms[1].body);
240 let els = if is_unit_expr(els) {
242 } else if let ExprKind::Block(_, _) = els.node {
243 // matches with blocks that contain statements are prettier as `if let + else`
246 // allow match arms with just expressions
249 let ty = cx.tables.expr_ty(ex);
250 if ty.sty != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.id) {
251 check_single_match_single_pattern(cx, ex, arms, expr, els);
252 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
257 fn check_single_match_single_pattern(
258 cx: &LateContext<'_, '_>,
264 if is_wild(&arms[1].pats[0]) {
265 report_single_match_single_pattern(cx, ex, arms, expr, els);
269 fn report_single_match_single_pattern(
270 cx: &LateContext<'_, '_>,
276 let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
277 let els_str = els.map_or(String::new(), |els| {
278 format!(" else {}", expr_block(cx, els, None, ".."))
284 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
288 "if let {} = {} {}{}",
289 snippet(cx, arms[0].pats[0].span, ".."),
290 snippet(cx, ex.span, ".."),
291 expr_block(cx, &arms[0].body, None, ".."),
294 Applicability::HasPlaceholders,
298 fn check_single_match_opt_like(
299 cx: &LateContext<'_, '_>,
306 // list of candidate Enums we know will never get any more members
308 (&paths::COW, "Borrowed"),
309 (&paths::COW, "Cow::Borrowed"),
310 (&paths::COW, "Cow::Owned"),
311 (&paths::COW, "Owned"),
312 (&paths::OPTION, "None"),
313 (&paths::RESULT, "Err"),
314 (&paths::RESULT, "Ok"),
317 let path = match arms[1].pats[0].node {
318 PatKind::TupleStruct(ref path, ref inner, _) => {
319 // contains any non wildcard patterns? e.g. Err(err)
320 if !inner.iter().all(is_wild) {
323 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
325 PatKind::Binding(BindingAnnotation::Unannotated, _, ident, None) => ident.to_string(),
326 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
330 for &(ty_path, pat_path) in candidates {
331 if path == *pat_path && match_type(cx, ty, ty_path) {
332 report_single_match_single_pattern(cx, ex, arms, expr, els);
337 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
338 // type of expression == bool
339 if cx.tables.expr_ty(ex).sty == ty::Bool {
344 "you seem to be trying to match on a boolean expression",
346 if arms.len() == 2 && arms[0].pats.len() == 1 {
348 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
349 if let ExprKind::Lit(ref lit) = arm_bool.node {
351 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
352 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
362 if let Some((true_expr, false_expr)) = exprs {
363 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
364 (false, false) => Some(format!(
366 snippet(cx, ex.span, "b"),
367 expr_block(cx, true_expr, None, ".."),
368 expr_block(cx, false_expr, None, "..")
370 (false, true) => Some(format!(
372 snippet(cx, ex.span, "b"),
373 expr_block(cx, true_expr, None, "..")
376 let test = Sugg::hir(cx, ex, "..");
377 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
379 (true, true) => None,
382 if let Some(sugg) = sugg {
383 db.span_suggestion_with_applicability(
385 "consider using an if/else expression",
387 Applicability::HasPlaceholders,
397 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
398 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
399 let ranges = all_ranges(cx, arms);
400 let type_ranges = type_ranges(&ranges);
401 if !type_ranges.is_empty() {
402 if let Some((start, end)) = overlapping(&type_ranges) {
405 MATCH_OVERLAPPING_ARM,
407 "some ranges overlap",
409 "overlaps with this",
416 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
418 PatKind::Wild => true,
423 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
424 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
425 if match_type(cx, ex_ty, &paths::RESULT) {
427 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
428 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
430 if path_str == "Err";
431 if inner.iter().any(is_wild);
432 if let ExprKind::Block(ref block, _) = arm.body.node;
433 if is_panic_block(block);
435 // `Err(_)` arm with `panic!` found
436 span_note_and_lint(cx,
439 "Err(_) will match all errors, maybe not a good idea",
441 "to remove this warning, match each error separately \
442 or use unreachable macro");
450 // If the block contains only a `panic!` macro (as expression or statement)
451 fn is_panic_block(block: &Block) -> bool {
452 match (&block.expr, block.stmts.len(), block.stmts.first()) {
453 (&Some(ref exp), 0, _) => {
454 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
456 (&None, 1, Some(stmt)) => {
457 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
463 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
464 if has_only_ref_pats(arms) {
465 let mut suggs = Vec::new();
466 let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
467 suggs.push((ex.span, Sugg::hir(cx, inner, "..").to_string()));
469 "you don't need to add `&` to both the expression and the patterns",
473 suggs.push((ex.span, Sugg::hir(cx, ex, "..").deref().to_string()));
475 "you don't need to add `&` to all patterns",
476 "instead of prefixing all patterns with `&`, you can dereference the expression",
480 suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
481 if let PatKind::Ref(ref refp, _) = p.node {
482 Some((p.span, snippet(cx, refp.span, "..").to_string()))
488 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
489 if !in_macro(expr.span) {
490 multispan_sugg(db, msg.to_owned(), suggs);
496 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
498 && arms[0].pats.len() == 1
499 && arms[0].guard.is_none()
500 && arms[1].pats.len() == 1
501 && arms[1].guard.is_none()
503 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
504 is_ref_some_arm(&arms[1])
505 } else if is_none_arm(&arms[1]) {
506 is_ref_some_arm(&arms[0])
510 if let Some(rb) = arm_ref {
511 let suggestion = if rb == BindingAnnotation::Ref {
516 let mut applicability = Applicability::MachineApplicable;
521 &format!("use {}() instead", suggestion),
525 snippet_with_applicability(cx, ex.span, "_", &mut applicability),
534 /// Get all arms that are unbounded `PatRange`s.
535 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
539 ref pats, guard: None, ..
547 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
548 let lhs = constant(cx, cx.tables, lhs)?.0;
549 let rhs = constant(cx, cx.tables, rhs)?.0;
550 let rhs = match *range_end {
551 RangeEnd::Included => Bound::Included(rhs),
552 RangeEnd::Excluded => Bound::Excluded(rhs),
554 return Some(SpannedRange {
560 if let PatKind::Lit(ref value) = pat.node {
561 let value = constant(cx, cx.tables, value)?.0;
562 return Some(SpannedRange {
564 node: (value.clone(), Bound::Included(value)),
574 #[derive(Debug, Eq, PartialEq)]
575 pub struct SpannedRange<T> {
577 pub node: (T, Bound<T>),
580 type TypedRanges = Vec<SpannedRange<u128>>;
582 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
583 /// and other types than
584 /// `Uint` and `Int` probably don't make sense.
585 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
588 .filter_map(|range| match range.node {
589 (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
591 node: (start, Bound::Included(end)),
593 (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
595 node: (start, Bound::Excluded(end)),
597 (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
599 node: (start, Bound::Unbounded),
606 fn is_unit_expr(expr: &Expr) -> bool {
608 ExprKind::Tup(ref v) if v.is_empty() => true,
609 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
614 // Checks if arm has the form `None => None`
615 fn is_none_arm(arm: &Arm) -> bool {
616 match arm.pats[0].node {
617 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
622 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
623 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
625 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
626 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
627 if let PatKind::Binding(rb, _, ident, _) = pats[0].node;
628 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
629 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
630 if let ExprKind::Path(ref some_path) = e.node;
631 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
632 if let ExprKind::Path(ref qpath) = args[0].node;
633 if let &QPath::Resolved(_, ref path2) = qpath;
634 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
642 fn has_only_ref_pats(arms: &[Arm]) -> bool {
645 .flat_map(|a| &a.pats)
648 PatKind::Ref(..) => Some(true), // &-patterns
649 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
650 _ => None, // any other pattern is not fine
653 .collect::<Option<Vec<bool>>>();
654 // look for Some(v) where there's at least one true element
655 mapped.map_or(false, |v| v.iter().any(|el| *el))
658 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
662 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
663 enum Kind<'a, T: 'a> {
664 Start(T, &'a SpannedRange<T>),
665 End(Bound<T>, &'a SpannedRange<T>),
668 impl<'a, T: Copy> Kind<'a, T> {
669 fn range(&self) -> &'a SpannedRange<T> {
671 Kind::Start(_, r) | Kind::End(_, r) => r,
675 fn value(self) -> Bound<T> {
677 Kind::Start(t, _) => Bound::Included(t),
678 Kind::End(t, _) => t,
683 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
684 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
685 Some(self.cmp(other))
689 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
690 fn cmp(&self, other: &Self) -> Ordering {
691 match (self.value(), other.value()) {
692 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
693 // Range patterns cannot be unbounded (yet)
694 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
695 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
696 Ordering::Equal => Ordering::Greater,
699 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
700 Ordering::Equal => Ordering::Less,
707 let mut values = Vec::with_capacity(2 * ranges.len());
710 values.push(Kind::Start(r.node.0, r));
711 values.push(Kind::End(r.node.1, r));
716 for (a, b) in values.iter().zip(values.iter().skip(1)) {
718 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
719 if ra.node != rb.node {
720 return Some((ra, rb));
723 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
724 _ => return Some((a.range(), b.range())),