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