3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use rustc::ty::{self, Ty};
6 use std::cmp::Ordering;
7 use std::collections::Bound;
8 use syntax::ast::LitKind;
9 use syntax::codemap::Span;
10 use crate::utils::paths;
11 use crate::utils::{expr_block, is_allowed, is_expn_of, match_qpath, match_type, multispan_sugg,
12 remove_blocks, snippet, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
13 use crate::utils::sugg::Sugg;
14 use crate::consts::{constant, Constant};
16 /// **What it does:** Checks for matches with a single arm where an `if let`
17 /// will usually suffice.
19 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
21 /// **Known problems:** None.
26 /// Some(ref foo) => bar(foo),
30 declare_clippy_lint! {
33 "a match statement with a single nontrivial arm (i.e. where the other arm \
34 is `_ => {}`) instead of `if let`"
37 /// **What it does:** Checks for matches with a two arms where an `if let` will
40 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
42 /// **Known problems:** Personal style preferences may differ.
47 /// Some(ref foo) => bar(foo),
48 /// _ => bar(other_ref),
51 declare_clippy_lint! {
52 pub SINGLE_MATCH_ELSE,
54 "a match statement with a two arms where the second arm's pattern is a wildcard \
58 /// **What it does:** Checks for matches where all arms match a reference,
59 /// suggesting to remove the reference and deref the matched expression
60 /// instead. It also checks for `if let &foo = bar` blocks.
62 /// **Why is this bad?** It just makes the code less readable. That reference
63 /// destructuring adds nothing to the code.
65 /// **Known problems:** None.
70 /// &A(ref y) => foo(y),
75 declare_clippy_lint! {
78 "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
81 /// **What it does:** Checks for matches where match expression is a `bool`. It
82 /// suggests to replace the expression with an `if...else` block.
84 /// **Why is this bad?** It makes the code less readable.
86 /// **Known problems:** None.
90 /// let condition: bool = true;
96 declare_clippy_lint! {
99 "a match on a boolean expression instead of an `if..else` block"
102 /// **What it does:** Checks for overlapping match arms.
104 /// **Why is this bad?** It is likely to be an error and if not, makes the code
107 /// **Known problems:** None.
113 /// 1 ... 10 => println!("1 ... 10"),
114 /// 5 ... 15 => println!("5 ... 15"),
118 declare_clippy_lint! {
119 pub MATCH_OVERLAPPING_ARM,
121 "a match with overlapping arms"
124 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
125 /// and take drastic actions like `panic!`.
127 /// **Why is this bad?** It is generally a bad practice, just like
128 /// catching all exceptions in java with `catch(Exception)`
130 /// **Known problems:** None.
134 /// let x : Result(i32, &str) = Ok(3);
136 /// Ok(_) => println!("ok"),
137 /// Err(_) => panic!("err"),
140 declare_clippy_lint! {
141 pub MATCH_WILD_ERR_ARM,
143 "a match with `Err(_)` arm and take drastic actions"
146 /// **What it does:** Checks for match which is used to add a reference to an
149 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
151 /// **Known problems:** None.
155 /// let x: Option<()> = None;
156 /// let r: Option<&()> = match x {
158 /// Some(ref v) => Some(v),
161 declare_clippy_lint! {
164 "a match on an Option value instead of using `as_ref()` or `as_mut`"
167 #[allow(missing_copy_implementations)]
168 pub struct MatchPass;
170 impl LintPass for MatchPass {
171 fn get_lints(&self) -> LintArray {
177 MATCH_OVERLAPPING_ARM,
184 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
185 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
186 if in_external_macro(cx.sess(), expr.span) {
189 if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
190 check_single_match(cx, ex, arms, expr);
191 check_match_bool(cx, ex, arms, expr);
192 check_overlapping_arms(cx, ex, arms);
193 check_wild_err_arm(cx, ex, arms);
194 check_match_as_ref(cx, ex, arms, expr);
196 if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
197 check_match_ref_pats(cx, ex, arms, expr);
202 #[cfg_attr(rustfmt, rustfmt_skip)]
203 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
204 if arms.len() == 2 &&
205 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
206 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
207 let els = remove_blocks(&arms[1].body);
208 let els = if is_unit_expr(els) {
210 } else if let ExprKind::Block(_, _) = els.node {
211 // matches with blocks that contain statements are prettier as `if let + else`
214 // allow match arms with just expressions
217 let ty = cx.tables.expr_ty(ex);
218 if ty.sty != ty::TyBool || is_allowed(cx, MATCH_BOOL, ex.id) {
219 check_single_match_single_pattern(cx, ex, arms, expr, els);
220 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
225 fn check_single_match_single_pattern(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
226 if is_wild(&arms[1].pats[0]) {
227 report_single_match_single_pattern(cx, ex, arms, expr, els);
231 fn report_single_match_single_pattern(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
232 let lint = if els.is_some() {
237 let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
242 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
246 "if let {} = {} {}{}",
247 snippet(cx, arms[0].pats[0].span, ".."),
248 snippet(cx, ex.span, ".."),
249 expr_block(cx, &arms[0].body, None, ".."),
255 fn check_single_match_opt_like(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr, ty: Ty<'_>, els: Option<&Expr>) {
256 // list of candidate Enums we know will never get any more members
258 (&paths::COW, "Borrowed"),
259 (&paths::COW, "Cow::Borrowed"),
260 (&paths::COW, "Cow::Owned"),
261 (&paths::COW, "Owned"),
262 (&paths::OPTION, "None"),
263 (&paths::RESULT, "Err"),
264 (&paths::RESULT, "Ok"),
267 let path = match arms[1].pats[0].node {
268 PatKind::TupleStruct(ref path, ref inner, _) => {
269 // contains any non wildcard patterns? e.g. Err(err)
270 if !inner.iter().all(is_wild) {
273 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
275 PatKind::Binding(BindingAnnotation::Unannotated, _, ident, None) => ident.to_string(),
276 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
280 for &(ty_path, pat_path) in candidates {
281 if path == *pat_path && match_type(cx, ty, ty_path) {
282 report_single_match_single_pattern(cx, ex, arms, expr, els);
287 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
288 // type of expression == bool
289 if cx.tables.expr_ty(ex).sty == ty::TyBool {
294 "you seem to be trying to match on a boolean expression",
296 if arms.len() == 2 && arms[0].pats.len() == 1 {
298 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
299 if let ExprKind::Lit(ref lit) = arm_bool.node {
301 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
302 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
312 if let Some((true_expr, false_expr)) = exprs {
313 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
314 (false, false) => Some(format!(
316 snippet(cx, ex.span, "b"),
317 expr_block(cx, true_expr, None, ".."),
318 expr_block(cx, false_expr, None, "..")
320 (false, true) => Some(format!(
322 snippet(cx, ex.span, "b"),
323 expr_block(cx, true_expr, None, "..")
326 let test = Sugg::hir(cx, ex, "..");
327 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
329 (true, true) => None,
332 if let Some(sugg) = sugg {
333 db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
342 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
343 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
344 let ranges = all_ranges(cx, arms);
345 let type_ranges = type_ranges(&ranges);
346 if !type_ranges.is_empty() {
347 if let Some((start, end)) = overlapping(&type_ranges) {
350 MATCH_OVERLAPPING_ARM,
352 "some ranges overlap",
354 "overlaps with this",
361 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
363 PatKind::Wild => true,
368 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
369 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
370 if match_type(cx, ex_ty, &paths::RESULT) {
372 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
373 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
375 if path_str == "Err";
376 if inner.iter().any(is_wild);
377 if let ExprKind::Block(ref block, _) = arm.body.node;
378 if is_panic_block(block);
380 // `Err(_)` arm with `panic!` found
381 span_note_and_lint(cx,
384 "Err(_) will match all errors, maybe not a good idea",
386 "to remove this warning, match each error separately \
387 or use unreachable macro");
395 // If the block contains only a `panic!` macro (as expression or statement)
396 fn is_panic_block(block: &Block) -> bool {
397 match (&block.expr, block.stmts.len(), block.stmts.first()) {
398 (&Some(ref exp), 0, _) => {
399 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
401 (&None, 1, Some(stmt)) => {
402 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
408 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
409 if has_only_ref_pats(arms) {
410 let mut suggs = Vec::new();
411 let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
412 suggs.push((ex.span, Sugg::hir(cx, inner, "..").to_string()));
414 "you don't need to add `&` to both the expression and the patterns",
418 suggs.push((ex.span, Sugg::hir(cx, ex, "..").deref().to_string()));
420 "you don't need to add `&` to all patterns",
421 "instead of prefixing all patterns with `&`, you can dereference the expression",
425 suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
426 if let PatKind::Ref(ref refp, _) = p.node {
427 Some((p.span, snippet(cx, refp.span, "..").to_string()))
433 span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
434 multispan_sugg(db, msg.to_owned(), suggs);
439 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
440 if arms.len() == 2 &&
441 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
442 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
443 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
444 is_ref_some_arm(&arms[1])
445 } else if is_none_arm(&arms[1]) {
446 is_ref_some_arm(&arms[0])
450 if let Some(rb) = arm_ref {
451 let suggestion = if rb == BindingAnnotation::Ref { "as_ref" } else { "as_mut" };
456 &format!("use {}() instead", suggestion),
458 format!("{}.{}()", snippet(cx, ex.span, "_"), suggestion)
464 /// Get all arms that are unbounded `PatRange`s.
465 fn all_ranges<'a, 'tcx>(
466 cx: &LateContext<'a, 'tcx>,
468 ) -> Vec<SpannedRange<Constant>> {
481 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
482 let lhs = constant(cx, cx.tables, lhs)?.0;
483 let rhs = constant(cx, cx.tables, rhs)?.0;
484 let rhs = match *range_end {
485 RangeEnd::Included => Bound::Included(rhs),
486 RangeEnd::Excluded => Bound::Excluded(rhs),
488 return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
491 if let PatKind::Lit(ref value) = pat.node {
492 let value = constant(cx, cx.tables, value)?.0;
493 return Some(SpannedRange { span: pat.span, node: (value.clone(), Bound::Included(value)) });
502 #[derive(Debug, Eq, PartialEq)]
503 pub struct SpannedRange<T> {
505 pub node: (T, Bound<T>),
508 type TypedRanges = Vec<SpannedRange<u128>>;
510 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
511 /// and other types than
512 /// `Uint` and `Int` probably don't make sense.
513 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
516 .filter_map(|range| match range.node {
518 Constant::Int(start),
519 Bound::Included(Constant::Int(end)),
520 ) => Some(SpannedRange {
522 node: (start, Bound::Included(end)),
525 Constant::Int(start),
526 Bound::Excluded(Constant::Int(end)),
527 ) => Some(SpannedRange {
529 node: (start, Bound::Excluded(end)),
532 Constant::Int(start),
534 ) => Some(SpannedRange {
536 node: (start, Bound::Unbounded),
543 fn is_unit_expr(expr: &Expr) -> bool {
545 ExprKind::Tup(ref v) if v.is_empty() => true,
546 ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
551 // Checks if arm has the form `None => None`
552 fn is_none_arm(arm: &Arm) -> bool {
553 match arm.pats[0].node {
554 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
559 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
560 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
562 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
563 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
564 if let PatKind::Binding(rb, _, ident, _) = pats[0].node;
565 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
566 if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
567 if let ExprKind::Path(ref some_path) = e.node;
568 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
569 if let ExprKind::Path(ref qpath) = args[0].node;
570 if let &QPath::Resolved(_, ref path2) = qpath;
571 if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
579 fn has_only_ref_pats(arms: &[Arm]) -> bool {
580 let mapped = arms.iter()
581 .flat_map(|a| &a.pats)
584 PatKind::Ref(..) => Some(true), // &-patterns
585 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
586 _ => None, // any other pattern is not fine
589 .collect::<Option<Vec<bool>>>();
590 // look for Some(v) where there's at least one true element
591 mapped.map_or(false, |v| v.iter().any(|el| *el))
594 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
598 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
599 enum Kind<'a, T: 'a> {
600 Start(T, &'a SpannedRange<T>),
601 End(Bound<T>, &'a SpannedRange<T>),
604 impl<'a, T: Copy> Kind<'a, T> {
605 fn range(&self) -> &'a SpannedRange<T> {
607 Kind::Start(_, r) | Kind::End(_, r) => r,
611 fn value(self) -> Bound<T> {
613 Kind::Start(t, _) => Bound::Included(t),
614 Kind::End(t, _) => t,
619 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
620 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
621 Some(self.cmp(other))
625 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
626 fn cmp(&self, other: &Self) -> Ordering {
627 match (self.value(), other.value()) {
628 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
629 // Range patterns cannot be unbounded (yet)
630 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
631 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
632 Ordering::Equal => Ordering::Greater,
635 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
636 Ordering::Equal => Ordering::Less,
643 let mut values = Vec::with_capacity(2 * ranges.len());
646 values.push(Kind::Start(r.node.0, r));
647 values.push(Kind::End(r.node.1, r));
652 for (a, b) in values.iter().zip(values.iter().skip(1)) {
654 (&Kind::Start(_, ra), &Kind::End(_, rb)) => if ra.node != rb.node {
655 return Some((ra, rb));
657 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
658 _ => return Some((a.range(), b.range())),