Skip to content

Commit 89aeed1

Browse files
authored
Fix if_then_some_else_none FP when encountering await codes (#16178)
changelog: Fix FP of [`if_then_some_else_none`] when the `then` block contains `await` codes. That is because `bool:then` doesn't work with await code. Closes: #16176
2 parents 9e3e964 + 6159c19 commit 89aeed1

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

clippy_lints/src/if_then_some_else_none.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@ use clippy_utils::eager_or_lazy::switch_to_eager_eval;
44
use clippy_utils::msrvs::{self, Msrv};
55
use clippy_utils::source::{snippet_with_applicability, snippet_with_context, walk_span_to_context};
66
use clippy_utils::sugg::Sugg;
7+
use clippy_utils::visitors::for_each_expr_without_closures;
78
use clippy_utils::{
8-
as_some_expr, contains_return, expr_adjustment_requires_coercion, higher, is_else_clause, is_in_const_context,
9-
is_none_expr, peel_blocks, sym,
9+
as_some_expr, expr_adjustment_requires_coercion, higher, is_else_clause, is_in_const_context, is_none_expr,
10+
peel_blocks, sym,
1011
};
12+
use core::ops::ControlFlow;
1113
use rustc_errors::Applicability;
1214
use rustc_hir::{Expr, ExprKind};
1315
use rustc_lint::{LateContext, LateLintPass};
@@ -76,8 +78,14 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
7678
&& !is_else_clause(cx.tcx, expr)
7779
&& !is_in_const_context(cx)
7880
&& self.msrv.meets(cx, msrvs::BOOL_THEN)
79-
&& !contains_return(then_block.stmts)
80-
&& then_block.expr.is_none_or(|expr| !contains_return(expr))
81+
&& for_each_expr_without_closures(then_block, |e| {
82+
if matches!(e.kind, ExprKind::Ret(..) | ExprKind::Yield(..)) {
83+
ControlFlow::Break(())
84+
} else {
85+
ControlFlow::Continue(())
86+
}
87+
})
88+
.is_none()
8189
{
8290
let method_name = if switch_to_eager_eval(cx, expr) && self.msrv.meets(cx, msrvs::BOOL_THEN_SOME) {
8391
sym::then_some

tests/ui/if_then_some_else_none.fixed

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,13 @@ mod issue15770 {
218218
Ok(())
219219
}
220220
}
221+
222+
mod issue16176 {
223+
pub async fn foo() -> u32 {
224+
todo!()
225+
}
226+
227+
pub async fn bar(cond: bool) -> Option<u32> {
228+
if cond { Some(foo().await) } else { None } // OK
229+
}
230+
}

tests/ui/if_then_some_else_none.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,13 @@ mod issue15770 {
274274
Ok(())
275275
}
276276
}
277+
278+
mod issue16176 {
279+
pub async fn foo() -> u32 {
280+
todo!()
281+
}
282+
283+
pub async fn bar(cond: bool) -> Option<u32> {
284+
if cond { Some(foo().await) } else { None } // OK
285+
}
286+
}

0 commit comments

Comments
 (0)