]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Auto merge of #3984 - phansch:bytecount_sugg, 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};
13 use rustc::{declare_lint_pass, declare_tool_lint};
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 declare_lint_pass!(Matches => [
219     SINGLE_MATCH,
220     MATCH_REF_PATS,
221     MATCH_BOOL,
222     SINGLE_MATCH_ELSE,
223     MATCH_OVERLAPPING_ARM,
224     MATCH_WILD_ERR_ARM,
225     MATCH_AS_REF,
226     WILDCARD_ENUM_MATCH_ARM
227 ]);
228
229 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
230     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
231         if in_external_macro(cx.sess(), expr.span) {
232             return;
233         }
234         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.node {
235             check_single_match(cx, ex, arms, expr);
236             check_match_bool(cx, ex, arms, expr);
237             check_overlapping_arms(cx, ex, arms);
238             check_wild_err_arm(cx, ex, arms);
239             check_wild_enum_match(cx, ex, arms);
240             check_match_as_ref(cx, ex, arms, expr);
241         }
242         if let ExprKind::Match(ref ex, ref arms, _) = expr.node {
243             check_match_ref_pats(cx, ex, arms, expr);
244         }
245     }
246 }
247
248 #[rustfmt::skip]
249 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
250     if arms.len() == 2 &&
251       arms[0].pats.len() == 1 && arms[0].guard.is_none() &&
252       arms[1].pats.len() == 1 && arms[1].guard.is_none() {
253         let els = remove_blocks(&arms[1].body);
254         let els = if is_unit_expr(els) {
255             None
256         } else if let ExprKind::Block(_, _) = els.node {
257             // matches with blocks that contain statements are prettier as `if let + else`
258             Some(els)
259         } else {
260             // allow match arms with just expressions
261             return;
262         };
263         let ty = cx.tables.expr_ty(ex);
264         if ty.sty != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
265             check_single_match_single_pattern(cx, ex, arms, expr, els);
266             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
267         }
268     }
269 }
270
271 fn check_single_match_single_pattern(
272     cx: &LateContext<'_, '_>,
273     ex: &Expr,
274     arms: &[Arm],
275     expr: &Expr,
276     els: Option<&Expr>,
277 ) {
278     if is_wild(&arms[1].pats[0]) {
279         report_single_match_single_pattern(cx, ex, arms, expr, els);
280     }
281 }
282
283 fn report_single_match_single_pattern(
284     cx: &LateContext<'_, '_>,
285     ex: &Expr,
286     arms: &[Arm],
287     expr: &Expr,
288     els: Option<&Expr>,
289 ) {
290     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
291     let els_str = els.map_or(String::new(), |els| {
292         format!(" else {}", expr_block(cx, els, None, ".."))
293     });
294     span_lint_and_sugg(
295         cx,
296         lint,
297         expr.span,
298         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
299          let`",
300         "try this",
301         format!(
302             "if let {} = {} {}{}",
303             snippet(cx, arms[0].pats[0].span, ".."),
304             snippet(cx, ex.span, ".."),
305             expr_block(cx, &arms[0].body, None, ".."),
306             els_str,
307         ),
308         Applicability::HasPlaceholders,
309     );
310 }
311
312 fn check_single_match_opt_like(
313     cx: &LateContext<'_, '_>,
314     ex: &Expr,
315     arms: &[Arm],
316     expr: &Expr,
317     ty: Ty<'_>,
318     els: Option<&Expr>,
319 ) {
320     // list of candidate `Enum`s we know will never get any more members
321     let candidates = &[
322         (&paths::COW, "Borrowed"),
323         (&paths::COW, "Cow::Borrowed"),
324         (&paths::COW, "Cow::Owned"),
325         (&paths::COW, "Owned"),
326         (&paths::OPTION, "None"),
327         (&paths::RESULT, "Err"),
328         (&paths::RESULT, "Ok"),
329     ];
330
331     let path = match arms[1].pats[0].node {
332         PatKind::TupleStruct(ref path, ref inner, _) => {
333             // Contains any non wildcard patterns (e.g., `Err(err)`)?
334             if !inner.iter().all(is_wild) {
335                 return;
336             }
337             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
338         },
339         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
340         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
341         _ => return,
342     };
343
344     for &(ty_path, pat_path) in candidates {
345         if path == *pat_path && match_type(cx, ty, ty_path) {
346             report_single_match_single_pattern(cx, ex, arms, expr, els);
347         }
348     }
349 }
350
351 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
352     // Type of expression is `bool`.
353     if cx.tables.expr_ty(ex).sty == ty::Bool {
354         span_lint_and_then(
355             cx,
356             MATCH_BOOL,
357             expr.span,
358             "you seem to be trying to match on a boolean expression",
359             move |db| {
360                 if arms.len() == 2 && arms[0].pats.len() == 1 {
361                     // no guards
362                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pats[0].node {
363                         if let ExprKind::Lit(ref lit) = arm_bool.node {
364                             match lit.node {
365                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
366                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
367                                 _ => None,
368                             }
369                         } else {
370                             None
371                         }
372                     } else {
373                         None
374                     };
375
376                     if let Some((true_expr, false_expr)) = exprs {
377                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
378                             (false, false) => Some(format!(
379                                 "if {} {} else {}",
380                                 snippet(cx, ex.span, "b"),
381                                 expr_block(cx, true_expr, None, ".."),
382                                 expr_block(cx, false_expr, None, "..")
383                             )),
384                             (false, true) => Some(format!(
385                                 "if {} {}",
386                                 snippet(cx, ex.span, "b"),
387                                 expr_block(cx, true_expr, None, "..")
388                             )),
389                             (true, false) => {
390                                 let test = Sugg::hir(cx, ex, "..");
391                                 Some(format!("if {} {}", !test, expr_block(cx, false_expr, None, "..")))
392                             },
393                             (true, true) => None,
394                         };
395
396                         if let Some(sugg) = sugg {
397                             db.span_suggestion(
398                                 expr.span,
399                                 "consider using an if/else expression",
400                                 sugg,
401                                 Applicability::HasPlaceholders,
402                             );
403                         }
404                     }
405                 }
406             },
407         );
408     }
409 }
410
411 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr, arms: &'tcx [Arm]) {
412     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
413         let ranges = all_ranges(cx, arms);
414         let type_ranges = type_ranges(&ranges);
415         if !type_ranges.is_empty() {
416             if let Some((start, end)) = overlapping(&type_ranges) {
417                 span_note_and_lint(
418                     cx,
419                     MATCH_OVERLAPPING_ARM,
420                     start.span,
421                     "some ranges overlap",
422                     end.span,
423                     "overlaps with this",
424                 );
425             }
426         }
427     }
428 }
429
430 fn is_wild(pat: &impl std::ops::Deref<Target = Pat>) -> bool {
431     match pat.node {
432         PatKind::Wild => true,
433         _ => false,
434     }
435 }
436
437 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
438     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
439     if match_type(cx, ex_ty, &paths::RESULT) {
440         for arm in arms {
441             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pats[0].node {
442                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
443                 if_chain! {
444                     if path_str == "Err";
445                     if inner.iter().any(is_wild);
446                     if let ExprKind::Block(ref block, _) = arm.body.node;
447                     if is_panic_block(block);
448                     then {
449                         // `Err(_)` arm with `panic!` found
450                         span_note_and_lint(cx,
451                                            MATCH_WILD_ERR_ARM,
452                                            arm.pats[0].span,
453                                            "Err(_) will match all errors, maybe not a good idea",
454                                            arm.pats[0].span,
455                                            "to remove this warning, match each error separately \
456                                             or use unreachable macro");
457                     }
458                 }
459             }
460         }
461     }
462 }
463
464 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm]) {
465     let ty = cx.tables.expr_ty(ex);
466     if !ty.is_enum() {
467         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
468         // don't complain about not enumerating the mall.
469         return;
470     }
471
472     // First pass - check for violation, but don't do much book-keeping because this is hopefully
473     // the uncommon case, and the book-keeping is slightly expensive.
474     let mut wildcard_span = None;
475     let mut wildcard_ident = None;
476     for arm in arms {
477         for pat in &arm.pats {
478             if let PatKind::Wild = pat.node {
479                 wildcard_span = Some(pat.span);
480             } else if let PatKind::Binding(_, _, ident, None) = pat.node {
481                 wildcard_span = Some(pat.span);
482                 wildcard_ident = Some(ident);
483             }
484         }
485     }
486
487     if let Some(wildcard_span) = wildcard_span {
488         // Accumulate the variants which should be put in place of the wildcard because they're not
489         // already covered.
490
491         let mut missing_variants = vec![];
492         if let ty::Adt(def, _) = ty.sty {
493             for variant in &def.variants {
494                 missing_variants.push(variant);
495             }
496         }
497
498         for arm in arms {
499             if arm.guard.is_some() {
500                 // Guards mean that this case probably isn't exhaustively covered. Technically
501                 // this is incorrect, as we should really check whether each variant is exhaustively
502                 // covered by the set of guards that cover it, but that's really hard to do.
503                 continue;
504             }
505             for pat in &arm.pats {
506                 if let PatKind::Path(ref path) = pat.deref().node {
507                     if let QPath::Resolved(_, p) = path {
508                         missing_variants.retain(|e| e.ctor_def_id != Some(p.def.def_id()));
509                     }
510                 } else if let PatKind::TupleStruct(ref path, ..) = pat.deref().node {
511                     if let QPath::Resolved(_, p) = path {
512                         missing_variants.retain(|e| e.ctor_def_id != Some(p.def.def_id()));
513                     }
514                 }
515             }
516         }
517
518         let suggestion: Vec<String> = missing_variants
519             .iter()
520             .map(|v| {
521                 let suffix = match v.ctor_kind {
522                     CtorKind::Fn => "(..)",
523                     CtorKind::Const | CtorKind::Fictive => "",
524                 };
525                 let ident_str = if let Some(ident) = wildcard_ident {
526                     format!("{} @ ", ident.name)
527                 } else {
528                     String::new()
529                 };
530                 // This path assumes that the enum type is imported into scope.
531                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
532             })
533             .collect();
534
535         if suggestion.is_empty() {
536             return;
537         }
538
539         span_lint_and_sugg(
540             cx,
541             WILDCARD_ENUM_MATCH_ARM,
542             wildcard_span,
543             "wildcard match will miss any future added variants.",
544             "try this",
545             suggestion.join(" | "),
546             Applicability::MachineApplicable,
547         )
548     }
549 }
550
551 // If the block contains only a `panic!` macro (as expression or statement)
552 fn is_panic_block(block: &Block) -> bool {
553     match (&block.expr, block.stmts.len(), block.stmts.first()) {
554         (&Some(ref exp), 0, _) => {
555             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
556         },
557         (&None, 1, Some(stmt)) => {
558             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
559         },
560         _ => false,
561     }
562 }
563
564 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
565     if has_only_ref_pats(arms) {
566         let mut suggs = Vec::new();
567         let (title, msg) = if let ExprKind::AddrOf(Mutability::MutImmutable, ref inner) = ex.node {
568             let span = ex.span.source_callsite();
569             suggs.push((span, Sugg::hir_with_macro_callsite(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             let span = ex.span.source_callsite();
576             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
577             (
578                 "you don't need to add `&` to all patterns",
579                 "instead of prefixing all patterns with `&`, you can dereference the expression",
580             )
581         };
582
583         suggs.extend(arms.iter().flat_map(|a| &a.pats).filter_map(|p| {
584             if let PatKind::Ref(ref refp, _) = p.node {
585                 Some((p.span, snippet(cx, refp.span, "..").to_string()))
586             } else {
587                 None
588             }
589         }));
590
591         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
592             if !in_macro(expr.span) {
593                 multispan_sugg(db, msg.to_owned(), suggs);
594             }
595         });
596     }
597 }
598
599 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {
600     if arms.len() == 2
601         && arms[0].pats.len() == 1
602         && arms[0].guard.is_none()
603         && arms[1].pats.len() == 1
604         && arms[1].guard.is_none()
605     {
606         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
607             is_ref_some_arm(&arms[1])
608         } else if is_none_arm(&arms[1]) {
609             is_ref_some_arm(&arms[0])
610         } else {
611             None
612         };
613         if let Some(rb) = arm_ref {
614             let suggestion = if rb == BindingAnnotation::Ref {
615                 "as_ref"
616             } else {
617                 "as_mut"
618             };
619             let mut applicability = Applicability::MachineApplicable;
620             span_lint_and_sugg(
621                 cx,
622                 MATCH_AS_REF,
623                 expr.span,
624                 &format!("use {}() instead", suggestion),
625                 "try this",
626                 format!(
627                     "{}.{}()",
628                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
629                     suggestion
630                 ),
631                 applicability,
632             )
633         }
634     }
635 }
636
637 /// Gets all arms that are unbounded `PatRange`s.
638 fn all_ranges<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arms: &'tcx [Arm]) -> Vec<SpannedRange<Constant>> {
639     arms.iter()
640         .flat_map(|arm| {
641             if let Arm {
642                 ref pats, guard: None, ..
643             } = *arm
644             {
645                 pats.iter()
646             } else {
647                 [].iter()
648             }
649             .filter_map(|pat| {
650                 if let PatKind::Range(ref lhs, ref rhs, ref range_end) = pat.node {
651                     let lhs = constant(cx, cx.tables, lhs)?.0;
652                     let rhs = constant(cx, cx.tables, rhs)?.0;
653                     let rhs = match *range_end {
654                         RangeEnd::Included => Bound::Included(rhs),
655                         RangeEnd::Excluded => Bound::Excluded(rhs),
656                     };
657                     return Some(SpannedRange {
658                         span: pat.span,
659                         node: (lhs, rhs),
660                     });
661                 }
662
663                 if let PatKind::Lit(ref value) = pat.node {
664                     let value = constant(cx, cx.tables, value)?.0;
665                     return Some(SpannedRange {
666                         span: pat.span,
667                         node: (value.clone(), Bound::Included(value)),
668                     });
669                 }
670
671                 None
672             })
673         })
674         .collect()
675 }
676
677 #[derive(Debug, Eq, PartialEq)]
678 pub struct SpannedRange<T> {
679     pub span: Span,
680     pub node: (T, Bound<T>),
681 }
682
683 type TypedRanges = Vec<SpannedRange<u128>>;
684
685 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
686 /// and other types than
687 /// `Uint` and `Int` probably don't make sense.
688 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
689     ranges
690         .iter()
691         .filter_map(|range| match range.node {
692             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
693                 span: range.span,
694                 node: (start, Bound::Included(end)),
695             }),
696             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
697                 span: range.span,
698                 node: (start, Bound::Excluded(end)),
699             }),
700             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
701                 span: range.span,
702                 node: (start, Bound::Unbounded),
703             }),
704             _ => None,
705         })
706         .collect()
707 }
708
709 fn is_unit_expr(expr: &Expr) -> bool {
710     match expr.node {
711         ExprKind::Tup(ref v) if v.is_empty() => true,
712         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
713         _ => false,
714     }
715 }
716
717 // Checks if arm has the form `None => None`
718 fn is_none_arm(arm: &Arm) -> bool {
719     match arm.pats[0].node {
720         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
721         _ => false,
722     }
723 }
724
725 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
726 fn is_ref_some_arm(arm: &Arm) -> Option<BindingAnnotation> {
727     if_chain! {
728         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pats[0].node;
729         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
730         if let PatKind::Binding(rb, .., ident, _) = pats[0].node;
731         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
732         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).node;
733         if let ExprKind::Path(ref some_path) = e.node;
734         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
735         if let ExprKind::Path(ref qpath) = args[0].node;
736         if let &QPath::Resolved(_, ref path2) = qpath;
737         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
738         then {
739             return Some(rb)
740         }
741     }
742     None
743 }
744
745 fn has_only_ref_pats(arms: &[Arm]) -> bool {
746     let mapped = arms
747         .iter()
748         .flat_map(|a| &a.pats)
749         .map(|p| {
750             match p.node {
751                 PatKind::Ref(..) => Some(true), // &-patterns
752                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
753                 _ => None,                      // any other pattern is not fine
754             }
755         })
756         .collect::<Option<Vec<bool>>>();
757     // look for Some(v) where there's at least one true element
758     mapped.map_or(false, |v| v.iter().any(|el| *el))
759 }
760
761 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
762 where
763     T: Copy + Ord,
764 {
765     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
766     enum Kind<'a, T: 'a> {
767         Start(T, &'a SpannedRange<T>),
768         End(Bound<T>, &'a SpannedRange<T>),
769     }
770
771     impl<'a, T: Copy> Kind<'a, T> {
772         fn range(&self) -> &'a SpannedRange<T> {
773             match *self {
774                 Kind::Start(_, r) | Kind::End(_, r) => r,
775             }
776         }
777
778         fn value(self) -> Bound<T> {
779             match self {
780                 Kind::Start(t, _) => Bound::Included(t),
781                 Kind::End(t, _) => t,
782             }
783         }
784     }
785
786     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
787         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
788             Some(self.cmp(other))
789         }
790     }
791
792     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
793         fn cmp(&self, other: &Self) -> Ordering {
794             match (self.value(), other.value()) {
795                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
796                 // Range patterns cannot be unbounded (yet)
797                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
798                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
799                     Ordering::Equal => Ordering::Greater,
800                     other => other,
801                 },
802                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
803                     Ordering::Equal => Ordering::Less,
804                     other => other,
805                 },
806             }
807         }
808     }
809
810     let mut values = Vec::with_capacity(2 * ranges.len());
811
812     for r in ranges {
813         values.push(Kind::Start(r.node.0, r));
814         values.push(Kind::End(r.node.1, r));
815     }
816
817     values.sort();
818
819     for (a, b) in values.iter().zip(values.iter().skip(1)) {
820         match (a, b) {
821             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
822                 if ra.node != rb.node {
823                     return Some((ra, rb));
824                 }
825             },
826             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
827             _ => return Some((a.range(), b.range())),
828         }
829     }
830
831     None
832 }