3 use rustc::middle::const_val::ConstVal;
4 use rustc::ty::{self, Ty};
5 use rustc::ty::subst::Substs;
6 use rustc_const_eval::ConstContext;
7 use rustc_const_math::ConstInt;
8 use std::cmp::Ordering;
9 use std::collections::Bound;
10 use syntax::ast::LitKind;
11 use syntax::ast::NodeId;
12 use syntax::codemap::Span;
14 use utils::{expr_block, in_external_macro, is_allowed, is_expn_of, match_qpath, match_type, remove_blocks,
15 snippet, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty};
16 use utils::sugg::Sugg;
18 /// **What it does:** Checks for matches with a single arm where an `if let`
19 /// will usually suffice.
21 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
23 /// **Known problems:** None.
28 /// Some(ref foo) => bar(foo),
35 "a match statement with a single nontrivial arm (i.e. where the other arm \
36 is `_ => {}`) instead of `if let`"
39 /// **What it does:** Checks for matches with a two arms where an `if let` will
42 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
44 /// **Known problems:** Personal style preferences may differ.
49 /// Some(ref foo) => bar(foo),
50 /// _ => bar(other_ref),
54 pub SINGLE_MATCH_ELSE,
56 "a match statement with a two arms where the second arm's pattern is a wildcard \
60 /// **What it does:** Checks for matches where all arms match a reference,
61 /// suggesting to remove the reference and deref the matched expression
62 /// instead. It also checks for `if let &foo = bar` blocks.
64 /// **Why is this bad?** It just makes the code less readable. That reference
65 /// destructuring adds nothing to the code.
67 /// **Known problems:** None.
72 /// &A(ref y) => foo(y),
80 "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
83 /// **What it does:** Checks for matches where match expression is a `bool`. It
84 /// suggests to replace the expression with an `if...else` block.
86 /// **Why is this bad?** It makes the code less readable.
88 /// **Known problems:** None.
92 /// let condition: bool = true;
101 "a match on a boolean expression instead of an `if..else` block"
104 /// **What it does:** Checks for overlapping match arms.
106 /// **Why is this bad?** It is likely to be an error and if not, makes the code
109 /// **Known problems:** None.
115 /// 1 ... 10 => println!("1 ... 10"),
116 /// 5 ... 15 => println!("5 ... 15"),
121 pub MATCH_OVERLAPPING_ARM,
123 "a match with overlapping arms"
126 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
127 /// and take drastic actions like `panic!`.
129 /// **Why is this bad?** It is generally a bad practice, just like
130 /// catching all exceptions in java with `catch(Exception)`
132 /// **Known problems:** None.
136 /// let x : Result(i32, &str) = Ok(3);
138 /// Ok(_) => println!("ok"),
139 /// Err(_) => panic!("err"),
143 pub MATCH_WILD_ERR_ARM,
145 "a match with `Err(_)` arm and take drastic actions"
148 /// **What it does:** Checks for match which is used to add a reference to an
151 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
153 /// **Known problems:** None.
157 /// let x: Option<()> = None;
158 /// let r: Option<&()> = match x {
160 /// Some(ref v) => Some(v),
166 "a match on an Option value instead of using `as_ref()` or `as_mut`"
169 #[allow(missing_copy_implementations)]
170 pub struct MatchPass;
172 impl LintPass for MatchPass {
173 fn get_lints(&self) -> LintArray {
179 MATCH_OVERLAPPING_ARM,
186 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
187 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
188 if in_external_macro(cx, expr.span) {
191 if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
192 check_single_match(cx, ex, arms, expr);
193 check_match_bool(cx, ex, arms, expr);
194 check_overlapping_arms(cx, ex, arms);
195 check_wild_err_arm(cx, ex, arms);
196 check_match_as_ref(cx, ex, arms, expr);
198 if let ExprMatch(ref ex, ref arms, source) = expr.node {
199 check_match_ref_pats(cx, ex, arms, source, expr);
204 #[cfg_attr(rustfmt, rustfmt_skip)]
205 fn check_single_match(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
206 if arms.len() == 2 &&
207 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
208 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
209 let els = remove_blocks(&arms[1].body);
210 let els = if is_unit_expr(els) {
212 } else if let ExprBlock(_) = els.node {
213 // matches with blocks that contain statements are prettier as `if let + else`
216 // allow match arms with just expressions
219 let ty = cx.tables.expr_ty(ex);
220 if ty.sty != ty::TyBool || is_allowed(cx, MATCH_BOOL, ex.id) {
221 check_single_match_single_pattern(cx, ex, arms, expr, els);
222 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
227 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
228 if arms[1].pats[0].node == PatKind::Wild {
229 report_single_match_single_pattern(cx, ex, arms, expr, els);
233 fn report_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
234 let lint = if els.is_some() {
239 let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
244 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
248 "if let {} = {} {}{}",
249 snippet(cx, arms[0].pats[0].span, ".."),
250 snippet(cx, ex.span, ".."),
251 expr_block(cx, &arms[0].body, None, ".."),
257 fn check_single_match_opt_like(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, ty: Ty, els: Option<&Expr>) {
258 // list of candidate Enums we know will never get any more members
260 (&paths::COW, "Borrowed"),
261 (&paths::COW, "Cow::Borrowed"),
262 (&paths::COW, "Cow::Owned"),
263 (&paths::COW, "Owned"),
264 (&paths::OPTION, "None"),
265 (&paths::RESULT, "Err"),
266 (&paths::RESULT, "Ok"),
269 let path = match arms[1].pats[0].node {
270 PatKind::TupleStruct(ref path, ref inner, _) => {
271 // contains any non wildcard patterns? e.g. Err(err)
272 if inner.iter().any(|pat| pat.node != PatKind::Wild) {
275 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
277 PatKind::Binding(BindingAnnotation::Unannotated, _, ident, None) => ident.node.to_string(),
278 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
282 for &(ty_path, pat_path) in candidates {
283 if path == *pat_path && match_type(cx, ty, ty_path) {
284 report_single_match_single_pattern(cx, ex, arms, expr, els);
289 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
290 // type of expression == bool
291 if cx.tables.expr_ty(ex).sty == ty::TyBool {
296 "you seem to be trying to match on a boolean expression",
298 if arms.len() == 2 && arms[0].pats.len() == 1 {
300 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
301 if let ExprLit(ref lit) = arm_bool.node {
303 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
304 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
314 if let Some((true_expr, false_expr)) = exprs {
315 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
316 (false, false) => Some(format!(
318 snippet(cx, ex.span, "b"),
319 expr_block(cx, true_expr, None, ".."),
320 expr_block(cx, false_expr, None, "..")
322 (false, true) => Some(format!(
324 snippet(cx, ex.span, "b"),
325 expr_block(cx, true_expr, None, "..")
328 let test = Sugg::hir(cx, ex, "..");
329 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
331 (true, true) => None,
334 if let Some(sugg) = sugg {
335 db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
344 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
345 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
346 let ranges = all_ranges(cx, arms, ex.id);
347 let type_ranges = type_ranges(&ranges);
348 if !type_ranges.is_empty() {
349 if let Some((start, end)) = overlapping(&type_ranges) {
352 MATCH_OVERLAPPING_ARM,
354 "some ranges overlap",
356 "overlaps with this",
363 fn check_wild_err_arm(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
364 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
365 if match_type(cx, ex_ty, &paths::RESULT) {
367 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
368 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
370 if path_str == "Err";
371 if inner.iter().any(|pat| pat.node == PatKind::Wild);
372 if let ExprBlock(ref block) = arm.body.node;
373 if is_panic_block(block);
375 // `Err(_)` arm with `panic!` found
376 span_note_and_lint(cx,
379 "Err(_) will match all errors, maybe not a good idea",
381 "to remove this warning, match each error seperately \
382 or use unreachable macro");
390 // If the block contains only a `panic!` macro (as expression or statement)
391 fn is_panic_block(block: &Block) -> bool {
392 match (&block.expr, block.stmts.len(), block.stmts.first()) {
393 (&Some(ref exp), 0, _) => {
394 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
396 (&None, 1, Some(stmt)) => {
397 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
403 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
404 if has_only_ref_pats(arms) {
405 if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
410 "you don't need to add `&` to both the expression and the patterns",
412 let inner = Sugg::hir(cx, inner, "..");
413 let template = match_template(expr.span, source, &inner);
414 db.span_suggestion(expr.span, "try", template);
422 "you don't need to add `&` to all patterns",
424 let ex = Sugg::hir(cx, ex, "..");
425 let template = match_template(expr.span, source, &ex.deref());
428 "instead of prefixing all patterns with `&`, you can dereference the expression",
437 fn check_match_as_ref(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
438 if arms.len() == 2 &&
439 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
440 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
441 let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
442 is_ref_some_arm(&arms[1])
443 } else if is_none_arm(&arms[1]) {
444 is_ref_some_arm(&arms[0])
448 if let Some(rb) = arm_ref {
449 let suggestion = if rb == BindingAnnotation::Ref { "as_ref" } else { "as_mut" };
454 &format!("use {}() instead", suggestion),
456 format!("{}.{}()", snippet(cx, ex.span, "_"), suggestion)
462 /// Get all arms that are unbounded `PatRange`s.
463 fn all_ranges<'a, 'tcx>(
464 cx: &LateContext<'a, 'tcx>,
467 ) -> Vec<SpannedRange<&'tcx ty::Const<'tcx>>> {
468 let parent_item = cx.tcx.hir.get_parent(id);
469 let parent_def_id = cx.tcx.hir.local_def_id(parent_item);
470 let substs = Substs::identity_for_item(cx.tcx, parent_def_id);
471 let constcx = ConstContext::new(cx.tcx, cx.param_env.and(substs), cx.tables);
485 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node;
486 if let Ok(lhs) = constcx.eval(lhs);
487 if let Ok(rhs) = constcx.eval(rhs);
489 let rhs = match *range_end {
490 RangeEnd::Included => Bound::Included(rhs),
491 RangeEnd::Excluded => Bound::Excluded(rhs),
493 return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
498 if let PatKind::Lit(ref value) = pat.node;
499 if let Ok(value) = constcx.eval(value);
501 return Some(SpannedRange { span: pat.span, node: (value, Bound::Included(value)) });
511 #[derive(Debug, Eq, PartialEq)]
512 pub struct SpannedRange<T> {
514 pub node: (T, Bound<T>),
517 type TypedRanges = Vec<SpannedRange<ConstInt>>;
519 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
520 /// and other types than
521 /// `Uint` and `Int` probably don't make sense.
522 fn type_ranges(ranges: &[SpannedRange<&ty::Const>]) -> TypedRanges {
525 .filter_map(|range| match range.node {
528 val: ConstVal::Integral(start),
531 Bound::Included(&ty::Const {
532 val: ConstVal::Integral(end),
535 ) => Some(SpannedRange {
537 node: (start, Bound::Included(end)),
541 val: ConstVal::Integral(start),
544 Bound::Excluded(&ty::Const {
545 val: ConstVal::Integral(end),
548 ) => Some(SpannedRange {
550 node: (start, Bound::Excluded(end)),
554 val: ConstVal::Integral(start),
558 ) => Some(SpannedRange {
560 node: (start, Bound::Unbounded),
567 fn is_unit_expr(expr: &Expr) -> bool {
569 ExprTup(ref v) if v.is_empty() => true,
570 ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
575 // Checks if arm has the form `None => None`
576 fn is_none_arm(arm: &Arm) -> bool {
577 match arm.pats[0].node {
578 PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
583 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
584 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
586 if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
587 if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
588 if let PatKind::Binding(rb, _, ref ident, _) = pats[0].node;
589 if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
590 if let ExprCall(ref e, ref args) = remove_blocks(&arm.body).node;
591 if let ExprPath(ref some_path) = e.node;
592 if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
593 if let ExprPath(ref qpath) = args[0].node;
594 if let &QPath::Resolved(_, ref path2) = qpath;
595 if path2.segments.len() == 1 && ident.node == path2.segments[0].name;
603 fn has_only_ref_pats(arms: &[Arm]) -> bool {
604 let mapped = arms.iter()
605 .flat_map(|a| &a.pats)
608 PatKind::Ref(..) => Some(true), // &-patterns
609 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
610 _ => None, // any other pattern is not fine
613 .collect::<Option<Vec<bool>>>();
614 // look for Some(v) where there's at least one true element
615 mapped.map_or(false, |v| v.iter().any(|el| *el))
618 fn match_template(span: Span, source: MatchSource, expr: &Sugg) -> String {
620 MatchSource::Normal => format!("match {} {{ .. }}", expr),
621 MatchSource::IfLetDesugar { .. } => format!("if let .. = {} {{ .. }}", expr),
622 MatchSource::WhileLetDesugar => format!("while let .. = {} {{ .. }}", expr),
623 MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
624 MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
628 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
632 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
633 enum Kind<'a, T: 'a> {
634 Start(T, &'a SpannedRange<T>),
635 End(Bound<T>, &'a SpannedRange<T>),
638 impl<'a, T: Copy> Kind<'a, T> {
639 fn range(&self) -> &'a SpannedRange<T> {
641 Kind::Start(_, r) | Kind::End(_, r) => r,
645 fn value(self) -> Bound<T> {
647 Kind::Start(t, _) => Bound::Included(t),
648 Kind::End(t, _) => t,
653 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
654 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
655 Some(self.cmp(other))
659 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
660 fn cmp(&self, other: &Self) -> Ordering {
661 match (self.value(), other.value()) {
662 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
663 // Range patterns cannot be unbounded (yet)
664 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
665 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
666 Ordering::Equal => Ordering::Greater,
669 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
670 Ordering::Equal => Ordering::Less,
677 let mut values = Vec::with_capacity(2 * ranges.len());
680 values.push(Kind::Start(r.node.0, r));
681 values.push(Kind::End(r.node.1, r));
686 for (a, b) in values.iter().zip(values.iter().skip(1)) {
688 (&Kind::Start(_, ra), &Kind::End(_, rb)) => if ra.node != rb.node {
689 return Some((ra, rb));
691 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
692 _ => return Some((a.range(), b.range())),