]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
wildcard_enum_match_arm gives suggestions
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::{
5     expr_block, in_macro, is_allowed, is_expn_of, match_qpath, match_type, multispan_sugg, remove_blocks, snippet,
6     snippet_with_applicability, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty,
7 };
8 use if_chain::if_chain;
9 use rustc::hir::def::CtorKind;
10 use rustc::hir::*;
11 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
12 use rustc::ty::{self, Ty, TyKind};
13 use rustc::{declare_tool_lint, lint_array};
14 use rustc_errors::Applicability;
15 use std::cmp::Ordering;
16 use std::collections::Bound;
17 use std::ops::Deref;
18 use syntax::ast::LitKind;
19 use syntax::source_map::Span;
20
21 /// **What it does:** Checks for matches with a single arm where an `if let`
22 /// will usually suffice.
23 ///
24 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
25 ///
26 /// **Known problems:** None.
27 ///
28 /// **Example:**
29 /// ```rust
30 /// match x {
31 ///     Some(ref foo) => bar(foo),
32 ///     _ => (),
33 /// }
34 /// ```
35 declare_clippy_lint! {
36     pub SINGLE_MATCH,
37     style,
38     "a match statement with a single nontrivial arm (i.e. where the other arm is `_ => {}`) instead of `if let`"
39 }
40
41 /// **What it does:** Checks for matches with a two arms where an `if let else` will
42 /// usually suffice.
43 ///
44 /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
45 ///
46 /// **Known problems:** Personal style preferences may differ.
47 ///
48 /// **Example:**
49 ///
50 /// Using `match`:
51 ///
52 /// ```rust
53 /// match x {
54 ///     Some(ref foo) => bar(foo),
55 ///     _ => bar(other_ref),
56 /// }
57 /// ```
58 ///
59 /// Using `if let` with `else`:
60 ///
61 /// ```rust
62 /// if let Some(ref foo) = x {
63 ///     bar(foo);
64 /// } else {
65 ///     bar(other_ref);
66 /// }
67 /// ```
68 declare_clippy_lint! {
69     pub SINGLE_MATCH_ELSE,
70     pedantic,
71     "a match statement with a two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
72 }
73
74 /// **What it does:** Checks for matches where all arms match a reference,
75 /// suggesting to remove the reference and deref the matched expression
76 /// instead. It also checks for `if let &foo = bar` blocks.
77 ///
78 /// **Why is this bad?** It just makes the code less readable. That reference
79 /// destructuring adds nothing to the code.
80 ///
81 /// **Known problems:** None.
82 ///
83 /// **Example:**
84 /// ```rust
85 /// match x {
86 ///     &A(ref y) => foo(y),
87 ///     &B => bar(),
88 ///     _ => frob(&x),
89 /// }
90 /// ```
91 declare_clippy_lint! {
92     pub MATCH_REF_PATS,
93     style,
94     "a match or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
95 }
96
97 /// **What it does:** Checks for matches where match expression is a `bool`. It
98 /// suggests to replace the expression with an `if...else` block.
99 ///
100 /// **Why is this bad?** It makes the code less readable.
101 ///
102 /// **Known problems:** None.
103 ///
104 /// **Example:**
105 /// ```rust
106 /// let condition: bool = true;
107 /// match condition {
108 ///     true => foo(),
109 ///     false => bar(),
110 /// }
111 /// ```
112 /// Use if/else instead:
113 /// ```rust
114 /// let condition: bool = true;
115 /// if condition {
116 ///     foo();
117 /// } else {
118 ///     bar();
119 /// }
120 /// ```
121 declare_clippy_lint! {
122     pub MATCH_BOOL,
123     style,
124     "a match on a boolean expression instead of an `if..else` block"
125 }
126
127 /// **What it does:** Checks for overlapping match arms.
128 ///
129 /// **Why is this bad?** It is likely to be an error and if not, makes the code
130 /// less obvious.
131 ///
132 /// **Known problems:** None.
133 ///
134 /// **Example:**
135 /// ```rust
136 /// let x = 5;
137 /// match x {
138 ///     1...10 => println!("1 ... 10"),
139 ///     5...15 => println!("5 ... 15"),
140 ///     _ => (),
141 /// }
142 /// ```
143 declare_clippy_lint! {
144     pub MATCH_OVERLAPPING_ARM,
145     style,
146     "a match with overlapping arms"
147 }
148
149 /// **What it does:** Checks for arm which matches all errors with `Err(_)`
150 /// and take drastic actions like `panic!`.
151 ///
152 /// **Why is this bad?** It is generally a bad practice, just like
153 /// catching all exceptions in java with `catch(Exception)`
154 ///
155 /// **Known problems:** None.
156 ///
157 /// **Example:**
158 /// ```rust
159 /// let x: Result(i32, &str) = Ok(3);
160 /// match x {
161 ///     Ok(_) => println!("ok"),
162 ///     Err(_) => panic!("err"),
163 /// }
164 /// ```
165 declare_clippy_lint! {
166     pub MATCH_WILD_ERR_ARM,
167     style,
168     "a match with `Err(_)` arm and take drastic actions"
169 }
170
171 /// **What it does:** Checks for match which is used to add a reference to an
172 /// `Option` value.
173 ///
174 /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
175 ///
176 /// **Known problems:** None.
177 ///
178 /// **Example:**
179 /// ```rust
180 /// let x: Option<()> = None;
181 /// let r: Option<&()> = match x {
182 ///     None => None,
183 ///     Some(ref v) => Some(v),
184 /// };
185 /// ```
186 declare_clippy_lint! {
187     pub MATCH_AS_REF,
188     complexity,
189     "a match on an Option value instead of using `as_ref()` or `as_mut`"
190 }
191
192 /// **What it does:** Checks for wildcard enum matches using `_`.
193 ///
194 /// **Why is this bad?** New enum variants added by library updates can be missed.
195 ///
196 /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
197 /// variants, and also may not use correct path to enum if it's not present in the current scope.
198 ///
199 /// **Example:**
200 /// ```rust
201 /// match x {
202 ///     A => {},
203 ///     _ => {},
204 /// }
205 /// ```
206 declare_clippy_lint! {
207     pub WILDCARD_ENUM_MATCH_ARM,
208     restriction,
209     "a wildcard enum match arm using `_`"
210 }
211
212 #[allow(missing_copy_implementations)]
213 pub struct MatchPass;
214
215 impl LintPass for MatchPass {
216     fn get_lints(&self) -> LintArray {
217         lint_array!(
218             SINGLE_MATCH,
219             MATCH_REF_PATS,
220             MATCH_BOOL,
221             SINGLE_MATCH_ELSE,
222             MATCH_OVERLAPPING_ARM,
223             MATCH_WILD_ERR_ARM,
224             MATCH_AS_REF,
225             WILDCARD_ENUM_MATCH_ARM
226         )
227     }
228
229     fn name(&self) -> &'static str {
230         "Matches"
231     }
232 }
233
234 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchPass {
235     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
236         if in_external_macro(cx.sess(), expr.span) {
237             return;
238         }
239         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
240             check_single_match(cx, ex, arms, expr);
241             check_match_bool(cx, ex, arms, expr);
242             check_overlapping_arms(cx, ex, arms);
243             check_wild_err_arm(cx, ex, arms);
244             check_wild_enum_match(cx, ex, arms);
245             check_match_as_ref(cx, ex, arms, expr);
246         }
247         if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
248             check_match_ref_pats(cx, ex, arms, expr);
249         }
250     }
251 }
252
253 #[rustfmt::skip]
254 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
255     if arms.len() == 2 &&
256       arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
257       arms[1].pats.len() == 1 && arms[1].guard.is_none() {
258         let els = remove_blocks(&arms[1].body);
259         let els = if is_unit_expr(els) {
260             None
261         } else if let ExprKind::Block(_, _) = els.node {
262             // matches with blocks that contain statements are prettier as `if let + else`
263             Some(els)
264         } else {
265             // allow match arms with just expressions
266             return;
267         };
268         let ty = cx.tables.expr_ty(ex);
269         if ty.sty != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.id) {
270             check_single_match_single_pattern(cx, ex, arms, expr, els);
271             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
272         }
273     }
274 }
275
276 fn check_single_match_single_pattern(
277     cx: &LateContext<'_, '_>,
278     ex: &Expr,
279     arms: &[Arm],
280     expr: &Expr,
281     els: Option<&Expr>,
282 ) {
283     if is_wild(&arms[1].pats[0]) {
284         report_single_match_single_pattern(cx, ex, arms, expr, els);
285     }
286 }
287
288 fn report_single_match_single_pattern(
289     cx: &LateContext<'_, '_>,
290     ex: &Expr,
291     arms: &[Arm],
292     expr: &Expr,
293     els: Option<&Expr>,
294 ) {
295     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
296     let els_str = els.map_or(String::new(), |els| {
297         format!(" else {}", expr_block(cx, els, None, ".."))
298     });
299     span_lint_and_sugg(
300         cx,
301         lint,
302         expr.span,
303         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
304          let`",
305         "try this",
306         format!(
307             "if let {} = {} {}{}",
308             snippet(cx, arms[0].pats[0].span, ".."),
309             snippet(cx, ex.span, ".."),
310             expr_block(cx, &arms[0].body, None, ".."),
311             els_str,
312         ),
313         Applicability::HasPlaceholders,
314     );
315 }
316
317 fn check_single_match_opt_like(
318     cx: &LateContext<'_, '_>,
319     ex: &Expr,
320     arms: &[Arm],
321     expr: &Expr,
322     ty: Ty<'_>,
323     els: Option<&Expr>,
324 ) {
325     // list of candidate Enums we know will never get any more members
326     let candidates = &[
327         (&paths::COW, "Borrowed"),
328         (&paths::COW, "Cow::Borrowed"),
329         (&paths::COW, "Cow::Owned"),
330         (&paths::COW, "Owned"),
331         (&paths::OPTION, "None"),
332         (&paths::RESULT, "Err"),
333         (&paths::RESULT, "Ok"),
334     ];
335
336     let path = match arms[1].pats[0].node {
337         PatKind::TupleStruct(ref path, ref inner, _) => {
338             // contains any non wildcard patterns? e.g. Err(err)
339             if !inner.iter().all(is_wild) {
340                 return;
341             }
342             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
343         },
344         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
345         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
346         _ => return,
347     };
348
349     for &(ty_path, pat_path) in candidates {
350         if path == *pat_path && match_type(cx, ty, ty_path) {
351             report_single_match_single_pattern(cx, ex, arms, expr, els);
352         }
353     }
354 }
355
356 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
357     // type of expression == bool
358     if cx.tables.expr_ty(ex).sty == ty::Bool {
359         span_lint_and_then(
360             cx,
361             MATCH_BOOL,
362             expr.span,
363             "you seem to be trying to match on a boolean expression",
364             move |db| {
365                 if arms.len() == 2 && arms[0].pats.len() == 1 {
366                     // no guards
367                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
368                         if let ExprKind::Lit(ref lit) = arm_bool.node {
369                             match lit.node {
370                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
371                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
372                                 _ => None,
373                             }
374                         } else {
375                             None
376                         }
377                     } else {
378                         None
379                     };
380
381                     if let Some((true_expr, false_expr)) = exprs {
382                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
383                             (false, false) => Some(format!(
384                                 "if {} {} else {}",
385                                 snippet(cx, ex.span, "b"),
386                                 expr_block(cx, true_expr, None, ".."),
387                                 expr_block(cx, false_expr, None, "..")
388                             )),
389                             (false, true) => Some(format!(
390                                 "if {} {}",
391                                 snippet(cx, ex.span, "b"),
392                                 expr_block(cx, true_expr, None, "..")
393                             )),
394                             (true, false) => {
395                                 let test = Sugg::hir(cx, ex, "..");
396                                 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
397                             },
398                             (true, true) => None,
399                         };
400
401                         if let Some(sugg) = sugg {
402                             db.span_suggestion(
403                                 expr.span,
404                                 "consider using an if/else expression",
405                                 sugg,
406                                 Applicability::HasPlaceholders,
407                             );
408                         }
409                     }
410                 }
411             },
412         );
413     }
414 }
415
416 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
417     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
418         let ranges = all_ranges(cx, arms);
419         let type_ranges = type_ranges(&ranges);
420         if !type_ranges.is_empty() {
421             if let Some((start, end)) = overlapping(&type_ranges) {
422                 span_note_and_lint(
423                     cx,
424                     MATCH_OVERLAPPING_ARM,
425                     start.span,
426                     "some ranges overlap",
427                     end.span,
428                     "overlaps with this",
429                 );
430             }
431         }
432     }
433 }
434
435 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
436     match pat.node {
437         PatKind::Wild => true,
438         _ => false,
439     }
440 }
441
442 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
443     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
444     if match_type(cx, ex_ty, &paths::RESULT) {
445         for arm in arms {
446             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
447                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
448                 if_chain! {
449                     if path_str == "Err";
450                     if inner.iter().any(is_wild);
451                     if let ExprKind::Block(ref block, _) = arm.body.node;
452                     if is_panic_block(block);
453                     then {
454                         // `Err(_)` arm with `panic!` found
455                         span_note_and_lint(cx,
456                                            MATCH_WILD_ERR_ARM,
457                                            arm.pats[0].span,
458                                            "Err(_) will match all errors, maybe not a good idea",
459                                            arm.pats[0].span,
460                                            "to remove this warning, match each error separately \
461                                             or use unreachable macro");
462                     }
463                 }
464             }
465         }
466     }
467 }
468
469 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
470     let ty = cx.tables.expr_ty(ex);
471     if !ty.is_enum() {
472         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
473         // don't complain about not enumerating the mall.
474         return;
475     }
476
477     // First pass - check for violation, but don't do much book-keeping because this is hopefully
478     // the uncommon case, and the book-keeping is slightly expensive.
479     let mut wildcard_span = None;
480     let mut wildcard_ident = None;
481     for arm in arms {
482         for pat in &arm.pats {
483             if let PatKind::Wild = pat.node {
484                 wildcard_span = Some(pat.span);
485             } else if let PatKind::Binding(_, _, ident, None) = pat.node {
486                 wildcard_span = Some(pat.span);
487                 wildcard_ident = Some(ident);
488             }
489         }
490     }
491
492     if let Some(wildcard_span) = wildcard_span {
493         // Accumulate the variants which should be put in place of the wildcard because they're not
494         // already covered.
495
496         let mut missing_variants = vec![];
497         if let TyKind::Adt(def, _) = ty.sty {
498             for variant in &def.variants {
499                 missing_variants.push(variant);
500             }
501         }
502
503         for arm in arms {
504             if arm.guard.is_some() {
505                 // Guards mean that this case probably isn't exhaustively covered. Technically
506                 // this is incorrect, as we should really check whether each variant is exhaustively
507                 // covered by the set of guards that cover it, but that's really hard to do.
508                 continue;
509             }
510             for pat in &arm.pats {
511                 if let PatKind::Path(ref path) = pat.deref().node {
512                     if let QPath::Resolved(_, p) = path {
513                         missing_variants.retain(|e| e.did != p.def.def_id());
514                     }
515                 } else if let PatKind::TupleStruct(ref path, ..) = pat.deref().node {
516                     if let QPath::Resolved(_, p) = path {
517                         missing_variants.retain(|e| e.did != p.def.def_id());
518                     }
519                 }
520             }
521         }
522
523         let suggestion: Vec<String> = missing_variants
524             .iter()
525             .map(|v| {
526                 let suffix = match v.ctor_kind {
527                     CtorKind::Fn => "(..)",
528                     CtorKind::Const | CtorKind::Fictive => "",
529                 };
530                 let ident_str = if let Some(ident) = wildcard_ident {
531                     format!("{} @ ", ident.name)
532                 } else {
533                     String::new()
534                 };
535                 // This path assumes that the enum type is imported into scope.
536                 format!("{}{}{}", ident_str, cx.tcx.item_path_str(v.did), suffix)
537             })
538             .collect();
539
540         span_lint_and_sugg(
541             cx,
542             WILDCARD_ENUM_MATCH_ARM,
543             wildcard_span,
544             "wildcard match will miss any future added variants.",
545             "try this",
546             suggestion.join(" | "),
547             Applicability::MachineApplicable,
548         )
549     }
550 }
551
552 // If the block contains only a `panic!` macro (as expression or statement)
553 fn is_panic_block(block: &Block) -> bool {
554     match (&block.expr, block.stmts.len(), block.stmts.first()) {
555         (&Some(ref exp), 0, _) => {
556             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
557         },
558         (&None, 1, Some(stmt)) => {
559             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
560         },
561         _ => false,
562     }
563 }
564
565 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
566     if has_only_ref_pats(arms) {
567         let mut suggs = Vec::new();
568         let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
569             suggs.push((ex.span, Sugg::hir(cx, inner, "..").to_string()));
570             (
571                 "you don't need to add `&` to both the expression and the patterns",
572                 "try",
573             )
574         } else {
575             suggs.push((ex.span, Sugg::hir(cx, ex, "..").deref().to_string()));
576             (
577                 "you don't need to add `&` to all patterns",
578                 "instead of prefixing all patterns with `&`, you can dereference the expression",
579             )
580         };
581
582         suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
583             if let PatKind::Ref(ref refp, _) = p.node {
584                 Some((p.span, snippet(cx, refp.span, "..").to_string()))
585             } else {
586                 None
587             }
588         }));
589
590         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
591             if !in_macro(expr.span) {
592                 multispan_sugg(db, msg.to_owned(), suggs);
593             }
594         });
595     }
596 }
597
598 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
599     if arms.len() == 2
600         && arms[0].pats.len() == 1
601         && arms[0].guard.is_none()
602         && arms[1].pats.len() == 1
603         && arms[1].guard.is_none()
604     {
605         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
606             is_ref_some_arm(&arms[1])
607         } else if is_none_arm(&arms[1]) {
608             is_ref_some_arm(&arms[0])
609         } else {
610             None
611         };
612         if let Some(rb) = arm_ref {
613             let suggestion = if rb == BindingAnnotation::Ref {
614                 "as_ref"
615             } else {
616                 "as_mut"
617             };
618             let mut applicability = Applicability::MachineApplicable;
619             span_lint_and_sugg(
620                 cx,
621                 MATCH_AS_REF,
622                 expr.span,
623                 &format!("use {}() instead", suggestion),
624                 "try this",
625                 format!(
626                     "{}.{}()",
627                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
628                     suggestion
629                 ),
630                 applicability,
631             )
632         }
633     }
634 }
635
636 /// Get all arms that are unbounded `PatRange`s.
637 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
638     arms.iter()
639         .flat_map(|arm| {
640             if let Arm {
641                 ref pats, guard: None, ..
642             } = *arm
643             {
644                 pats.iter()
645             } else {
646                 [].iter()
647             }
648             .filter_map(|pat| {
649                 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
650                     let lhs = constant(cx, cx.tables, lhs)?.0;
651                     let rhs = constant(cx, cx.tables, rhs)?.0;
652                     let rhs = match *range_end {
653                         RangeEnd::Included => Bound::Included(rhs),
654                         RangeEnd::Excluded => Bound::Excluded(rhs),
655                     };
656                     return Some(SpannedRange {
657                         span: pat.span,
658                         node: (lhs, rhs),
659                     });
660                 }
661
662                 if let PatKind::Lit(ref value) = pat.node {
663                     let value = constant(cx, cx.tables, value)?.0;
664                     return Some(SpannedRange {
665                         span: pat.span,
666                         node: (value.clone(), Bound::Included(value)),
667                     });
668                 }
669
670                 None
671             })
672         })
673         .collect()
674 }
675
676 #[derive(Debug, Eq, PartialEq)]
677 pub struct SpannedRange<T> {
678     pub span: Span,
679     pub node: (T, Bound<T>),
680 }
681
682 type TypedRanges = Vec<SpannedRange<u128>>;
683
684 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
685 /// and other types than
686 /// `Uint` and `Int` probably don't make sense.
687 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
688     ranges
689         .iter()
690         .filter_map(|range| match range.node {
691             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
692                 span: range.span,
693                 node: (start, Bound::Included(end)),
694             }),
695             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
696                 span: range.span,
697                 node: (start, Bound::Excluded(end)),
698             }),
699             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
700                 span: range.span,
701                 node: (start, Bound::Unbounded),
702             }),
703             _ => None,
704         })
705         .collect()
706 }
707
708 fn is_unit_expr(expr: &Expr) -> bool {
709     match expr.node {
710         ExprKind::Tup(ref v) if v.is_empty() => true,
711         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
712         _ => false,
713     }
714 }
715
716 // Checks if arm has the form `None => None`
717 fn is_none_arm(arm: &Arm) -> bool {
718     match arm.pats[0].node {
719         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
720         _ => false,
721     }
722 }
723
724 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
725 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
726     if_chain! {
727         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
728         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
729         if let PatKind::Binding(rb, .., ident, _) = pats[0].node;
730         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
731         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
732         if let ExprKind::Path(ref some_path) = e.node;
733         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
734         if let ExprKind::Path(ref qpath) = args[0].node;
735         if let &QPath::Resolved(_, ref path2) = qpath;
736         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
737         then {
738             return Some(rb)
739         }
740     }
741     None
742 }
743
744 fn has_only_ref_pats(arms: &[Arm]) -> bool {
745     let mapped = arms
746         .iter()
747         .flat_map(|a| &a.pats)
748         .map(|p| {
749             match p.node {
750                 PatKind::Ref(..) => Some(true), // &-patterns
751                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
752                 _ => None,                      // any other pattern is not fine
753             }
754         })
755         .collect::<Option<Vec<bool>>>();
756     // look for Some(v) where there's at least one true element
757     mapped.map_or(false, |v| v.iter().any(|el| *el))
758 }
759
760 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
761 where
762     T: Copy + Ord,
763 {
764     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
765     enum Kind<'a, T: 'a> {
766         Start(T, &'a SpannedRange<T>),
767         End(Bound<T>, &'a SpannedRange<T>),
768     }
769
770     impl<'a, T: Copy> Kind<'a, T> {
771         fn range(&self) -> &'a SpannedRange<T> {
772             match *self {
773                 Kind::Start(_, r) | Kind::End(_, r) => r,
774             }
775         }
776
777         fn value(self) -> Bound<T> {
778             match self {
779                 Kind::Start(t, _) => Bound::Included(t),
780                 Kind::End(t, _) => t,
781             }
782         }
783     }
784
785     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
786         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
787             Some(self.cmp(other))
788         }
789     }
790
791     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
792         fn cmp(&self, other: &Self) -> Ordering {
793             match (self.value(), other.value()) {
794                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
795                 // Range patterns cannot be unbounded (yet)
796                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
797                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
798                     Ordering::Equal => Ordering::Greater,
799                     other => other,
800                 },
801                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
802                     Ordering::Equal => Ordering::Less,
803                     other => other,
804                 },
805             }
806         }
807     }
808
809     let mut values = Vec::with_capacity(2 * ranges.len());
810
811     for r in ranges {
812         values.push(Kind::Start(r.node.0, r));
813         values.push(Kind::End(r.node.1, r));
814     }
815
816     values.sort();
817
818     for (a, b) in values.iter().zip(values.iter().skip(1)) {
819         match (a, b) {
820             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
821                 if ra.node != rb.node {
822                     return Some((ra, rb));
823                 }
824             },
825             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
826             _ => return Some((a.range(), b.range())),
827         }
828     }
829
830     None
831 }