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