]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/infallible_destructuring_match.rs
Merge pull request #2977 from flip1995/tool_lints
[rust.git] / clippy_lints / src / infallible_destructuring_match.rs
1 use super::utils::{get_arg_name, match_var, remove_blocks, snippet, span_lint_and_sugg};
2 use rustc::hir::*;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5 use if_chain::if_chain;
6
7 /// **What it does:** Checks for matches being used to destructure a single-variant enum
8 /// or tuple struct where a `let` will suffice.
9 ///
10 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// enum Wrapper {
17 ///     Data(i32),
18 /// }
19 ///
20 /// let wrapper = Wrapper::Data(42);
21 ///
22 /// let data = match wrapper {
23 ///     Wrapper::Data(i) => i,
24 /// };
25 /// ```
26 ///
27 /// The correct use would be:
28 /// ```rust
29 /// enum Wrapper {
30 ///     Data(i32),
31 /// }
32 ///
33 /// let wrapper = Wrapper::Data(42);
34 /// let Wrapper::Data(data) = wrapper;
35 /// ```
36 declare_clippy_lint! {
37     pub INFALLIBLE_DESTRUCTURING_MATCH,
38     style,
39     "a match statement with a single infallible arm instead of a `let`"
40 }
41
42 #[derive(Copy, Clone, Default)]
43 pub struct Pass;
44
45 impl LintPass for Pass {
46     fn get_lints(&self) -> LintArray {
47         lint_array!(INFALLIBLE_DESTRUCTURING_MATCH)
48     }
49 }
50
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
52     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
53         if_chain! {
54             if let Some(ref expr) = local.init;
55             if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.node;
56             if arms.len() == 1 && arms[0].pats.len() == 1 && arms[0].guard.is_none();
57             if let PatKind::TupleStruct(QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pats[0].node;
58             if args.len() == 1;
59             if let Some(arg) = get_arg_name(&args[0]);
60             let body = remove_blocks(&arms[0].body);
61             if match_var(body, arg);
62
63             then {
64                 span_lint_and_sugg(
65                     cx,
66                     INFALLIBLE_DESTRUCTURING_MATCH,
67                     local.span,
68                     "you seem to be trying to use match to destructure a single infallible pattern. \
69                      Consider using `let`",
70                     "try this",
71                     format!(
72                         "let {}({}) = {};",
73                         snippet(cx, variant_name.span, ".."),
74                         snippet(cx, local.pat.span, ".."),
75                         snippet(cx, target.span, ".."),
76                     ),
77                 );
78             }
79         }
80     }
81 }