]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches.rs
Auto merge of #5287 - matthiaskrgr:pat_isref, r=flip1995
[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, Node, Pat,
18     PatKind, QPath, 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 declare_clippy_lint! {
315     /// **What it does:** Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched.
316     ///
317     /// **Why is this bad?** Correctness and readability. It's like having a wildcard pattern after
318     /// matching all enum variants explicitly.
319     ///
320     /// **Known problems:** None.
321     ///
322     /// **Example:**
323     /// ```rust
324     /// # struct A { a: i32 }
325     /// let a = A { a: 5 };
326     ///
327     /// // Bad
328     /// match a {
329     ///     A { a: 5, .. } => {},
330     ///     _ => {},
331     /// }
332     ///
333     /// // Good
334     /// match a {
335     ///     A { a: 5 } => {},
336     ///     _ => {},
337     /// }
338     /// ```
339     pub REST_PAT_IN_FULLY_BOUND_STRUCTS,
340     restriction,
341     "a match on a struct that binds all fields but still uses the wildcard pattern"
342 }
343
344 #[derive(Default)]
345 pub struct Matches {
346     infallible_destructuring_match_linted: bool,
347 }
348
349 impl_lint_pass!(Matches => [
350     SINGLE_MATCH,
351     MATCH_REF_PATS,
352     MATCH_BOOL,
353     SINGLE_MATCH_ELSE,
354     MATCH_OVERLAPPING_ARM,
355     MATCH_WILD_ERR_ARM,
356     MATCH_AS_REF,
357     WILDCARD_ENUM_MATCH_ARM,
358     WILDCARD_IN_OR_PATTERNS,
359     MATCH_SINGLE_BINDING,
360     INFALLIBLE_DESTRUCTURING_MATCH,
361     REST_PAT_IN_FULLY_BOUND_STRUCTS
362 ]);
363
364 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Matches {
365     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
366         if in_external_macro(cx.sess(), expr.span) {
367             return;
368         }
369         if let ExprKind::Match(ref ex, ref arms, MatchSource::Normal) = expr.kind {
370             check_single_match(cx, ex, arms, expr);
371             check_match_bool(cx, ex, arms, expr);
372             check_overlapping_arms(cx, ex, arms);
373             check_wild_err_arm(cx, ex, arms);
374             check_wild_enum_match(cx, ex, arms);
375             check_match_as_ref(cx, ex, arms, expr);
376             check_wild_in_or_pats(cx, arms);
377
378             if self.infallible_destructuring_match_linted {
379                 self.infallible_destructuring_match_linted = false;
380             } else {
381                 check_match_single_binding(cx, ex, arms, expr);
382             }
383         }
384         if let ExprKind::Match(ref ex, ref arms, _) = expr.kind {
385             check_match_ref_pats(cx, ex, arms, expr);
386         }
387     }
388
389     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
390         if_chain! {
391             if let Some(ref expr) = local.init;
392             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.kind;
393             if arms.len() == 1 && arms[0].guard.is_none();
394             if let PatKind::TupleStruct(
395                 QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pat.kind;
396             if args.len() == 1;
397             if let Some(arg) = get_arg_name(&args[0]);
398             let body = remove_blocks(&arms[0].body);
399             if match_var(body, arg);
400
401             then {
402                 let mut applicability = Applicability::MachineApplicable;
403                 self.infallible_destructuring_match_linted = true;
404                 span_lint_and_sugg(
405                     cx,
406                     INFALLIBLE_DESTRUCTURING_MATCH,
407                     local.span,
408                     "you seem to be trying to use `match` to destructure a single infallible pattern. \
409                     Consider using `let`",
410                     "try this",
411                     format!(
412                         "let {}({}) = {};",
413                         snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
414                         snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
415                         snippet_with_applicability(cx, target.span, "..", &mut applicability),
416                     ),
417                     applicability,
418                 );
419             }
420         }
421     }
422
423     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat<'_>) {
424         if_chain! {
425             if let PatKind::Struct(ref qpath, fields, true) = pat.kind;
426             if let QPath::Resolved(_, ref path) = qpath;
427             if let Some(def_id) = path.res.opt_def_id();
428             let ty = cx.tcx.type_of(def_id);
429             if let ty::Adt(def, _) = ty.kind;
430             if def.is_struct() || def.is_union();
431             if fields.len() == def.non_enum_variant().fields.len();
432
433             then {
434                 span_lint_and_help(
435                     cx,
436                     REST_PAT_IN_FULLY_BOUND_STRUCTS,
437                     pat.span,
438                     "unnecessary use of `..` pattern in struct binding. All fields were already bound",
439                     "consider removing `..` from this binding",
440                 );
441             }
442         }
443     }
444 }
445
446 #[rustfmt::skip]
447 fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
448     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
449         if let PatKind::Or(..) = arms[0].pat.kind {
450             // don't lint for or patterns for now, this makes
451             // the lint noisy in unnecessary situations
452             return;
453         }
454         let els = remove_blocks(&arms[1].body);
455         let els = if is_unit_expr(els) {
456             None
457         } else if let ExprKind::Block(_, _) = els.kind {
458             // matches with blocks that contain statements are prettier as `if let + else`
459             Some(els)
460         } else {
461             // allow match arms with just expressions
462             return;
463         };
464         let ty = cx.tables.expr_ty(ex);
465         if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) {
466             check_single_match_single_pattern(cx, ex, arms, expr, els);
467             check_single_match_opt_like(cx, ex, arms, expr, ty, els);
468         }
469     }
470 }
471
472 fn check_single_match_single_pattern(
473     cx: &LateContext<'_, '_>,
474     ex: &Expr<'_>,
475     arms: &[Arm<'_>],
476     expr: &Expr<'_>,
477     els: Option<&Expr<'_>>,
478 ) {
479     if is_wild(&arms[1].pat) {
480         report_single_match_single_pattern(cx, ex, arms, expr, els);
481     }
482 }
483
484 fn report_single_match_single_pattern(
485     cx: &LateContext<'_, '_>,
486     ex: &Expr<'_>,
487     arms: &[Arm<'_>],
488     expr: &Expr<'_>,
489     els: Option<&Expr<'_>>,
490 ) {
491     let lint = if els.is_some() { SINGLE_MATCH_ELSE } else { SINGLE_MATCH };
492     let els_str = els.map_or(String::new(), |els| {
493         format!(" else {}", expr_block(cx, els, None, "..", Some(expr.span)))
494     });
495     span_lint_and_sugg(
496         cx,
497         lint,
498         expr.span,
499         "you seem to be trying to use match for destructuring a single pattern. Consider using `if \
500          let`",
501         "try this",
502         format!(
503             "if let {} = {} {}{}",
504             snippet(cx, arms[0].pat.span, ".."),
505             snippet(cx, ex.span, ".."),
506             expr_block(cx, &arms[0].body, None, "..", Some(expr.span)),
507             els_str,
508         ),
509         Applicability::HasPlaceholders,
510     );
511 }
512
513 fn check_single_match_opt_like(
514     cx: &LateContext<'_, '_>,
515     ex: &Expr<'_>,
516     arms: &[Arm<'_>],
517     expr: &Expr<'_>,
518     ty: Ty<'_>,
519     els: Option<&Expr<'_>>,
520 ) {
521     // list of candidate `Enum`s we know will never get any more members
522     let candidates = &[
523         (&paths::COW, "Borrowed"),
524         (&paths::COW, "Cow::Borrowed"),
525         (&paths::COW, "Cow::Owned"),
526         (&paths::COW, "Owned"),
527         (&paths::OPTION, "None"),
528         (&paths::RESULT, "Err"),
529         (&paths::RESULT, "Ok"),
530     ];
531
532     let path = match arms[1].pat.kind {
533         PatKind::TupleStruct(ref path, ref inner, _) => {
534             // Contains any non wildcard patterns (e.g., `Err(err)`)?
535             if !inner.iter().all(is_wild) {
536                 return;
537             }
538             print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
539         },
540         PatKind::Binding(BindingAnnotation::Unannotated, .., ident, None) => ident.to_string(),
541         PatKind::Path(ref path) => print::to_string(print::NO_ANN, |s| s.print_qpath(path, false)),
542         _ => return,
543     };
544
545     for &(ty_path, pat_path) in candidates {
546         if path == *pat_path && match_type(cx, ty, ty_path) {
547             report_single_match_single_pattern(cx, ex, arms, expr, els);
548         }
549     }
550 }
551
552 fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
553     // Type of expression is `bool`.
554     if cx.tables.expr_ty(ex).kind == ty::Bool {
555         span_lint_and_then(
556             cx,
557             MATCH_BOOL,
558             expr.span,
559             "you seem to be trying to match on a boolean expression",
560             move |db| {
561                 if arms.len() == 2 {
562                     // no guards
563                     let exprs = if let PatKind::Lit(ref arm_bool) = arms[0].pat.kind {
564                         if let ExprKind::Lit(ref lit) = arm_bool.kind {
565                             match lit.node {
566                                 LitKind::Bool(true) => Some((&*arms[0].body, &*arms[1].body)),
567                                 LitKind::Bool(false) => Some((&*arms[1].body, &*arms[0].body)),
568                                 _ => None,
569                             }
570                         } else {
571                             None
572                         }
573                     } else {
574                         None
575                     };
576
577                     if let Some((true_expr, false_expr)) = exprs {
578                         let sugg = match (is_unit_expr(true_expr), is_unit_expr(false_expr)) {
579                             (false, false) => Some(format!(
580                                 "if {} {} else {}",
581                                 snippet(cx, ex.span, "b"),
582                                 expr_block(cx, true_expr, None, "..", Some(expr.span)),
583                                 expr_block(cx, false_expr, None, "..", Some(expr.span))
584                             )),
585                             (false, true) => Some(format!(
586                                 "if {} {}",
587                                 snippet(cx, ex.span, "b"),
588                                 expr_block(cx, true_expr, None, "..", Some(expr.span))
589                             )),
590                             (true, false) => {
591                                 let test = Sugg::hir(cx, ex, "..");
592                                 Some(format!(
593                                     "if {} {}",
594                                     !test,
595                                     expr_block(cx, false_expr, None, "..", Some(expr.span))
596                                 ))
597                             },
598                             (true, true) => None,
599                         };
600
601                         if let Some(sugg) = sugg {
602                             db.span_suggestion(
603                                 expr.span,
604                                 "consider using an `if`/`else` expression",
605                                 sugg,
606                                 Applicability::HasPlaceholders,
607                             );
608                         }
609                     }
610                 }
611             },
612         );
613     }
614 }
615
616 fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) {
617     if arms.len() >= 2 && cx.tables.expr_ty(ex).is_integral() {
618         let ranges = all_ranges(cx, arms, cx.tables.expr_ty(ex));
619         let type_ranges = type_ranges(&ranges);
620         if !type_ranges.is_empty() {
621             if let Some((start, end)) = overlapping(&type_ranges) {
622                 span_lint_and_note(
623                     cx,
624                     MATCH_OVERLAPPING_ARM,
625                     start.span,
626                     "some ranges overlap",
627                     end.span,
628                     "overlaps with this",
629                 );
630             }
631         }
632     }
633 }
634
635 fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
636     let ex_ty = walk_ptrs_ty(cx.tables.expr_ty(ex));
637     if match_type(cx, ex_ty, &paths::RESULT) {
638         for arm in arms {
639             if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind {
640                 let path_str = print::to_string(print::NO_ANN, |s| s.print_qpath(path, false));
641                 if path_str == "Err" {
642                     let mut matching_wild = inner.iter().any(is_wild);
643                     let mut ident_bind_name = String::from("_");
644                     if !matching_wild {
645                         // Looking for unused bindings (i.e.: `_e`)
646                         inner.iter().for_each(|pat| {
647                             if let PatKind::Binding(.., ident, None) = &pat.kind {
648                                 if ident.as_str().starts_with('_') && is_unused(ident, arm.body) {
649                                     ident_bind_name = (&ident.name.as_str()).to_string();
650                                     matching_wild = true;
651                                 }
652                             }
653                         });
654                     }
655                     if_chain! {
656                         if matching_wild;
657                         if let ExprKind::Block(ref block, _) = arm.body.kind;
658                         if is_panic_block(block);
659                         then {
660                             // `Err(_)` or `Err(_e)` arm with `panic!` found
661                             span_lint_and_note(cx,
662                                 MATCH_WILD_ERR_ARM,
663                                 arm.pat.span,
664                                 &format!("`Err({})` matches all errors", &ident_bind_name),
665                                 arm.pat.span,
666                                 "match each error separately or use the error output",
667                             );
668                         }
669                     }
670                 }
671             }
672         }
673     }
674 }
675
676 fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) {
677     let ty = cx.tables.expr_ty(ex);
678     if !ty.is_enum() {
679         // If there isn't a nice closed set of possible values that can be conveniently enumerated,
680         // don't complain about not enumerating the mall.
681         return;
682     }
683
684     // First pass - check for violation, but don't do much book-keeping because this is hopefully
685     // the uncommon case, and the book-keeping is slightly expensive.
686     let mut wildcard_span = None;
687     let mut wildcard_ident = None;
688     for arm in arms {
689         if let PatKind::Wild = arm.pat.kind {
690             wildcard_span = Some(arm.pat.span);
691         } else if let PatKind::Binding(_, _, ident, None) = arm.pat.kind {
692             wildcard_span = Some(arm.pat.span);
693             wildcard_ident = Some(ident);
694         }
695     }
696
697     if let Some(wildcard_span) = wildcard_span {
698         // Accumulate the variants which should be put in place of the wildcard because they're not
699         // already covered.
700
701         let mut missing_variants = vec![];
702         if let ty::Adt(def, _) = ty.kind {
703             for variant in &def.variants {
704                 missing_variants.push(variant);
705             }
706         }
707
708         for arm in arms {
709             if arm.guard.is_some() {
710                 // Guards mean that this case probably isn't exhaustively covered. Technically
711                 // this is incorrect, as we should really check whether each variant is exhaustively
712                 // covered by the set of guards that cover it, but that's really hard to do.
713                 continue;
714             }
715             if let PatKind::Path(ref path) = arm.pat.kind {
716                 if let QPath::Resolved(_, p) = path {
717                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
718                 }
719             } else if let PatKind::TupleStruct(ref path, ..) = arm.pat.kind {
720                 if let QPath::Resolved(_, p) = path {
721                     missing_variants.retain(|e| e.ctor_def_id != Some(p.res.def_id()));
722                 }
723             }
724         }
725
726         let mut suggestion: Vec<String> = missing_variants
727             .iter()
728             .map(|v| {
729                 let suffix = match v.ctor_kind {
730                     CtorKind::Fn => "(..)",
731                     CtorKind::Const | CtorKind::Fictive => "",
732                 };
733                 let ident_str = if let Some(ident) = wildcard_ident {
734                     format!("{} @ ", ident.name)
735                 } else {
736                     String::new()
737                 };
738                 // This path assumes that the enum type is imported into scope.
739                 format!("{}{}{}", ident_str, cx.tcx.def_path_str(v.def_id), suffix)
740             })
741             .collect();
742
743         if suggestion.is_empty() {
744             return;
745         }
746
747         let mut message = "wildcard match will miss any future added variants";
748
749         if let ty::Adt(def, _) = ty.kind {
750             if def.is_variant_list_non_exhaustive() {
751                 message = "match on non-exhaustive enum doesn't explicitly match all known variants";
752                 suggestion.push(String::from("_"));
753             }
754         }
755
756         span_lint_and_sugg(
757             cx,
758             WILDCARD_ENUM_MATCH_ARM,
759             wildcard_span,
760             message,
761             "try this",
762             suggestion.join(" | "),
763             Applicability::MachineApplicable,
764         )
765     }
766 }
767
768 // If the block contains only a `panic!` macro (as expression or statement)
769 fn is_panic_block(block: &Block<'_>) -> bool {
770     match (&block.expr, block.stmts.len(), block.stmts.first()) {
771         (&Some(ref exp), 0, _) => {
772             is_expn_of(exp.span, "panic").is_some() && is_expn_of(exp.span, "unreachable").is_none()
773         },
774         (&None, 1, Some(stmt)) => {
775             is_expn_of(stmt.span, "panic").is_some() && is_expn_of(stmt.span, "unreachable").is_none()
776         },
777         _ => false,
778     }
779 }
780
781 fn check_match_ref_pats(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
782     if has_only_ref_pats(arms) {
783         let mut suggs = Vec::with_capacity(arms.len() + 1);
784         let (title, msg) = if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = ex.kind {
785             let span = ex.span.source_callsite();
786             suggs.push((span, Sugg::hir_with_macro_callsite(cx, inner, "..").to_string()));
787             (
788                 "you don't need to add `&` to both the expression and the patterns",
789                 "try",
790             )
791         } else {
792             let span = ex.span.source_callsite();
793             suggs.push((span, Sugg::hir_with_macro_callsite(cx, ex, "..").deref().to_string()));
794             (
795                 "you don't need to add `&` to all patterns",
796                 "instead of prefixing all patterns with `&`, you can dereference the expression",
797             )
798         };
799
800         suggs.extend(arms.iter().filter_map(|a| {
801             if let PatKind::Ref(ref refp, _) = a.pat.kind {
802                 Some((a.pat.span, snippet(cx, refp.span, "..").to_string()))
803             } else {
804                 None
805             }
806         }));
807
808         span_lint_and_then(cx, MATCH_REF_PATS, expr.span, title, |db| {
809             if !expr.span.from_expansion() {
810                 multispan_sugg(db, msg.to_owned(), suggs);
811             }
812         });
813     }
814 }
815
816 fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
817     if arms.len() == 2 && arms[0].guard.is_none() && arms[1].guard.is_none() {
818         let arm_ref: Option<BindingAnnotation> = if is_none_arm(&arms[0]) {
819             is_ref_some_arm(&arms[1])
820         } else if is_none_arm(&arms[1]) {
821             is_ref_some_arm(&arms[0])
822         } else {
823             None
824         };
825         if let Some(rb) = arm_ref {
826             let suggestion = if rb == BindingAnnotation::Ref {
827                 "as_ref"
828             } else {
829                 "as_mut"
830             };
831
832             let output_ty = cx.tables.expr_ty(expr);
833             let input_ty = cx.tables.expr_ty(ex);
834
835             let cast = if_chain! {
836                 if let ty::Adt(_, substs) = input_ty.kind;
837                 let input_ty = substs.type_at(0);
838                 if let ty::Adt(_, substs) = output_ty.kind;
839                 let output_ty = substs.type_at(0);
840                 if let ty::Ref(_, output_ty, _) = output_ty.kind;
841                 if input_ty != output_ty;
842                 then {
843                     ".map(|x| x as _)"
844                 } else {
845                     ""
846                 }
847             };
848
849             let mut applicability = Applicability::MachineApplicable;
850             span_lint_and_sugg(
851                 cx,
852                 MATCH_AS_REF,
853                 expr.span,
854                 &format!("use `{}()` instead", suggestion),
855                 "try this",
856                 format!(
857                     "{}.{}(){}",
858                     snippet_with_applicability(cx, ex.span, "_", &mut applicability),
859                     suggestion,
860                     cast,
861                 ),
862                 applicability,
863             )
864         }
865     }
866 }
867
868 fn check_wild_in_or_pats(cx: &LateContext<'_, '_>, arms: &[Arm<'_>]) {
869     for arm in arms {
870         if let PatKind::Or(ref fields) = arm.pat.kind {
871             // look for multiple fields in this arm that contains at least one Wild pattern
872             if fields.len() > 1 && fields.iter().any(is_wild) {
873                 span_lint_and_help(
874                     cx,
875                     WILDCARD_IN_OR_PATTERNS,
876                     arm.pat.span,
877                     "wildcard pattern covers any other pattern as it will match anyway.",
878                     "Consider handling `_` separately.",
879                 );
880             }
881         }
882     }
883 }
884
885 fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: &[Arm<'_>], expr: &Expr<'_>) {
886     if in_macro(expr.span) || arms.len() != 1 || is_refutable(cx, arms[0].pat) {
887         return;
888     }
889     let matched_vars = ex.span;
890     let bind_names = arms[0].pat.span;
891     let match_body = remove_blocks(&arms[0].body);
892     let mut snippet_body = if match_body.span.from_expansion() {
893         Sugg::hir_with_macro_callsite(cx, match_body, "..").to_string()
894     } else {
895         snippet_block(cx, match_body.span, "..", Some(expr.span)).to_string()
896     };
897
898     // Do we need to add ';' to suggestion ?
899     match match_body.kind {
900         ExprKind::Block(block, _) => {
901             // macro + expr_ty(body) == ()
902             if block.span.from_expansion() && cx.tables.expr_ty(&match_body).is_unit() {
903                 snippet_body.push(';');
904             }
905         },
906         _ => {
907             // expr_ty(body) == ()
908             if cx.tables.expr_ty(&match_body).is_unit() {
909                 snippet_body.push(';');
910             }
911         },
912     }
913
914     let mut applicability = Applicability::MaybeIncorrect;
915     match arms[0].pat.kind {
916         PatKind::Binding(..) | PatKind::Tuple(_, _) | PatKind::Struct(..) => {
917             // If this match is in a local (`let`) stmt
918             let (target_span, sugg) = if let Some(parent_let_node) = opt_parent_let(cx, ex) {
919                 (
920                     parent_let_node.span,
921                     format!(
922                         "let {} = {};\n{}let {} = {};",
923                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
924                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
925                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
926                         snippet_with_applicability(cx, parent_let_node.pat.span, "..", &mut applicability),
927                         snippet_body
928                     ),
929                 )
930             } else {
931                 (
932                     expr.span,
933                     format!(
934                         "let {} = {};\n{}{}",
935                         snippet_with_applicability(cx, bind_names, "..", &mut applicability),
936                         snippet_with_applicability(cx, matched_vars, "..", &mut applicability),
937                         " ".repeat(indent_of(cx, expr.span).unwrap_or(0)),
938                         snippet_body
939                     ),
940                 )
941             };
942             span_lint_and_sugg(
943                 cx,
944                 MATCH_SINGLE_BINDING,
945                 target_span,
946                 "this match could be written as a `let` statement",
947                 "consider using `let` statement",
948                 sugg,
949                 applicability,
950             );
951         },
952         PatKind::Wild => {
953             span_lint_and_sugg(
954                 cx,
955                 MATCH_SINGLE_BINDING,
956                 expr.span,
957                 "this match could be replaced by its body itself",
958                 "consider using the match body instead",
959                 snippet_body,
960                 Applicability::MachineApplicable,
961             );
962         },
963         _ => (),
964     }
965 }
966
967 /// Returns true if the `ex` match expression is in a local (`let`) statement
968 fn opt_parent_let<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>) -> Option<&'a Local<'a>> {
969     if_chain! {
970         let map = &cx.tcx.hir();
971         if let Some(Node::Expr(parent_arm_expr)) = map.find(map.get_parent_node(ex.hir_id));
972         if let Some(Node::Local(parent_let_expr)) = map.find(map.get_parent_node(parent_arm_expr.hir_id));
973         then {
974             return Some(parent_let_expr);
975         }
976     }
977     None
978 }
979
980 /// Gets all arms that are unbounded `PatRange`s.
981 fn all_ranges<'a, 'tcx>(
982     cx: &LateContext<'a, 'tcx>,
983     arms: &'tcx [Arm<'_>],
984     ty: Ty<'tcx>,
985 ) -> Vec<SpannedRange<Constant>> {
986     arms.iter()
987         .flat_map(|arm| {
988             if let Arm {
989                 ref pat, guard: None, ..
990             } = *arm
991             {
992                 if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind {
993                     let lhs = match lhs {
994                         Some(lhs) => constant(cx, cx.tables, lhs)?.0,
995                         None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?,
996                     };
997                     let rhs = match rhs {
998                         Some(rhs) => constant(cx, cx.tables, rhs)?.0,
999                         None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?,
1000                     };
1001                     let rhs = match range_end {
1002                         RangeEnd::Included => Bound::Included(rhs),
1003                         RangeEnd::Excluded => Bound::Excluded(rhs),
1004                     };
1005                     return Some(SpannedRange {
1006                         span: pat.span,
1007                         node: (lhs, rhs),
1008                     });
1009                 }
1010
1011                 if let PatKind::Lit(ref value) = pat.kind {
1012                     let value = constant(cx, cx.tables, value)?.0;
1013                     return Some(SpannedRange {
1014                         span: pat.span,
1015                         node: (value.clone(), Bound::Included(value)),
1016                     });
1017                 }
1018             }
1019             None
1020         })
1021         .collect()
1022 }
1023
1024 #[derive(Debug, Eq, PartialEq)]
1025 pub struct SpannedRange<T> {
1026     pub span: Span,
1027     pub node: (T, Bound<T>),
1028 }
1029
1030 type TypedRanges = Vec<SpannedRange<u128>>;
1031
1032 /// Gets all `Int` ranges or all `Uint` ranges. Mixed types are an error anyway
1033 /// and other types than
1034 /// `Uint` and `Int` probably don't make sense.
1035 fn type_ranges(ranges: &[SpannedRange<Constant>]) -> TypedRanges {
1036     ranges
1037         .iter()
1038         .filter_map(|range| match range.node {
1039             (Constant::Int(start), Bound::Included(Constant::Int(end))) => Some(SpannedRange {
1040                 span: range.span,
1041                 node: (start, Bound::Included(end)),
1042             }),
1043             (Constant::Int(start), Bound::Excluded(Constant::Int(end))) => Some(SpannedRange {
1044                 span: range.span,
1045                 node: (start, Bound::Excluded(end)),
1046             }),
1047             (Constant::Int(start), Bound::Unbounded) => Some(SpannedRange {
1048                 span: range.span,
1049                 node: (start, Bound::Unbounded),
1050             }),
1051             _ => None,
1052         })
1053         .collect()
1054 }
1055
1056 fn is_unit_expr(expr: &Expr<'_>) -> bool {
1057     match expr.kind {
1058         ExprKind::Tup(ref v) if v.is_empty() => true,
1059         ExprKind::Block(ref b, _) if b.stmts.is_empty() && b.expr.is_none() => true,
1060         _ => false,
1061     }
1062 }
1063
1064 // Checks if arm has the form `None => None`
1065 fn is_none_arm(arm: &Arm<'_>) -> bool {
1066     match arm.pat.kind {
1067         PatKind::Path(ref path) if match_qpath(path, &paths::OPTION_NONE) => true,
1068         _ => false,
1069     }
1070 }
1071
1072 // Checks if arm has the form `Some(ref v) => Some(v)` (checks for `ref` and `ref mut`)
1073 fn is_ref_some_arm(arm: &Arm<'_>) -> Option<BindingAnnotation> {
1074     if_chain! {
1075         if let PatKind::TupleStruct(ref path, ref pats, _) = arm.pat.kind;
1076         if pats.len() == 1 && match_qpath(path, &paths::OPTION_SOME);
1077         if let PatKind::Binding(rb, .., ident, _) = pats[0].kind;
1078         if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
1079         if let ExprKind::Call(ref e, ref args) = remove_blocks(&arm.body).kind;
1080         if let ExprKind::Path(ref some_path) = e.kind;
1081         if match_qpath(some_path, &paths::OPTION_SOME) && args.len() == 1;
1082         if let ExprKind::Path(ref qpath) = args[0].kind;
1083         if let &QPath::Resolved(_, ref path2) = qpath;
1084         if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
1085         then {
1086             return Some(rb)
1087         }
1088     }
1089     None
1090 }
1091
1092 fn has_only_ref_pats(arms: &[Arm<'_>]) -> bool {
1093     let mapped = arms
1094         .iter()
1095         .map(|a| {
1096             match a.pat.kind {
1097                 PatKind::Ref(..) => Some(true), // &-patterns
1098                 PatKind::Wild => Some(false),   // an "anything" wildcard is also fine
1099                 _ => None,                      // any other pattern is not fine
1100             }
1101         })
1102         .collect::<Option<Vec<bool>>>();
1103     // look for Some(v) where there's at least one true element
1104     mapped.map_or(false, |v| v.iter().any(|el| *el))
1105 }
1106
1107 pub fn overlapping<T>(ranges: &[SpannedRange<T>]) -> Option<(&SpannedRange<T>, &SpannedRange<T>)>
1108 where
1109     T: Copy + Ord,
1110 {
1111     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1112     enum Kind<'a, T> {
1113         Start(T, &'a SpannedRange<T>),
1114         End(Bound<T>, &'a SpannedRange<T>),
1115     }
1116
1117     impl<'a, T: Copy> Kind<'a, T> {
1118         fn range(&self) -> &'a SpannedRange<T> {
1119             match *self {
1120                 Kind::Start(_, r) | Kind::End(_, r) => r,
1121             }
1122         }
1123
1124         fn value(self) -> Bound<T> {
1125             match self {
1126                 Kind::Start(t, _) => Bound::Included(t),
1127                 Kind::End(t, _) => t,
1128             }
1129         }
1130     }
1131
1132     impl<'a, T: Copy + Ord> PartialOrd for Kind<'a, T> {
1133         fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1134             Some(self.cmp(other))
1135         }
1136     }
1137
1138     impl<'a, T: Copy + Ord> Ord for Kind<'a, T> {
1139         fn cmp(&self, other: &Self) -> Ordering {
1140             match (self.value(), other.value()) {
1141                 (Bound::Included(a), Bound::Included(b)) | (Bound::Excluded(a), Bound::Excluded(b)) => a.cmp(&b),
1142                 // Range patterns cannot be unbounded (yet)
1143                 (Bound::Unbounded, _) | (_, Bound::Unbounded) => unimplemented!(),
1144                 (Bound::Included(a), Bound::Excluded(b)) => match a.cmp(&b) {
1145                     Ordering::Equal => Ordering::Greater,
1146                     other => other,
1147                 },
1148                 (Bound::Excluded(a), Bound::Included(b)) => match a.cmp(&b) {
1149                     Ordering::Equal => Ordering::Less,
1150                     other => other,
1151                 },
1152             }
1153         }
1154     }
1155
1156     let mut values = Vec::with_capacity(2 * ranges.len());
1157
1158     for r in ranges {
1159         values.push(Kind::Start(r.node.0, r));
1160         values.push(Kind::End(r.node.1, r));
1161     }
1162
1163     values.sort();
1164
1165     for (a, b) in values.iter().zip(values.iter().skip(1)) {
1166         match (a, b) {
1167             (&Kind::Start(_, ra), &Kind::End(_, rb)) => {
1168                 if ra.node != rb.node {
1169                     return Some((ra, rb));
1170                 }
1171             },
1172             (&Kind::End(a, _), &Kind::Start(b, _)) if a != Bound::Included(b) => (),
1173             _ => return Some((a.range(), b.range())),
1174         }
1175     }
1176
1177     None
1178 }