]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/matches/needless_match.rs
Auto merge of #8619 - pitaj:fix-6973, r=giraffate
[rust.git] / clippy_lints / src / matches / needless_match.rs
1 use super::NEEDLESS_MATCH;
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::ty::{is_type_diagnostic_item, same_type_and_consts};
5 use clippy_utils::{
6     eq_expr_value, get_parent_expr_for_hir, get_parent_node, higher, is_else_clause, is_lang_ctor, over,
7     peel_blocks_with_stmt,
8 };
9 use rustc_errors::Applicability;
10 use rustc_hir::LangItem::OptionNone;
11 use rustc_hir::{Arm, BindingAnnotation, Expr, ExprKind, FnRetTy, Node, Pat, PatKind, Path, QPath};
12 use rustc_lint::LateContext;
13 use rustc_span::sym;
14 use rustc_typeck::hir_ty_to_ty;
15
16 pub(crate) fn check_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
17     if arms.len() > 1 && expr_ty_matches_p_ty(cx, ex, expr) && check_all_arms(cx, ex, arms) {
18         let mut applicability = Applicability::MachineApplicable;
19         span_lint_and_sugg(
20             cx,
21             NEEDLESS_MATCH,
22             expr.span,
23             "this match expression is unnecessary",
24             "replace it with",
25             snippet_with_applicability(cx, ex.span, "..", &mut applicability).to_string(),
26             applicability,
27         );
28     }
29 }
30
31 /// Check for nop `if let` expression that assembled as unnecessary match
32 ///
33 /// ```rust,ignore
34 /// if let Some(a) = option {
35 ///     Some(a)
36 /// } else {
37 ///     None
38 /// }
39 /// ```
40 /// OR
41 /// ```rust,ignore
42 /// if let SomeEnum::A = some_enum {
43 ///     SomeEnum::A
44 /// } else if let SomeEnum::B = some_enum {
45 ///     SomeEnum::B
46 /// } else {
47 ///     some_enum
48 /// }
49 /// ```
50 pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>) {
51     if let Some(ref if_let) = higher::IfLet::hir(cx, ex) {
52         if !is_else_clause(cx.tcx, ex) && expr_ty_matches_p_ty(cx, if_let.let_expr, ex) && check_if_let(cx, if_let) {
53             let mut applicability = Applicability::MachineApplicable;
54             span_lint_and_sugg(
55                 cx,
56                 NEEDLESS_MATCH,
57                 ex.span,
58                 "this if-let expression is unnecessary",
59                 "replace it with",
60                 snippet_with_applicability(cx, if_let.let_expr.span, "..", &mut applicability).to_string(),
61                 applicability,
62             );
63         }
64     }
65 }
66
67 fn check_all_arms(cx: &LateContext<'_>, match_expr: &Expr<'_>, arms: &[Arm<'_>]) -> bool {
68     for arm in arms {
69         let arm_expr = peel_blocks_with_stmt(arm.body);
70         if let PatKind::Wild = arm.pat.kind {
71             return eq_expr_value(cx, match_expr, strip_return(arm_expr));
72         } else if !pat_same_as_expr(arm.pat, arm_expr) {
73             return false;
74         }
75     }
76
77     true
78 }
79
80 fn check_if_let(cx: &LateContext<'_>, if_let: &higher::IfLet<'_>) -> bool {
81     if let Some(if_else) = if_let.if_else {
82         if !pat_same_as_expr(if_let.let_pat, peel_blocks_with_stmt(if_let.if_then)) {
83             return false;
84         }
85
86         // Recurrsively check for each `else if let` phrase,
87         if let Some(ref nested_if_let) = higher::IfLet::hir(cx, if_else) {
88             return check_if_let(cx, nested_if_let);
89         }
90
91         if matches!(if_else.kind, ExprKind::Block(..)) {
92             let else_expr = peel_blocks_with_stmt(if_else);
93             if matches!(else_expr.kind, ExprKind::Block(..)) {
94                 return false;
95             }
96             let ret = strip_return(else_expr);
97             let let_expr_ty = cx.typeck_results().expr_ty(if_let.let_expr);
98             if is_type_diagnostic_item(cx, let_expr_ty, sym::Option) {
99                 if let ExprKind::Path(ref qpath) = ret.kind {
100                     return is_lang_ctor(cx, qpath, OptionNone) || eq_expr_value(cx, if_let.let_expr, ret);
101                 }
102                 return true;
103             }
104             return eq_expr_value(cx, if_let.let_expr, ret);
105         }
106     }
107
108     false
109 }
110
111 /// Strip `return` keyword if the expression type is `ExprKind::Ret`.
112 fn strip_return<'hir>(expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> {
113     if let ExprKind::Ret(Some(ret)) = expr.kind {
114         ret
115     } else {
116         expr
117     }
118 }
119
120 /// Manually check for coercion casting by checking if the type of the match operand or let expr
121 /// differs with the assigned local variable or the funtion return type.
122 fn expr_ty_matches_p_ty(cx: &LateContext<'_>, expr: &Expr<'_>, p_expr: &Expr<'_>) -> bool {
123     if let Some(p_node) = get_parent_node(cx.tcx, p_expr.hir_id) {
124         match p_node {
125             // Compare match_expr ty with local in `let local = match match_expr {..}`
126             Node::Local(local) => {
127                 let results = cx.typeck_results();
128                 return same_type_and_consts(results.node_type(local.hir_id), results.expr_ty(expr));
129             },
130             // compare match_expr ty with RetTy in `fn foo() -> RetTy`
131             Node::Item(..) => {
132                 if let Some(fn_decl) = p_node.fn_decl() {
133                     if let FnRetTy::Return(ret_ty) = fn_decl.output {
134                         return same_type_and_consts(hir_ty_to_ty(cx.tcx, ret_ty), cx.typeck_results().expr_ty(expr));
135                     }
136                 }
137             },
138             // check the parent expr for this whole block `{ match match_expr {..} }`
139             Node::Block(block) => {
140                 if let Some(block_parent_expr) = get_parent_expr_for_hir(cx, block.hir_id) {
141                     return expr_ty_matches_p_ty(cx, expr, block_parent_expr);
142                 }
143             },
144             // recursively call on `if xxx {..}` etc.
145             Node::Expr(p_expr) => {
146                 return expr_ty_matches_p_ty(cx, expr, p_expr);
147             },
148             _ => {},
149         }
150     }
151     false
152 }
153
154 fn pat_same_as_expr(pat: &Pat<'_>, expr: &Expr<'_>) -> bool {
155     let expr = strip_return(expr);
156     match (&pat.kind, &expr.kind) {
157         // Example: `Some(val) => Some(val)`
158         (PatKind::TupleStruct(QPath::Resolved(_, path), tuple_params, _), ExprKind::Call(call_expr, call_params)) => {
159             if let ExprKind::Path(QPath::Resolved(_, call_path)) = call_expr.kind {
160                 return over(path.segments, call_path.segments, |pat_seg, call_seg| {
161                     pat_seg.ident.name == call_seg.ident.name
162                 }) && same_non_ref_symbols(tuple_params, call_params);
163             }
164         },
165         // Example: `val => val`
166         (
167             PatKind::Binding(annot, _, pat_ident, _),
168             ExprKind::Path(QPath::Resolved(
169                 _,
170                 Path {
171                     segments: [first_seg, ..],
172                     ..
173                 },
174             )),
175         ) => {
176             return !matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut)
177                 && pat_ident.name == first_seg.ident.name;
178         },
179         // Example: `Custom::TypeA => Custom::TypeB`, or `None => None`
180         (PatKind::Path(QPath::Resolved(_, p_path)), ExprKind::Path(QPath::Resolved(_, e_path))) => {
181             return over(p_path.segments, e_path.segments, |p_seg, e_seg| {
182                 p_seg.ident.name == e_seg.ident.name
183             });
184         },
185         // Example: `5 => 5`
186         (PatKind::Lit(pat_lit_expr), ExprKind::Lit(expr_spanned)) => {
187             if let ExprKind::Lit(pat_spanned) = &pat_lit_expr.kind {
188                 return pat_spanned.node == expr_spanned.node;
189             }
190         },
191         _ => {},
192     }
193
194     false
195 }
196
197 fn same_non_ref_symbols(pats: &[Pat<'_>], exprs: &[Expr<'_>]) -> bool {
198     if pats.len() != exprs.len() {
199         return false;
200     }
201
202     for i in 0..pats.len() {
203         if !pat_same_as_expr(&pats[i], &exprs[i]) {
204             return false;
205         }
206     }
207
208     true
209 }