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