]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Merge branch 'master' of github.com:rust-lang/rust-clippy
[rust.git] / clippy_lints / src / matches.rs
1 use crate::consts::{constant, miri_to_const, Constant};
2 use crate::utils::paths;
3 use crate::utils::sugg::Sugg;
4 use crate::utils::usage::is_unused;
5 use crate::utils::{
6     expr_block, get_arg_name, in_macro, indent_of, is_allowed, is_expn_of, is_refutable, is_wild, match_qpath,
7     match_type, match_var, multispan_sugg, remove_blocks, snippet, snippet_block, snippet_with_applicability,
8     span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then, walk_ptrs_ty,
9 };
10 use if_chain::if_chain;
11 use rustc::lint::in_external_macro;
12 use rustc::ty::{self, Ty};
13 use rustc_ast::ast::LitKind;
14 use rustc_errors::Applicability;
15 use rustc_hir::def::CtorKind;
16 use rustc_hir::{
17     print, Arm, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, Local, MatchSource, Mutability, PatKind, QPath,
18     RangeEnd,
19 };
20 use rustc_lint::{LateContext, LateLintPass, LintContext};
21 use rustc_session::{declare_tool_lint, impl_lint_pass};
22 use rustc_span::source_map::Span;
23 use std::cmp::Ordering;
24 use std::collections::Bound;
25
26 declare_clippy_lint! {
27     /// **What it does:** Checks for matches with a single arm where an `if let`
28     /// will usually suffice.
29     ///
30     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
31     ///
32     /// **Known problems:** None.
33     ///
34     /// **Example:**
35     /// ```rust
36     /// # fn bar(stool: &str) {}
37     /// # let x = Some("abc");
38     /// match x {
39     ///     Some(ref foo) => bar(foo),
40     ///     _ => (),
41     /// }
42     /// ```
43     pub SINGLE_MATCH,
44     style,
45     "a `match` statement with a single nontrivial arm (i.e., where the other arm is `_ => {}`) instead of `if let`"
46 }
47
48 declare_clippy_lint! {
49     /// **What it does:** Checks for matches with two arms where an `if let else` will
50     /// usually suffice.
51     ///
52     /// **Why is this bad?** Just readability – `if let` nests less than a `match`.
53     ///
54     /// **Known problems:** Personal style preferences may differ.
55     ///
56     /// **Example:**
57     ///
58     /// Using `match`:
59     ///
60     /// ```rust
61     /// # fn bar(foo: &usize) {}
62     /// # let other_ref: usize = 1;
63     /// # let x: Option<&usize> = Some(&1);
64     /// match x {
65     ///     Some(ref foo) => bar(foo),
66     ///     _ => bar(&other_ref),
67     /// }
68     /// ```
69     ///
70     /// Using `if let` with `else`:
71     ///
72     /// ```rust
73     /// # fn bar(foo: &usize) {}
74     /// # let other_ref: usize = 1;
75     /// # let x: Option<&usize> = Some(&1);
76     /// if let Some(ref foo) = x {
77     ///     bar(foo);
78     /// } else {
79     ///     bar(&other_ref);
80     /// }
81     /// ```
82     pub SINGLE_MATCH_ELSE,
83     pedantic,
84     "a `match` statement with two arms where the second arm's pattern is a placeholder instead of a specific match pattern"
85 }
86
87 declare_clippy_lint! {
88     /// **What it does:** Checks for matches where all arms match a reference,
89     /// suggesting to remove the reference and deref the matched expression
90     /// instead. It also checks for `if let &foo = bar` blocks.
91     ///
92     /// **Why is this bad?** It just makes the code less readable. That reference
93     /// destructuring adds nothing to the code.
94     ///
95     /// **Known problems:** None.
96     ///
97     /// **Example:**
98     /// ```rust,ignore
99     /// match x {
100     ///     &A(ref y) => foo(y),
101     ///     &B => bar(),
102     ///     _ => frob(&x),
103     /// }
104     /// ```
105     pub MATCH_REF_PATS,
106     style,
107     "a `match` or `if let` with all arms prefixed with `&` instead of deref-ing the match expression"
108 }
109
110 declare_clippy_lint! {
111     /// **What it does:** Checks for matches where match expression is a `bool`. It
112     /// suggests to replace the expression with an `if...else` block.
113     ///
114     /// **Why is this bad?** It makes the code less readable.
115     ///
116     /// **Known problems:** None.
117     ///
118     /// **Example:**
119     /// ```rust
120     /// # fn foo() {}
121     /// # fn bar() {}
122     /// let condition: bool = true;
123     /// match condition {
124     ///     true => foo(),
125     ///     false => bar(),
126     /// }
127     /// ```
128     /// Use if/else instead:
129     /// ```rust
130     /// # fn foo() {}
131     /// # fn bar() {}
132     /// let condition: bool = true;
133     /// if condition {
134     ///     foo();
135     /// } else {
136     ///     bar();
137     /// }
138     /// ```
139     pub MATCH_BOOL,
140     style,
141     "a `match` on a boolean expression instead of an `if..else` block"
142 }
143
144 declare_clippy_lint! {
145     /// **What it does:** Checks for overlapping match arms.
146     ///
147     /// **Why is this bad?** It is likely to be an error and if not, makes the code
148     /// less obvious.
149     ///
150     /// **Known problems:** None.
151     ///
152     /// **Example:**
153     /// ```rust
154     /// let x = 5;
155     /// match x {
156     ///     1...10 => println!("1 ... 10"),
157     ///     5...15 => println!("5 ... 15"),
158     ///     _ => (),
159     /// }
160     /// ```
161     pub MATCH_OVERLAPPING_ARM,
162     style,
163     "a `match` with overlapping arms"
164 }
165
166 declare_clippy_lint! {
167     /// **What it does:** Checks for arm which matches all errors with `Err(_)`
168     /// and take drastic actions like `panic!`.
169     ///
170     /// **Why is this bad?** It is generally a bad practice, just like
171     /// catching all exceptions in java with `catch(Exception)`
172     ///
173     /// **Known problems:** None.
174     ///
175     /// **Example:**
176     /// ```rust
177     /// let x: Result<i32, &str> = Ok(3);
178     /// match x {
179     ///     Ok(_) => println!("ok"),
180     ///     Err(_) => panic!("err"),
181     /// }
182     /// ```
183     pub MATCH_WILD_ERR_ARM,
184     style,
185     "a `match` with `Err(_)` arm and take drastic actions"
186 }
187
188 declare_clippy_lint! {
189     /// **What it does:** Checks for match which is used to add a reference to an
190     /// `Option` value.
191     ///
192     /// **Why is this bad?** Using `as_ref()` or `as_mut()` instead is shorter.
193     ///
194     /// **Known problems:** None.
195     ///
196     /// **Example:**
197     /// ```rust
198     /// let x: Option<()> = None;
199     /// let r: Option<&()> = match x {
200     ///     None => None,
201     ///     Some(ref v) => Some(v),
202     /// };
203     /// ```
204     pub MATCH_AS_REF,
205     complexity,
206     "a `match` on an Option value instead of using `as_ref()` or `as_mut`"
207 }
208
209 declare_clippy_lint! {
210     /// **What it does:** Checks for wildcard enum matches using `_`.
211     ///
212     /// **Why is this bad?** New enum variants added by library updates can be missed.
213     ///
214     /// **Known problems:** Suggested replacements may be incorrect if guards exhaustively cover some
215     /// variants, and also may not use correct path to enum if it's not present in the current scope.
216     ///
217     /// **Example:**
218     /// ```rust
219     /// # enum Foo { A(usize), B(usize) }
220     /// # let x = Foo::B(1);
221     /// match x {
222     ///     A => {},
223     ///     _ => {},
224     /// }
225     /// ```
226     pub WILDCARD_ENUM_MATCH_ARM,
227     restriction,
228     "a wildcard enum match arm using `_`"
229 }
230
231 declare_clippy_lint! {
232     /// **What it does:** Checks for wildcard pattern used with others patterns in same match arm.
233     ///
234     /// **Why is this bad?** Wildcard pattern already covers any other pattern as it will match anyway.
235     /// It makes the code less readable, especially to spot wildcard pattern use in match arm.
236     ///
237     /// **Known problems:** None.
238     ///
239     /// **Example:**
240     /// ```rust
241     /// match "foo" {
242     ///     "a" => {},
243     ///     "bar" | _ => {},
244     /// }
245     /// ```
246     pub WILDCARD_IN_OR_PATTERNS,
247     complexity,
248     "a wildcard pattern used with others patterns in same match arm"
249 }
250
251 declare_clippy_lint! {
252     /// **What it does:** Checks for matches being used to destructure a single-variant enum
253     /// or tuple struct where a `let` will suffice.
254     ///
255     /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
256     ///
257     /// **Known problems:** None.
258     ///
259     /// **Example:**
260     /// ```rust
261     /// enum Wrapper {
262     ///     Data(i32),
263     /// }
264     ///
265     /// let wrapper = Wrapper::Data(42);
266     ///
267     /// let data = match wrapper {
268     ///     Wrapper::Data(i) => i,
269     /// };
270     /// ```
271     ///
272     /// The correct use would be:
273     /// ```rust
274     /// enum Wrapper {
275     ///     Data(i32),
276     /// }
277     ///
278     /// let wrapper = Wrapper::Data(42);
279     /// let Wrapper::Data(data) = wrapper;
280     /// ```
281     pub INFALLIBLE_DESTRUCTURING_MATCH,
282     style,
283     "a `match` statement with a single infallible arm instead of a `let`"
284 }
285
286 declare_clippy_lint! {
287     /// **What it does:** Checks for useless match that binds to only one value.
288     ///
289     /// **Why is this bad?** Readability and needless complexity.
290     ///
291     /// **Known problems:**  Suggested replacements may be incorrect when `match`
292     /// is actually binding temporary value, bringing a 'dropped while borrowed' error.
293     ///
294     /// **Example:**
295     /// ```rust
296     /// # let a = 1;
297     /// # let b = 2;
298     ///
299     /// // Bad
300     /// match (a, b) {
301     ///     (c, d) => {
302     ///         // useless match
303     ///     }
304     /// }
305     ///
306     /// // Good
307     /// let (c, d) = (a, b);
308     /// ```
309     pub MATCH_SINGLE_BINDING,
310     complexity,
311     "a match with a single binding instead of using `let` statement"
312 }
313
314 #[derive(Default)]
315 pub struct Matches {
316     infallible_destructuring_match_linted: bool,
317 }
318
319 impl_lint_pass!(Matches => [
320     SINGLE_MATCH,
321     MATCH_REF_PATS,
322     MATCH_BOOL,
323     SINGLE_MATCH_ELSE,
324     MATCH_OVERLAPPING_ARM,
325     MATCH_WILD_ERR_ARM,
326     MATCH_AS_REF,
327     WILDCARD_ENUM_MATCH_ARM,
328     WILDCARD_IN_OR_PATTERNS,
329     MATCH_SINGLE_BINDING,
330     INFALLIBLE_DESTRUCTURING_MATCH
331 ]);
332
333 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
334     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
335         if in_external_macro(cx.sess(), expr.span) {
336             return;
337         }
338         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
339             check_single_match(cx, ex, arms, expr);
340             check_match_bool(cx, ex, arms, expr);
341             check_overlapping_arms(cx, ex, arms);
342             check_wild_err_arm(cx, ex, arms);
343             check_wild_enum_match(cx, ex, arms);
344             check_match_as_ref(cx, ex, arms, expr);
345             check_wild_in_or_pats(cx, arms);
346
347             if self.infallible_destructuring_match_linted {
348                 self.infallible_destructuring_match_linted = false;
349             } else {
350                 check_match_single_binding(cx, ex, arms, expr);
351             }
352         }
353         if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
354             check_match_ref_pats(cx, ex, arms, expr);
355         }
356     }
357
358     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
359         if_chain! {
360             if let Some(ref expr) = local.init;
361             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
362             if arms.len() == 1 && arms[0].guard.is_none();
363             if let PatKind::TupleStruct(
364                 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
365             if args.len() == 1;
366             if let Some(arg) = get_arg_name(&args[0]);
367             let body = remove_blocks(&arms[0].body);
368             if match_var(body, arg);
369
370             then {
371                 let mut applicability = Applicability::MachineApplicable;
372                 self.infallible_destructuring_match_linted = true;
373                 span_lint_and_sugg(
374                     cx,
375                     INFALLIBLE_DESTRUCTURING_MATCH,
376                     local.span,
377                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
378                     Consider using `let`",
379                     "try this",
380                     format!(
381                         "let {}({}) = {};",
382                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
383                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
384                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
385                     ),
386                     applicability,
387                 );
388             }
389         }
390     }
391 }
392
393 #[rustfmt::skip]
394 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
395     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
396         if let PatKind::Or(..) = arms[0].pat.kind {
397             // don't lint for or patterns for now, this makes
398             // the lint noisy in unnecessary situations
399             return;
400         }
401         let els = remove_blocks(&arms[1].body);
402         let els = if is_unit_expr(els) {
403             None
404         } else if let ExprKind::Block(_, _) = els.kind {
405             // matches with blocks that contain statements are prettier as `if let + else`
406             Some(els)
407         } else {
408             // allow match arms with just expressions
409             return;
410         };
411         let ty = cx.tables.expr_ty(ex);
412         if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
413             check_single_match_single_pattern(cx, ex, arms, expr, els);
414             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
415         }
416     }
417 }
418
419 fn check_single_match_single_pattern(
420     cx: &LateContext<'_, '_>,
421     ex: &Expr<'_>,
422     arms: &[Arm<'_>],
423     expr: &Expr<'_>,
424     els: Option<&Expr<'_>>,
425 ) {
426     if is_wild(&arms[1].pat) {
427         report_single_match_single_pattern(cx, ex, arms, expr, els);
428     }
429 }
430
431 fn report_single_match_single_pattern(
432     cx: &LateContext<'_, '_>,
433     ex: &Expr<'_>,
434     arms: &[Arm<'_>],
435     expr: &Expr<'_>,
436     els: Option<&Expr<'_>>,
437 ) {
438     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
439     let els_str = els.map_or(String::new(), |els| {
440         format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
441     });
442     span_lint_and_sugg(
443         cx,
444         lint,
445         expr.span,
446         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
447          let`",
448         "try this",
449         format!(
450             "if let {} = {} {}{}",
451             snippet(cx, arms[0].pat.span, ".."),
452             snippet(cx, ex.span, ".."),
453             expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
454             els_str,
455         ),
456         Applicability::HasPlaceholders,
457     );
458 }
459
460 fn check_single_match_opt_like(
461     cx: &LateContext<'_, '_>,
462     ex: &Expr<'_>,
463     arms: &[Arm<'_>],
464     expr: &Expr<'_>,
465     ty: Ty<'_>,
466     els: Option<&Expr<'_>>,
467 ) {
468     // list of candidate `Enum`s we know will never get any more members
469     let candidates = &[
470         (&paths::COW, "Borrowed"),
471         (&paths::COW, "Cow::Borrowed"),
472         (&paths::COW, "Cow::Owned"),
473         (&paths::COW, "Owned"),
474         (&paths::OPTION, "None"),
475         (&paths::RESULT, "Err"),
476         (&paths::RESULT, "Ok"),
477     ];
478
479     let path = match arms[1].pat.kind {
480         PatKind::TupleStruct(ref path, ref inner, _) => {
481             // Contains any non wildcard patterns (e.g., `Err(err)`)?
482             if !inner.iter().all(is_wild) {
483                 return;
484             }
485             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
486         },
487         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
488         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
489         _ => return,
490     };
491
492     for &(ty_path, pat_path) in candidates {
493         if path == *pat_path && match_type(cx, ty, ty_path) {
494             report_single_match_single_pattern(cx, ex, arms, expr, els);
495         }
496     }
497 }
498
499 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
500     // Type of expression is `bool`.
501     if cx.tables.expr_ty(ex).kind == ty::Bool {
502         span_lint_and_then(
503             cx,
504             MATCH_BOOL,
505             expr.span,
506             "you seem to be trying to match on a boolean expression",
507             move |db| {
508                 if arms.len() == 2 {
509                     // no guards
510                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
511                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
512                             match lit.node {
513                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
514                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
515                                 _ => None,
516                             }
517                         } else {
518                             None
519                         }
520                     } else {
521                         None
522                     };
523
524                     if let Some((true_expr, false_expr)) = exprs {
525                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
526                             (false, false) => Some(format!(
527                                 "if {} {} else {}",
528                                 snippet(cx, ex.span, "b"),
529                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
530                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
531                             )),
532                             (false, true) => Some(format!(
533                                 "if {} {}",
534                                 snippet(cx, ex.span, "b"),
535                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
536                             )),
537                             (true, false) => {
538                                 let test = Sugg::hir(cx, ex, "..");
539                                 Some(format!(
540                                     "if {} {}",
541                                     !test,
542                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
543                                 ))
544                             },
545                             (true, true) => None,
546                         };
547
548                         if let Some(sugg) = sugg {
549                             db.span_suggestion(
550                                 expr.span,
551                                 "consider using an `if`/`else` expression",
552                                 sugg,
553                                 Applicability::HasPlaceholders,
554                             );
555                         }
556                     }
557                 }
558             },
559         );
560     }
561 }
562
563 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
564     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
565         let ranges = all_ranges(cx, arms, cx.tables.expr_ty(ex));
566         let type_ranges = type_ranges(&ranges);
567         if !type_ranges.is_empty() {
568             if let Some((start, end)) = overlapping(&type_ranges) {
569                 span_lint_and_note(
570                     cx,
571                     MATCH_OVERLAPPING_ARM,
572                     start.span,
573                     "some ranges overlap",
574                     end.span,
575                     "overlaps with this",
576                 );
577             }
578         }
579     }
580 }
581
582 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
583     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
584     if match_type(cx, ex_ty, &paths::RESULT) {
585         for arm in arms {
586             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
587                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
588                 if path_str == "Err" {
589                     let mut matching_wild = inner.iter().any(is_wild);
590                     let mut ident_bind_name = String::from("_");
591                     if !matching_wild {
592                         // Looking for unused bindings (i.e.: `_e`)
593                         inner.iter().for_each(|pat| {
594                             if let PatKind::Binding(.., ident, None) = &pat.kind {
595                                 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
596                                     ident_bind_name = (&ident.name.as_str()).to_string();
597                                     matching_wild = true;
598                                 }
599                             }
600                         });
601                     }
602                     if_chain! {
603                         if matching_wild;
604                         if let ExprKind::Block(ref block, _) = arm.body.kind;
605                         if is_panic_block(block);
606                         then {
607                             // `Err(_)` or `Err(_e)` arm with `panic!` found
608                             span_lint_and_note(cx,
609                                 MATCH_WILD_ERR_ARM,
610                                 arm.pat.span,
611                                 &format!("`Err({})` matches all errors", &ident_bind_name),
612                                 arm.pat.span,
613                                 "match each error separately or use the error output",
614                             );
615                         }
616                     }
617                 }
618             }
619         }
620     }
621 }
622
623 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
624     let ty = cx.tables.expr_ty(ex);
625     if !ty.is_enum() {
626         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
627         // don't complain about not enumerating the mall.
628         return;
629     }
630
631     // First pass - check for violation, but don't do much book-keeping because this is hopefully
632     // the uncommon case, and the book-keeping is slightly expensive.
633     let mut wildcard_span = None;
634     let mut wildcard_ident = None;
635     for arm in arms {
636         if let PatKind::Wild = arm.pat.kind {
637             wildcard_span = Some(arm.pat.span);
638         } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
639             wildcard_span = Some(arm.pat.span);
640             wildcard_ident = Some(ident);
641         }
642     }
643
644     if let Some(wildcard_span) = wildcard_span {
645         // Accumulate the variants which should be put in place of the wildcard because they're not
646         // already covered.
647
648         let mut missing_variants = vec![];
649         if let ty::Adt(def, _) = ty.kind {
650             for variant in &def.variants {
651                 missing_variants.push(variant);
652             }
653         }
654
655         for arm in arms {
656             if arm.guard.is_some() {
657                 // Guards mean that this case probably isn't exhaustively covered. Technically
658                 // this is incorrect, as we should really check whether each variant is exhaustively
659                 // covered by the set of guards that cover it, but that's really hard to do.
660                 continue;
661             }
662             if let PatKind::Path(ref path) = arm.pat.kind {
663                 if let QPath::Resolved(_, p) = path {
664                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
665                 }
666             } else if let PatKind::TupleStruct(ref path, ..) = arm.pat.kind {
667                 if let QPath::Resolved(_, p) = path {
668                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
669                 }
670             }
671         }
672
673         let mut suggestion: Vec<String> = missing_variants
674             .iter()
675             .map(|v| {
676                 let suffix = match v.ctor_kind {
677                     CtorKind::Fn => "(..)",
678                     CtorKind::Const | CtorKind::Fictive => "",
679                 };
680                 let ident_str = if let Some(ident) = wildcard_ident {
681                     format!("{} @ ", ident.name)
682                 } else {
683                     String::new()
684                 };
685                 // This path assumes that the enum type is imported into scope.
686                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
687             })
688             .collect();
689
690         if suggestion.is_empty() {
691             return;
692         }
693
694         let mut message = "wildcard match will miss any future added variants";
695
696         if let ty::Adt(def, _) = ty.kind {
697             if def.is_variant_list_non_exhaustive() {
698                 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
699                 suggestion.push(String::from("_"));
700             }
701         }
702
703         span_lint_and_sugg(
704             cx,
705             WILDCARD_ENUM_MATCH_ARM,
706             wildcard_span,
707             message,
708             "try this",
709             suggestion.join(" | "),
710             Applicability::MachineApplicable,
711         )
712     }
713 }
714
715 // If the block contains only a `panic!` macro (as expression or statement)
716 fn is_panic_block(block: &Block<'_>) -> bool {
717     match (&block.expr, block.stmts.len(), block.stmts.first()) {
718         (&Some(ref exp), 0, _) => {
719             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
720         },
721         (&None, 1, Some(stmt)) => {
722             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
723         },
724         _ => false,
725     }
726 }
727
728 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
729     if has_only_ref_pats(arms) {
730         let mut suggs = Vec::with_capacity(arms.len() + 1);
731         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
732             let span = ex.span.source_callsite();
733             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
734             (
735                 "you don't need to add `&` to both the expression and the patterns",
736                 "try",
737             )
738         } else {
739             let span = ex.span.source_callsite();
740             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
741             (
742                 "you don't need to add `&` to all patterns",
743                 "instead of prefixing all patterns with `&`, you can dereference the expression",
744             )
745         };
746
747         suggs.extend(arms.iter().filter_map(|a| {
748             if let PatKind::Ref(ref refp, _) = a.pat.kind {
749                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
750             } else {
751                 None
752             }
753         }));
754
755         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
756             if !expr.span.from_expansion() {
757                 multispan_sugg(db, msg.to_owned(), suggs);
758             }
759         });
760     }
761 }
762
763 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
764     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
765         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
766             is_ref_some_arm(&arms[1])
767         } else if is_none_arm(&arms[1]) {
768             is_ref_some_arm(&arms[0])
769         } else {
770             None
771         };
772         if let Some(rb) = arm_ref {
773             let suggestion = if rb == BindingAnnotation::Ref {
774                 "as_ref"
775             } else {
776                 "as_mut"
777             };
778
779             let output_ty = cx.tables.expr_ty(expr);
780             let input_ty = cx.tables.expr_ty(ex);
781
782             let cast = if_chain! {
783                 if let ty::Adt(_, substs) = input_ty.kind;
784                 let input_ty = substs.type_at(0);
785                 if let ty::Adt(_, substs) = output_ty.kind;
786                 let output_ty = substs.type_at(0);
787                 if let ty::Ref(_, output_ty, _) = output_ty.kind;
788                 if input_ty != output_ty;
789                 then {
790                     ".map(|x| x as _)"
791                 } else {
792                     ""
793                 }
794             };
795
796             let mut applicability = Applicability::MachineApplicable;
797             span_lint_and_sugg(
798                 cx,
799                 MATCH_AS_REF,
800                 expr.span,
801                 &format!("use `{}()` instead", suggestion),
802                 "try this",
803                 format!(
804                     "{}.{}(){}",
805                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
806                     suggestion,
807                     cast,
808                 ),
809                 applicability,
810             )
811         }
812     }
813 }
814
815 fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
816     for arm in arms {
817         if let PatKind::Or(ref fields) = arm.pat.kind {
818             // look for multiple fields in this arm that contains at least one Wild pattern
819             if fields.len() > 1 && fields.iter().any(is_wild) {
820                 span_lint_and_help(
821                     cx,
822                     WILDCARD_IN_OR_PATTERNS,
823                     arm.pat.span,
824                     "wildcard pattern covers any other pattern as it will match anyway.",
825                     "Consider handling `_` separately.",
826                 );
827             }
828         }
829     }
830 }
831
832 fn check_match_single_binding(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
833     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
834         return;
835     }
836     let matched_vars = ex.span;
837     let bind_names = arms[0].pat.span;
838     let match_body = remove_blocks(&arms[0].body);
839     let mut snippet_body = if match_body.span.from_expansion() {
840         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
841     } else {
842         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
843     };
844
845     // Do we need to add ';' to suggestion ?
846     match match_body.kind {
847         ExprKind::Block(block, _) => {
848             // macro + expr_ty(body) == ()
849             if block.span.from_expansion() && cx.tables.expr_ty(&match_body).is_unit() {
850                 snippet_body.push(';');
851             }
852         },
853         _ => {
854             // expr_ty(body) == ()
855             if cx.tables.expr_ty(&match_body).is_unit() {
856                 snippet_body.push(';');
857             }
858         },
859     }
860
861     let mut applicability = Applicability::MaybeIncorrect;
862     match arms[0].pat.kind {
863         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
864             span_lint_and_sugg(
865                 cx,
866                 MATCH_SINGLE_BINDING,
867                 expr.span,
868                 "this match could be written as a `let` statement",
869                 "consider using `let` statement",
870                 format!(
871                     "let {} = {};\n{}{}",
872                     snippet_with_applicability(cx, bind_names, "..", &mut applicability),
873                     snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
874                     " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
875                     snippet_body,
876                 ),
877                 applicability,
878             );
879         },
880         PatKind::Wild => {
881             span_lint_and_sugg(
882                 cx,
883                 MATCH_SINGLE_BINDING,
884                 expr.span,
885                 "this match could be replaced by its body itself",
886                 "consider using the match body instead",
887                 snippet_body,
888                 Applicability::MachineApplicable,
889             );
890         },
891         _ => (),
892     }
893 }
894
895 /// Gets all arms that are unbounded `PatRange`s.
896 fn all_ranges<'a, 'tcx>(
897     cx: &LateContext<'a, 'tcx>,
898     arms: &'tcx [Arm<'_>],
899     ty: Ty<'tcx>,
900 ) -> Vec<SpannedRange<Constant>> {
901     arms.iter()
902         .flat_map(|arm| {
903             if let Arm {
904                 ref pat, guard: None, ..
905             } = *arm
906             {
907                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
908                     let lhs = match lhs {
909                         Some(lhs) => constant(cx, cx.tables, lhs)?.0,
910                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
911                     };
912                     let rhs = match rhs {
913                         Some(rhs) => constant(cx, cx.tables, rhs)?.0,
914                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
915                     };
916                     let rhs = match range_end {
917                         RangeEnd::Included => Bound::Included(rhs),
918                         RangeEnd::Excluded => Bound::Excluded(rhs),
919                     };
920                     return Some(SpannedRange {
921                         span: pat.span,
922                         node: (lhs, rhs),
923                     });
924                 }
925
926                 if let PatKind::Lit(ref value) = pat.kind {
927                     let value = constant(cx, cx.tables, value)?.0;
928                     return Some(SpannedRange {
929                         span: pat.span,
930                         node: (value.clone(), Bound::Included(value)),
931                     });
932                 }
933             }
934             None
935         })
936         .collect()
937 }
938
939 #[derive(Debug, Eq, PartialEq)]
940 pub struct SpannedRange<T> {
941     pub span: Span,
942     pub node: (T, Bound<T>),
943 }
944
945 type TypedRanges = Vec<SpannedRange<u128>>;
946
947 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
948 /// and other types than
949 /// `Uint` and `Int` probably don't make sense.
950 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
951     ranges
952         .iter()
953         .filter_map(|range| match range.node {
954             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
955                 span: range.span,
956                 node: (start, Bound::Included(end)),
957             }),
958             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
959                 span: range.span,
960                 node: (start, Bound::Excluded(end)),
961             }),
962             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
963                 span: range.span,
964                 node: (start, Bound::Unbounded),
965             }),
966             _ => None,
967         })
968         .collect()
969 }
970
971 fn is_unit_expr(expr: &Expr<'_>) -> bool {
972     match expr.kind {
973         ExprKind::Tup(ref v) if v.is_empty() => true,
974         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
975         _ => false,
976     }
977 }
978
979 // Checks if arm has the form `None => None`
980 fn is_none_arm(arm: &Arm<'_>) -> bool {
981     match arm.pat.kind {
982         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
983         _ => false,
984     }
985 }
986
987 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
988 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
989     if_chain! {
990         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
991         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
992         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
993         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
994         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
995         if let ExprKind::Path(ref some_path) = e.kind;
996         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
997         if let ExprKind::Path(ref qpath) = args[0].kind;
998         if let &QPath::Resolved(_, ref path2) = qpath;
999         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1000         then {
1001             return Some(rb)
1002         }
1003     }
1004     None
1005 }
1006
1007 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1008     let mapped = arms
1009         .iter()
1010         .map(|a| {
1011             match a.pat.kind {
1012                 PatKind::Ref(..) => Some(true), // &-patterns
1013                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1014                 _ => None,                      // any other pattern is not fine
1015             }
1016         })
1017         .collect::<Option<Vec<bool>>>();
1018     // look for Some(v) where there's at least one true element
1019     mapped.map_or(false, |v| v.iter().any(|el| *el))
1020 }
1021
1022 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1023 where
1024     T: Copy + Ord,
1025 {
1026     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1027     enum Kind<'a, T> {
1028         Start(T, &'a SpannedRange<T>),
1029         End(Bound<T>, &'a SpannedRange<T>),
1030     }
1031
1032     impl<'a, T: Copy> Kind<'a, T> {
1033         fn range(&self) -> &'a SpannedRange<T> {
1034             match *self {
1035                 Kind::Start(_, r) | Kind::End(_, r) => r,
1036             }
1037         }
1038
1039         fn value(self) -> Bound<T> {
1040             match self {
1041                 Kind::Start(t, _) => Bound::Included(t),
1042                 Kind::End(t, _) => t,
1043             }
1044         }
1045     }
1046
1047     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1048         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1049             Some(self.cmp(other))
1050         }
1051     }
1052
1053     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1054         fn cmp(&self, other: &Self) -> Ordering {
1055             match (self.value(), other.value()) {
1056                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1057                 // Range patterns cannot be unbounded (yet)
1058                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1059                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1060                     Ordering::Equal => Ordering::Greater,
1061                     other => other,
1062                 },
1063                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1064                     Ordering::Equal => Ordering::Less,
1065                     other => other,
1066                 },
1067             }
1068         }
1069     }
1070
1071     let mut values = Vec::with_capacity(2 * ranges.len());
1072
1073     for r in ranges {
1074         values.push(Kind::Start(r.node.0, r));
1075         values.push(Kind::End(r.node.1, r));
1076     }
1077
1078     values.sort();
1079
1080     for (a, b) in values.iter().zip(values.iter().skip(1)) {
1081         match (a, b) {
1082             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1083                 if ra.node != rb.node {
1084                     return Some((ra, rb));
1085                 }
1086             },
1087             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1088             _ => return Some((a.range(), b.range())),
1089         }
1090     }
1091
1092     None
1093 }