-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathneedless_match.rs
More file actions
221 lines (205 loc) · 7.59 KB
/
needless_match.rs
File metadata and controls
221 lines (205 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use super::NEEDLESS_MATCH;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::res::{MaybeDef, MaybeQPath};
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::same_type_modulo_regions;
use clippy_utils::{
SpanlessEq, eq_expr_value, get_parent_expr_for_hir, higher, is_else_clause, over, peel_blocks_with_stmt,
};
use rustc_errors::Applicability;
use rustc_hir::LangItem::OptionNone;
use rustc_hir::{
Arm, BindingMode, ByRef, Expr, ExprKind, ItemKind, Node, Pat, PatExpr, PatExprKind, PatKind, Path, QPath,
};
use rustc_lint::LateContext;
use rustc_span::{SyntaxContext, sym};
pub(crate) fn check_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) {
if arms.len() > 1 && expr_ty_matches_p_ty(cx, ex, expr) && check_all_arms(cx, expr.span.ctxt(), ex, arms) {
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
NEEDLESS_MATCH,
expr.span,
"this match expression is unnecessary",
"replace it with",
snippet_with_applicability(cx, ex.span, "..", &mut applicability).to_string(),
applicability,
);
}
}
/// Check for nop `if let` expression that assembled as unnecessary match
///
/// ```rust,ignore
/// if let Some(a) = option {
/// Some(a)
/// } else {
/// None
/// }
/// ```
/// OR
/// ```rust,ignore
/// if let SomeEnum::A = some_enum {
/// SomeEnum::A
/// } else if let SomeEnum::B = some_enum {
/// SomeEnum::B
/// } else {
/// some_enum
/// }
/// ```
pub(crate) fn check_if_let<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'_>, if_let: &higher::IfLet<'tcx>) {
if !is_else_clause(cx.tcx, ex)
&& expr_ty_matches_p_ty(cx, if_let.let_expr, ex)
&& check_if_let_inner(cx, ex.span.ctxt(), if_let)
{
let mut applicability = Applicability::MachineApplicable;
span_lint_and_sugg(
cx,
NEEDLESS_MATCH,
ex.span,
"this if-let expression is unnecessary",
"replace it with",
snippet_with_applicability(cx, if_let.let_expr.span, "..", &mut applicability).to_string(),
applicability,
);
}
}
fn check_all_arms(cx: &LateContext<'_>, ctxt: SyntaxContext, match_expr: &Expr<'_>, arms: &[Arm<'_>]) -> bool {
for arm in arms {
let arm_expr = peel_blocks_with_stmt(arm.body);
if let Some(guard_expr) = &arm.guard
&& guard_expr.can_have_side_effects()
{
return false;
}
if let PatKind::Wild = arm.pat.kind {
if !eq_expr_value(cx, ctxt, match_expr, arm_expr) {
return false;
}
} else if !pat_same_as_expr(arm.pat, arm_expr) {
return false;
}
}
true
}
fn check_if_let_inner(cx: &LateContext<'_>, ctxt: SyntaxContext, if_let: &higher::IfLet<'_>) -> bool {
if let Some(if_else) = if_let.if_else {
if !pat_same_as_expr(if_let.let_pat, peel_blocks_with_stmt(if_let.if_then)) {
return false;
}
// Recursively check for each `else if let` phrase,
if let Some(ref nested_if_let) = higher::IfLet::hir(cx, if_else)
&& SpanlessEq::new(cx).eq_expr(ctxt, nested_if_let.let_expr, if_let.let_expr)
{
return check_if_let_inner(cx, ctxt, nested_if_let);
}
if matches!(if_else.kind, ExprKind::Block(..)) {
let else_expr = peel_blocks_with_stmt(if_else);
if matches!(else_expr.kind, ExprKind::Block(..)) {
return false;
}
let let_expr_ty = cx.typeck_results().expr_ty(if_let.let_expr);
if let_expr_ty.is_diag_item(cx, sym::Option) {
return else_expr.res(cx).ctor_parent(cx).is_lang_item(cx, OptionNone)
|| eq_expr_value(cx, ctxt, if_let.let_expr, else_expr);
}
return eq_expr_value(cx, ctxt, if_let.let_expr, else_expr);
}
}
false
}
/// Manually check for coercion casting by checking if the type of the match operand or let expr
/// differs with the assigned local variable or the function return type.
fn expr_ty_matches_p_ty(cx: &LateContext<'_>, expr: &Expr<'_>, p_expr: &Expr<'_>) -> bool {
match cx.tcx.parent_hir_node(p_expr.hir_id) {
// Compare match_expr ty with local in `let local = match match_expr {..}`
Node::LetStmt(local) => {
let results = cx.typeck_results();
return same_type_modulo_regions(results.node_type(local.hir_id), results.expr_ty(expr));
},
// compare match_expr ty with RetTy in `fn foo() -> RetTy`
Node::Item(item) => {
if let ItemKind::Fn { .. } = item.kind {
let output = cx
.tcx
.fn_sig(item.owner_id)
.instantiate_identity()
.skip_norm_wip()
.output()
.skip_binder();
return same_type_modulo_regions(output, cx.typeck_results().expr_ty(expr));
}
},
// check the parent expr for this whole block `{ match match_expr {..} }`
Node::Block(block) => {
if let Some(block_parent_expr) = get_parent_expr_for_hir(cx, block.hir_id) {
return expr_ty_matches_p_ty(cx, expr, block_parent_expr);
}
},
// recursively call on `if xxx {..}` etc.
Node::Expr(p_expr) => {
return expr_ty_matches_p_ty(cx, expr, p_expr);
},
_ => {},
}
false
}
fn pat_same_as_expr(pat: &Pat<'_>, expr: &Expr<'_>) -> bool {
match (&pat.kind, &expr.kind) {
// Example: `Some(val) => Some(val)`
(PatKind::TupleStruct(QPath::Resolved(_, path), tuple_params, _), ExprKind::Call(call_expr, call_params)) => {
if let ExprKind::Path(QPath::Resolved(_, call_path)) = call_expr.kind {
return over(path.segments, call_path.segments, |pat_seg, call_seg| {
pat_seg.ident.name == call_seg.ident.name
}) && same_non_ref_symbols(tuple_params, call_params);
}
},
// Example: `val => val`
(
PatKind::Binding(annot, _, pat_ident, _),
ExprKind::Path(QPath::Resolved(
_,
Path {
segments: [first_seg, ..],
..
},
)),
) => {
return !matches!(annot, BindingMode(ByRef::Yes(..), _)) && pat_ident.name == first_seg.ident.name;
},
// Example: `Custom::TypeA => Custom::TypeB`, or `None => None`
(
PatKind::Expr(PatExpr {
kind: PatExprKind::Path(QPath::Resolved(_, p_path)),
..
}),
ExprKind::Path(QPath::Resolved(_, e_path)),
) => {
return over(p_path.segments, e_path.segments, |p_seg, e_seg| {
p_seg.ident.name == e_seg.ident.name
});
},
// Example: `5 => 5`
(PatKind::Expr(pat_expr_expr), ExprKind::Lit(expr_spanned)) => {
if let PatExprKind::Lit {
lit: pat_spanned,
negated: false,
} = &pat_expr_expr.kind
{
return pat_spanned.node == expr_spanned.node;
}
},
_ => {},
}
false
}
fn same_non_ref_symbols(pats: &[Pat<'_>], exprs: &[Expr<'_>]) -> bool {
if pats.len() != exprs.len() {
return false;
}
for i in 0..pats.len() {
if !pat_same_as_expr(&pats[i], &exprs[i]) {
return false;
}
}
true
}