Skip to content

Commit 45084ee

Browse files
committed
give up when gurad has side effects
1 parent 459821b commit 45084ee

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

clippy_lints/src/matches/needless_match.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use clippy_utils::{
88
};
99
use rustc_errors::Applicability;
1010
use rustc_hir::LangItem::OptionNone;
11-
use rustc_hir::{Arm, BindingAnnotation, Expr, ExprKind, FnRetTy, Node, Pat, PatKind, Path, QPath};
11+
use rustc_hir::{Arm, BindingAnnotation, Expr, ExprKind, FnRetTy, Guard, Node, Pat, PatKind, Path, QPath};
1212
use rustc_lint::LateContext;
1313
use rustc_span::sym;
1414
use rustc_typeck::hir_ty_to_ty;
@@ -65,6 +65,22 @@ pub(crate) fn check_if_let<'tcx>(cx: &LateContext<'tcx>, ex: &Expr<'_>, if_let:
6565
fn check_all_arms(cx: &LateContext<'_>, match_expr: &Expr<'_>, arms: &[Arm<'_>]) -> bool {
6666
for arm in arms {
6767
let arm_expr = peel_blocks_with_stmt(arm.body);
68+
69+
if let Some(guard_expr) = &arm.guard {
70+
match guard_expr {
71+
// gives up if `pat if expr` can have side effects
72+
Guard::If(if_cond) => {
73+
if if_cond.can_have_side_effects() {
74+
return false;
75+
}
76+
},
77+
// gives up `pat if let ...` arm
78+
Guard::IfLet(_) => {
79+
return false;
80+
},
81+
};
82+
}
83+
6884
if let PatKind::Wild = arm.pat.kind {
6985
if !eq_expr_value(cx, match_expr, strip_return(arm_expr)) {
7086
return false;

tests/ui/needless_match.fixed

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ impl Tr for Result<i32, i32> {
209209

210210
mod issue9084 {
211211
fn wildcard_if() {
212-
let some_bool = true;
212+
let mut some_bool = true;
213213
let e = Some(1);
214214

215215
// should lint
@@ -230,6 +230,19 @@ mod issue9084 {
230230
_ if some_bool => e,
231231
_ => e,
232232
};
233+
234+
// should not lint (guard has side effects)
235+
let _ = match e {
236+
Some(i) => Some(i),
237+
_ if {
238+
some_bool = false;
239+
some_bool
240+
} =>
241+
{
242+
e
243+
},
244+
_ => e,
245+
};
233246
}
234247
}
235248

tests/ui/needless_match.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ impl Tr for Result<i32, i32> {
246246

247247
mod issue9084 {
248248
fn wildcard_if() {
249-
let some_bool = true;
249+
let mut some_bool = true;
250250
let e = Some(1);
251251

252252
// should lint
@@ -274,6 +274,19 @@ mod issue9084 {
274274
_ if some_bool => e,
275275
_ => e,
276276
};
277+
278+
// should not lint (guard has side effects)
279+
let _ = match e {
280+
Some(i) => Some(i),
281+
_ if {
282+
some_bool = false;
283+
some_bool
284+
} =>
285+
{
286+
e
287+
},
288+
_ => e,
289+
};
277290
}
278291
}
279292

0 commit comments

Comments
 (0)