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