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