3 use rustc::middle::const_val::ConstVal;
5 use rustc_const_eval::EvalHint::ExprTypeChecked;
6 use rustc_const_eval::eval_const_expr_partial;
7 use rustc_const_math::ConstInt;
8 use std::cmp::Ordering;
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};
14 /// **What it does:** This lint checks for matches with a single arm where an `if let` will usually suffice.
16 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
18 /// **Known problems:** None
23 /// Some(ref foo) -> bar(foo),
28 pub SINGLE_MATCH, Warn,
29 "a match statement with a single nontrivial arm (i.e, where the other arm \
30 is `_ => {}`) is used; recommends `if let` instead"
33 /// **What it does:** This lint checks for matches with a two arms where an `if let` will usually suffice.
35 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
37 /// **Known problems:** Personal style preferences may differ
42 /// Some(ref foo) -> bar(foo),
43 /// _ => bar(other_ref),
47 pub SINGLE_MATCH_ELSE, Allow,
48 "a match statement with a two arms where the second arm's pattern is a wildcard; \
49 recommends `if let` instead"
52 /// **What it does:** This lint checks for matches where all arms match a reference, suggesting to remove the reference and deref the matched expression instead. It also checks for `if let &foo = bar` blocks.
54 /// **Why is this bad?** It just makes the code less readable. That reference destructuring adds nothing to the code.
56 /// **Known problems:** None
62 /// &A(ref y) => foo(y),
68 pub MATCH_REF_PATS, Warn,
69 "a match or `if let` has all arms prefixed with `&`; the match expression can be \
73 /// **What it does:** This lint checks for matches where match expression is a `bool`. It suggests to replace the expression with an `if...else` block.
75 /// **Why is this bad?** It makes the code less readable.
77 /// **Known problems:** None
82 /// let condition: bool = true;
90 "a match on boolean expression; recommends `if..else` block instead"
93 /// **What it does:** This lint checks for overlapping match arms.
95 /// **Why is this bad?** It is likely to be an error and if not, makes the code less obvious.
97 /// **Known problems:** None
104 /// 1 ... 10 => println!("1 ... 10"),
105 /// 5 ... 15 => println!("5 ... 15"),
110 pub MATCH_OVERLAPPING_ARM, Warn, "a match has overlapping arms"
113 #[allow(missing_copy_implementations)]
114 pub struct MatchPass;
116 impl LintPass for MatchPass {
117 fn get_lints(&self) -> LintArray {
118 lint_array!(SINGLE_MATCH, MATCH_REF_PATS, MATCH_BOOL, SINGLE_MATCH_ELSE)
122 impl LateLintPass for MatchPass {
123 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
124 if in_external_macro(cx, expr.span) {
127 if let ExprMatch(ref ex, ref arms, MatchSource::Normal) = expr.node {
128 check_single_match(cx, ex, arms, expr);
129 check_match_bool(cx, ex, arms, expr);
130 check_overlapping_arms(cx, ex, arms);
132 if let ExprMatch(ref ex, ref arms, source) = expr.node {
133 check_match_ref_pats(cx, ex, arms, source, expr);
138 #[cfg_attr(rustfmt, rustfmt_skip)]
139 fn check_single_match(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
140 if arms.len() == 2 &&
141 arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
142 arms[1].pats.len() == 1 && arms[1].guard.is_none() {
143 let els = if is_unit_expr(&arms[1].body) {
145 } else if let ExprBlock(_) = arms[1].body.node {
146 // matches with blocks that contain statements are prettier as `if let + else`
149 // allow match arms with just expressions
152 let ty = cx.tcx.expr_ty(ex);
153 if ty.sty != ty::TyBool || cx.current_level(MATCH_BOOL) == Allow {
154 check_single_match_single_pattern(cx, ex, arms, expr, els);
155 check_single_match_opt_like(cx, ex, arms, expr, ty, els);
160 fn check_single_match_single_pattern(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, els: Option<&Expr>) {
161 if arms[1].pats[0].node == PatKind::Wild {
162 let lint = if els.is_some() {
167 let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
168 span_lint_and_then(cx,
171 "you seem to be trying to use match for destructuring a single pattern. \
172 Consider using `if let`",
174 db.span_suggestion(expr.span,
176 format!("if let {} = {} {}{}",
177 snippet(cx, arms[0].pats[0].span, ".."),
178 snippet(cx, ex.span, ".."),
179 expr_block(cx, &arms[0].body, None, ".."),
185 fn check_single_match_opt_like(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr, ty: ty::Ty, els: Option<&Expr>) {
186 // list of candidate Enums we know will never get any more members
187 let candidates = &[(&paths::COW, "Borrowed"),
188 (&paths::COW, "Cow::Borrowed"),
189 (&paths::COW, "Cow::Owned"),
190 (&paths::COW, "Owned"),
191 (&paths::OPTION, "None"),
192 (&paths::RESULT, "Err"),
193 (&paths::RESULT, "Ok")];
195 let path = match arms[1].pats[0].node {
196 PatKind::TupleStruct(ref path, Some(ref inner)) => {
197 // contains any non wildcard patterns? e.g. Err(err)
198 if inner.iter().any(|pat| pat.node != PatKind::Wild) {
203 PatKind::TupleStruct(ref path, None) => path.to_string(),
204 PatKind::Ident(BindByValue(MutImmutable), ident, None) => ident.node.to_string(),
208 for &(ty_path, pat_path) in candidates {
209 if &path == pat_path && match_type(cx, ty, ty_path) {
210 let lint = if els.is_some() {
215 let els_str = els.map_or(String::new(), |els| format!(" else {}", expr_block(cx, els, None, "..")));
216 span_lint_and_then(cx,
219 "you seem to be trying to use match for destructuring a single pattern. Consider \
222 db.span_suggestion(expr.span,
224 format!("if let {} = {} {}{}",
225 snippet(cx, arms[0].pats[0].span, ".."),
226 snippet(cx, ex.span, ".."),
227 expr_block(cx, &arms[0].body, None, ".."),
234 fn check_match_bool(cx: &LateContext, ex: &Expr, arms: &[Arm], expr: &Expr) {
235 // type of expression == bool
236 if cx.tcx.expr_ty(ex).sty == ty::TyBool {
237 let sugg = if arms.len() == 2 && arms[0].pats.len() == 1 {
239 let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
240 if let ExprLit(ref lit) = arm_bool.node {
242 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
243 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
253 if let Some((ref true_expr, ref false_expr)) = exprs {
254 match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
256 Some(format!("if {} {} else {}",
257 snippet(cx, ex.span, "b"),
258 expr_block(cx, true_expr, None, ".."),
259 expr_block(cx, false_expr, None, "..")))
262 Some(format!("if {} {}", snippet(cx, ex.span, "b"), expr_block(cx, true_expr, None, "..")))
265 Some(format!("try\nif !{} {}",
266 snippet(cx, ex.span, "b"),
267 expr_block(cx, false_expr, None, "..")))
269 (true, true) => None,
278 span_lint_and_then(cx,
281 "you seem to be trying to match on a boolean expression. Consider using an if..else block:",
283 if let Some(sugg) = sugg {
284 db.span_suggestion(expr.span, "try this", sugg);
290 fn check_overlapping_arms(cx: &LateContext, ex: &Expr, arms: &[Arm]) {
291 if arms.len() >= 2 && cx.tcx.expr_ty(ex).is_integral() {
292 let ranges = all_ranges(cx, arms);
293 let type_ranges = type_ranges(&ranges);
294 if !type_ranges.is_empty() {
295 if let Some((start, end)) = overlapping(&type_ranges) {
296 span_note_and_lint(cx,
297 MATCH_OVERLAPPING_ARM,
299 "some ranges overlap",
301 "overlaps with this");
307 fn check_match_ref_pats(cx: &LateContext, ex: &Expr, arms: &[Arm], source: MatchSource, expr: &Expr) {
308 if has_only_ref_pats(arms) {
309 if let ExprAddrOf(Mutability::MutImmutable, ref inner) = ex.node {
310 let template = match_template(cx, expr.span, source, "", inner);
311 span_lint_and_then(cx,
314 "you don't need to add `&` to both the expression and the patterns",
316 db.span_suggestion(expr.span, "try", template);
319 let template = match_template(cx, expr.span, source, "*", ex);
320 span_lint_and_then(cx,
323 "you don't need to add `&` to all patterns",
325 db.span_suggestion(expr.span,
326 "instead of prefixing all patterns with `&`, you can \
327 dereference the expression",
334 /// Get all arms that are unbounded `PatRange`s.
335 fn all_ranges(cx: &LateContext, arms: &[Arm]) -> Vec<SpannedRange<ConstVal>> {
338 if let Arm { ref pats, guard: None, .. } = *arm {
339 Some(pats.iter().filter_map(|pat| {
341 let PatKind::Range(ref lhs, ref rhs) = pat.node,
342 let Ok(lhs) = eval_const_expr_partial(cx.tcx, &lhs, ExprTypeChecked, None),
343 let Ok(rhs) = eval_const_expr_partial(cx.tcx, &rhs, ExprTypeChecked, None)
345 return Some(SpannedRange { span: pat.span, node: (lhs, rhs) });
349 let PatKind::Lit(ref value) = pat.node,
350 let Ok(value) = eval_const_expr_partial(cx.tcx, &value, ExprTypeChecked, None)
352 return Some(SpannedRange { span: pat.span, node: (value.clone(), value) });
361 .flat_map(IntoIterator::into_iter)
365 #[derive(Debug, Eq, PartialEq)]
366 pub struct SpannedRange<T> {
371 type TypedRanges = Vec<SpannedRange<ConstInt>>;
373 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway and other types than
374 /// `Uint` and `Int` probably don't make sense.
375 fn type_ranges(ranges: &[SpannedRange<ConstVal>]) -> TypedRanges {
377 .filter_map(|range| {
378 if let (ConstVal::Integral(start), ConstVal::Integral(end)) = range.node {
390 fn is_unit_expr(expr: &Expr) -> bool {
392 ExprTup(ref v) if v.is_empty() => true,
393 ExprBlock(ref b) if b.stmts.is_empty() && b.expr.is_none() => true,
398 fn has_only_ref_pats(arms: &[Arm]) -> bool {
399 let mapped = arms.iter()
400 .flat_map(|a| &a.pats)
403 PatKind::Ref(..) => Some(true), // &-patterns
404 PatKind::Wild => Some(false), // an "anything" wildcard is also fine
405 _ => None, // any other pattern is not fine
408 .collect::<Option<Vec<bool>>>();
409 // look for Some(v) where there's at least one true element
410 mapped.map_or(false, |v| v.iter().any(|el| *el))
413 fn match_template(cx: &LateContext, span: Span, source: MatchSource, op: &str, expr: &Expr) -> String {
414 let expr_snippet = snippet(cx, expr.span, "..");
416 MatchSource::Normal => format!("match {}{} {{ .. }}", op, expr_snippet),
417 MatchSource::IfLetDesugar { .. } => format!("if let .. = {}{} {{ .. }}", op, expr_snippet),
418 MatchSource::WhileLetDesugar => format!("while let .. = {}{} {{ .. }}", op, expr_snippet),
419 MatchSource::ForLoopDesugar => span_bug!(span, "for loop desugared to match with &-patterns!"),
420 MatchSource::TryDesugar => span_bug!(span, "`?` operator desugared to match with &-patterns!"),
424 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
427 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
428 enum Kind<'a, T: 'a> {
429 Start(T, &'a SpannedRange<T>),
430 End(T, &'a SpannedRange<T>),
433 impl<'a, T: Copy> Kind<'a, T> {
434 fn range(&self) -> &'a SpannedRange<T> {
437 Kind::End(_, r) => r,
441 fn value(self) -> T {
444 Kind::End(t, _) => t,
449 impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
450 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
451 Some(self.cmp(other))
455 impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
456 fn cmp(&self, other: &Self) -> Ordering {
457 self.value().cmp(&other.value())
461 let mut values = Vec::with_capacity(2 * ranges.len());
464 values.push(Kind::Start(r.node.0, &r));
465 values.push(Kind::End(r.node.1, &r));
470 for (a, b) in values.iter().zip(values.iter().skip(1)) {
472 (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
473 if ra.node != rb.node {
474 return Some((ra, rb));
477 (&Kind::End(a, _), &Kind::Start(b, _)) if a != b => (),
478 _ => return Some((&a.range(), &b.range())),