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