1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use super::utils::{get_arg_name, match_var, remove_blocks, snippet_with_applicability, span_lint_and_sugg};
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_errors::Applicability;
16 use if_chain::if_chain;
18 /// **What it does:** Checks for matches being used to destructure a single-variant enum
19 /// or tuple struct where a `let` will suffice.
21 /// **Why is this bad?** Just readability – `let` doesn't nest, whereas a `match` does.
23 /// **Known problems:** None.
31 /// let wrapper = Wrapper::Data(42);
33 /// let data = match wrapper {
34 /// Wrapper::Data(i) => i,
38 /// The correct use would be:
44 /// let wrapper = Wrapper::Data(42);
45 /// let Wrapper::Data(data) = wrapper;
47 declare_clippy_lint! {
48 pub INFALLIBLE_DESTRUCTURING_MATCH,
50 "a match statement with a single infallible arm instead of a `let`"
53 #[derive(Copy, Clone, Default)]
56 impl LintPass for Pass {
57 fn get_lints(&self) -> LintArray {
58 lint_array!(INFALLIBLE_DESTRUCTURING_MATCH)
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
63 fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local) {
65 if let Some(ref expr) = local.init;
66 if let ExprKind::Match(ref target, ref arms, MatchSource::Normal) = expr.node;
67 if arms.len() == 1 && arms[0].pats.len() == 1 && arms[0].guard.is_none();
68 if let PatKind::TupleStruct(QPath::Resolved(None, ref variant_name), ref args, _) = arms[0].pats[0].node;
70 if let Some(arg) = get_arg_name(&args[0]);
71 let body = remove_blocks(&arms[0].body);
72 if match_var(body, arg);
75 let mut applicability = Applicability::MachineApplicable;
78 INFALLIBLE_DESTRUCTURING_MATCH,
80 "you seem to be trying to use match to destructure a single infallible pattern. \
81 Consider using `let`",
85 snippet_with_applicability(cx, variant_name.span, "..", &mut applicability),
86 snippet_with_applicability(cx, local.pat.span, "..", &mut applicability),
87 snippet_with_applicability(cx, target.span, "..", &mut applicability),