3 use rustc::middle::const_val::ConstVal;
4 use rustc::ty::{self, Ty};
5 use rustc_const_eval::ConstContext;
6 use rustc_const_math::ConstInt;
7 use std::cmp::Ordering;
8 use std::collections::Bound;
9 use syntax::ast::LitKind;
10 use syntax::codemap::Span;
12 use utils::{match_type, snippet, span_note_and_lint, span_lint_and_then, in_external_macro, expr_block, walk_ptrs_ty,
13 is_expn_of, remove_blocks};
14 use utils::sugg::Sugg;
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),
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),
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),
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;
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"),
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"),
141 pub MATCH_WILD_ERR_ARM,
143 "a match with `Err(_)` arm and take drastic actions"
146 #[allow(missing_copy_implementations)]
147 pub struct MatchPass;
149 impl LintPass for MatchPass {
150 fn get_lints(&self) -> LintArray {
151 lint_array!(SINGLE_MATCH,
155 MATCH_OVERLAPPING_ARM,
160 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
161 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
162 if in_external_macro(cx, expr.span) {
165 if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
166 check_single_match(cx, ex, arms, expr);
167 check_match_bool(cx, ex, arms, expr);
168 check_overlapping_arms(cx, ex, arms);
169 check_wild_err_arm(cx, ex, arms);
171 if let ExprMatch(ref ex, ref arms, source) = expr.node {
172 check_match_ref_pats(cx, ex, arms, source, expr);
177 #[cfg_attr(rustfmt, rustfmt_skip)]
178 fn check_single_match(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
179 if arms.len() == 2 &&
180 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
181 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
182 let els = remove_blocks(&arms[1].body);
183 let els = if is_unit_expr(els) {
185 } else if let ExprBlock(_) = els.node {
186 // matches with blocks that contain statements are prettier as `if let + else`
189 // allow match arms with just expressions
192 let ty = cx.tables.expr_ty(ex);
193 if ty.sty != ty::TyBool || cx.current_level(MATCH_BOOL) == Allow {
194 check_single_match_single_pattern(cx, ex, arms, expr, els);
195 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
200 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
201 if arms[1].pats[0].node == PatKind::Wild {
202 report_single_match_single_pattern(cx, ex, arms, expr, els);
206 fn report_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
207 let lint = if els.is_some() {
212 let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
213 span_lint_and_then(cx,
216 "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
219 db.span_suggestion(expr.span,
221 format!("if let {} = {} {}{}",
222 snippet(cx, arms[0].pats[0].span, ".."),
223 snippet(cx, ex.span, ".."),
224 expr_block(cx, &arms[0].body, None, ".."),
229 fn check_single_match_opt_like(
237 // list of candidate Enums we know will never get any more members
238 let candidates = &[(&paths::COW, "Borrowed"),
239 (&paths::COW, "Cow::Borrowed"),
240 (&paths::COW, "Cow::Owned"),
241 (&paths::COW, "Owned"),
242 (&paths::OPTION, "None"),
243 (&paths::RESULT, "Err"),
244 (&paths::RESULT, "Ok")];
246 let path = match arms[1].pats[0].node {
247 PatKind::TupleStruct(ref path, ref inner, _) => {
248 // contains any non wildcard patterns? e.g. Err(err)
249 if inner.iter().any(|pat| pat.node != PatKind::Wild) {
252 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
254 PatKind::Binding(BindByValue(MutImmutable), _, ident, None) => ident.node.to_string(),
255 PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
259 for &(ty_path, pat_path) in candidates {
260 if path == *pat_path && match_type(cx, ty, ty_path) {
261 report_single_match_single_pattern(cx, ex, arms, expr, els);
266 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
267 // type of expression == bool
268 if cx.tables.expr_ty(ex).sty == ty::TyBool {
269 span_lint_and_then(cx,
272 "you seem to be trying to match on a boolean expression",
274 if arms.len() == 2 && arms[0].pats.len() == 1 {
276 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
277 if let ExprLit(ref lit) = arm_bool.node {
279 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
280 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
290 if let Some((true_expr, false_expr)) = exprs {
291 let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
293 Some(format!("if {} {} else {}",
294 snippet(cx, ex.span, "b"),
295 expr_block(cx, true_expr, None, ".."),
296 expr_block(cx, false_expr, None, "..")))
299 Some(format!("if {} {}", snippet(cx, ex.span, "b"), expr_block(cx, true_expr, None, "..")))
302 let test = Sugg::hir(cx, ex, "..");
303 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
305 (true, true) => None,
308 if let Some(sugg) = sugg {
309 db.span_suggestion(expr.span, "consider using an if/else expression", sugg);
318 fn check_overlapping_arms(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
319 if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
320 let ranges = all_ranges(cx, arms);
321 let type_ranges = type_ranges(&ranges);
322 if !type_ranges.is_empty() {
323 if let Some((start, end)) = overlapping(&type_ranges) {
324 span_note_and_lint(cx,
325 MATCH_OVERLAPPING_ARM,
327 "some ranges overlap",
329 "overlaps with this");
335 fn check_wild_err_arm(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
336 let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
337 if match_type(cx, ex_ty, &paths::RESULT) {
339 if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
340 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
343 inner.iter().any(|pat| pat.node == PatKind::Wild),
344 let ExprBlock(ref block) = arm.body.node,
345 is_panic_block(block)
347 // `Err(_)` arm with `panic!` found
348 span_note_and_lint(cx,
351 "Err(_) will match all errors, maybe not a good idea",
353 "to remove this warning, match each error seperately \
354 or use unreachable macro");
361 // If the block contains only a `panic!` macro (as expression or statement)
362 fn is_panic_block(block: &Block) -> bool {
363 match (&block.expr, block.stmts.len(), block.stmts.first()) {
364 (&Some(ref exp), 0, _) => {
365 is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
367 (&None, 1, Some(stmt)) => {
368 is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
374 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
375 if has_only_ref_pats(arms) {
376 if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
377 span_lint_and_then(cx,
380 "you don't need to add `&` to both the expression and the patterns",
382 let inner = Sugg::hir(cx, inner, "..");
383 let template = match_template(expr.span, source, &inner);
384 db.span_suggestion(expr.span, "try", template);
387 span_lint_and_then(cx,
390 "you don't need to add `&` to all patterns",
392 let ex = Sugg::hir(cx, ex, "..");
393 let template = match_template(expr.span, source, &ex.deref());
394 db.span_suggestion(expr.span,
395 "instead of prefixing all patterns with `&`, you can dereference the expression",
402 /// Get all arms that are unbounded `PatRange`s.
403 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &[Arm]) -> Vec<SpannedRange<ConstVal<'tcx>>> {
404 let constcx = ConstContext::with_tables(cx.tcx, cx.tables);
407 if let Arm { ref pats, guard: None, .. } = *arm {
414 let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node,
415 let Ok(lhs) = constcx.eval(lhs),
416 let Ok(rhs) = constcx.eval(rhs)
418 let rhs = match *range_end {
419 RangeEnd::Included => Bound::Included(rhs),
420 RangeEnd::Excluded => Bound::Excluded(rhs),
422 return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
426 let PatKind::Lit(ref value) = pat.node,
427 let Ok(value) = constcx.eval(value)
429 return Some(SpannedRange { span: pat.span, node: (value.clone(), Bound::Included(value)) });
438 #[derive(Debug, Eq, PartialEq)]
439 pub struct SpannedRange<T> {
441 pub node: (T, Bound<T>),
444 type TypedRanges = Vec<SpannedRange<ConstInt>>;
446 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway and other types than
447 /// `Uint` and `Int` probably don't make sense.
448 fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
450 .filter_map(|range| match range.node {
451 (ConstVal::Integral(start), Bound::Included(ConstVal::Integral(end))) => {
454 node: (start, Bound::Included(end)),
457 (ConstVal::Integral(start), Bound::Excluded(ConstVal::Integral(end))) => {
460 node: (start, Bound::Excluded(end)),
463 (ConstVal::Integral(start), Bound::Unbounded) => {
466 node: (start, Bound::Unbounded),
474 fn is_unit_expr(expr: &Expr) -> bool {
476 ExprTup(ref v) if v.is_empty() => true,
477 ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
482 fn has_only_ref_pats(arms: &[Arm]) -> bool {
483 let mapped = arms.iter()
484 .flat_map(|a| &a.pats)
487 PatKind::Ref(..) => Some(true), // &-patterns
488 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
489 _ => None, // any other pattern is not fine
492 .collect::<Option<Vec<bool>>>();
493 // look for Some(v) where there's at least one true element
494 mapped.map_or(false, |v| v.iter().any(|el| *el))
497 fn match_template(span: Span, source: MatchSource, expr: &Sugg) -> String {
499 MatchSource::Normal => format!("match {} {{ .. }}", expr),
500 MatchSource::IfLetDesugar { .. } => format!("if let .. = {} {{ .. }}", expr),
501 MatchSource::WhileLetDesugar => format!("while let .. = {} {{ .. }}", expr),
502 MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
503 MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
507 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
510 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
511 enum Kind<'a, T: 'a> {
512 Start(T, &'a SpannedRange<T>),
513 End(Bound<T>, &'a SpannedRange<T>),
516 impl<'a, T: Copy> Kind<'a, T> {
517 fn range(&self) -> &'a SpannedRange<T> {
520 Kind::End(_, r) => r,
524 fn value(self) -> Bound<T> {
526 Kind::Start(t, _) => Bound::Included(t),
527 Kind::End(t, _) => t,
532 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
533 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
534 Some(self.cmp(other))
538 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
539 fn cmp(&self, other: &Self) -> Ordering {
540 match (self.value(), other.value()) {
541 (Bound::Included(a), Bound::Included(b)) |
542 (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
543 // Range patterns cannot be unbounded (yet)
544 (Bound::Unbounded, _) |
545 (_, Bound::Unbounded) => unimplemented!(),
546 (Bound::Included(a), Bound::Excluded(b)) => {
548 Ordering::Equal => Ordering::Greater,
552 (Bound::Excluded(a), Bound::Included(b)) => {
554 Ordering::Equal => Ordering::Less,
562 let mut values = Vec::with_capacity(2 * ranges.len());
565 values.push(Kind::Start(r.node.0, r));
566 values.push(Kind::End(r.node.1, r));
571 for (a, b) in values.iter().zip(values.iter().skip(1)) {
573 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
574 if ra.node != rb.node {
575 return Some((ra, rb));
578 (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
579 _ => return Some((a.range(), b.range())),