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