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