]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Auto merge of #3814 - ljedrz:HirIdification_lockstep_upgrade, r=phansch
[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.hir_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         if suggestion.is_empty() {
541             return;
542         }
543
544         span_lint_and_sugg(
545             cx,
546             WILDCARD_ENUM_MATCH_ARM,
547             wildcard_span,
548             "wildcard match will miss any future added variants.",
549             "try this",
550             suggestion.join(" | "),
551             Applicability::MachineApplicable,
552         )
553     }
554 }
555
556 // If the block contains only a `panic!` macro (as expression or statement)
557 fn is_panic_block(block: &Block) -> bool {
558     match (&block.expr, block.stmts.len(), block.stmts.first()) {
559         (&Some(ref exp), 0, _) => {
560             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
561         },
562         (&None, 1, Some(stmt)) => {
563             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
564         },
565         _ => false,
566     }
567 }
568
569 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
570     if has_only_ref_pats(arms) {
571         let mut suggs = Vec::new();
572         let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
573             let span = ex.span.source_callsite();
574             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
575             (
576                 "you don't need to add `&` to both the expression and the patterns",
577                 "try",
578             )
579         } else {
580             let span = ex.span.source_callsite();
581             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
582             (
583                 "you don't need to add `&` to all patterns",
584                 "instead of prefixing all patterns with `&`, you can dereference the expression",
585             )
586         };
587
588         suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
589             if let PatKind::Ref(ref refp, _) = p.node {
590                 Some((p.span, snippet(cx, refp.span, "..").to_string()))
591             } else {
592                 None
593             }
594         }));
595
596         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
597             if !in_macro(expr.span) {
598                 multispan_sugg(db, msg.to_owned(), suggs);
599             }
600         });
601     }
602 }
603
604 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
605     if arms.len() == 2
606         && arms[0].pats.len() == 1
607         && arms[0].guard.is_none()
608         && arms[1].pats.len() == 1
609         && arms[1].guard.is_none()
610     {
611         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
612             is_ref_some_arm(&arms[1])
613         } else if is_none_arm(&arms[1]) {
614             is_ref_some_arm(&arms[0])
615         } else {
616             None
617         };
618         if let Some(rb) = arm_ref {
619             let suggestion = if rb == BindingAnnotation::Ref {
620                 "as_ref"
621             } else {
622                 "as_mut"
623             };
624             let mut applicability = Applicability::MachineApplicable;
625             span_lint_and_sugg(
626                 cx,
627                 MATCH_AS_REF,
628                 expr.span,
629                 &format!("use {}() instead", suggestion),
630                 "try this",
631                 format!(
632                     "{}.{}()",
633                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
634                     suggestion
635                 ),
636                 applicability,
637             )
638         }
639     }
640 }
641
642 /// Get all arms that are unbounded `PatRange`s.
643 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
644     arms.iter()
645         .flat_map(|arm| {
646             if let Arm {
647                 ref pats, guard: None, ..
648             } = *arm
649             {
650                 pats.iter()
651             } else {
652                 [].iter()
653             }
654             .filter_map(|pat| {
655                 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
656                     let lhs = constant(cx, cx.tables, lhs)?.0;
657                     let rhs = constant(cx, cx.tables, rhs)?.0;
658                     let rhs = match *range_end {
659                         RangeEnd::Included => Bound::Included(rhs),
660                         RangeEnd::Excluded => Bound::Excluded(rhs),
661                     };
662                     return Some(SpannedRange {
663                         span: pat.span,
664                         node: (lhs, rhs),
665                     });
666                 }
667
668                 if let PatKind::Lit(ref value) = pat.node {
669                     let value = constant(cx, cx.tables, value)?.0;
670                     return Some(SpannedRange {
671                         span: pat.span,
672                         node: (value.clone(), Bound::Included(value)),
673                     });
674                 }
675
676                 None
677             })
678         })
679         .collect()
680 }
681
682 #[derive(Debug, Eq, PartialEq)]
683 pub struct SpannedRange<T> {
684     pub span: Span,
685     pub node: (T, Bound<T>),
686 }
687
688 type TypedRanges = Vec<SpannedRange<u128>>;
689
690 /// Get all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
691 /// and other types than
692 /// `Uint` and `Int` probably don't make sense.
693 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
694     ranges
695         .iter()
696         .filter_map(|range| match range.node {
697             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
698                 span: range.span,
699                 node: (start, Bound::Included(end)),
700             }),
701             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
702                 span: range.span,
703                 node: (start, Bound::Excluded(end)),
704             }),
705             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
706                 span: range.span,
707                 node: (start, Bound::Unbounded),
708             }),
709             _ => None,
710         })
711         .collect()
712 }
713
714 fn is_unit_expr(expr: &Expr) -> bool {
715     match expr.node {
716         ExprKind::Tup(ref v) if v.is_empty() => true,
717         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
718         _ => false,
719     }
720 }
721
722 // Checks if arm has the form `None => None`
723 fn is_none_arm(arm: &Arm) -> bool {
724     match arm.pats[0].node {
725         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
726         _ => false,
727     }
728 }
729
730 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
731 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
732     if_chain! {
733         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
734         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
735         if let PatKind::Binding(rb, .., ident, _) = pats[0].node;
736         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
737         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
738         if let ExprKind::Path(ref some_path) = e.node;
739         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
740         if let ExprKind::Path(ref qpath) = args[0].node;
741         if let &QPath::Resolved(_, ref path2) = qpath;
742         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
743         then {
744             return Some(rb)
745         }
746     }
747     None
748 }
749
750 fn has_only_ref_pats(arms: &[Arm]) -> bool {
751     let mapped = arms
752         .iter()
753         .flat_map(|a| &a.pats)
754         .map(|p| {
755             match p.node {
756                 PatKind::Ref(..) => Some(true), // &-patterns
757                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
758                 _ => None,                      // any other pattern is not fine
759             }
760         })
761         .collect::<Option<Vec<bool>>>();
762     // look for Some(v) where there's at least one true element
763     mapped.map_or(false, |v| v.iter().any(|el| *el))
764 }
765
766 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
767 where
768     T: Copy + Ord,
769 {
770     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
771     enum Kind<'a, T: 'a> {
772         Start(T, &'a SpannedRange<T>),
773         End(Bound<T>, &'a SpannedRange<T>),
774     }
775
776     impl<'a, T: Copy> Kind<'a, T> {
777         fn range(&self) -> &'a SpannedRange<T> {
778             match *self {
779                 Kind::Start(_, r) | Kind::End(_, r) => r,
780             }
781         }
782
783         fn value(self) -> Bound<T> {
784             match self {
785                 Kind::Start(t, _) => Bound::Included(t),
786                 Kind::End(t, _) => t,
787             }
788         }
789     }
790
791     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
792         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
793             Some(self.cmp(other))
794         }
795     }
796
797     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
798         fn cmp(&self, other: &Self) -> Ordering {
799             match (self.value(), other.value()) {
800                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
801                 // Range patterns cannot be unbounded (yet)
802                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
803                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
804                     Ordering::Equal => Ordering::Greater,
805                     other => other,
806                 },
807                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
808                     Ordering::Equal => Ordering::Less,
809                     other => other,
810                 },
811             }
812         }
813     }
814
815     let mut values = Vec::with_capacity(2 * ranges.len());
816
817     for r in ranges {
818         values.push(Kind::Start(r.node.0, r));
819         values.push(Kind::End(r.node.1, r));
820     }
821
822     values.sort();
823
824     for (a, b) in values.iter().zip(values.iter().skip(1)) {
825         match (a, b) {
826             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
827                 if ra.node != rb.node {
828                     return Some((ra, rb));
829                 }
830             },
831             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
832             _ => return Some((a.range(), b.range())),
833         }
834     }
835
836     None
837 }