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