Skip to content

Commit d6c707d

Browse files
committed
Auto merge of #7980 - dswij:7870, r=xFrednet
Fix FP on `if_then_some_else_none` when there is early return closes #7870 changelog: [`if_then_some_else_none`] now does not fire when there is early return
2 parents 57a8804 + ec3d1c8 commit d6c707d

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

clippy_lints/src/if_then_some_else_none.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use clippy_utils::diagnostics::span_lint_and_help;
22
use clippy_utils::source::snippet_with_macro_callsite;
3-
use clippy_utils::{higher, is_else_clause, is_lang_ctor, meets_msrv, msrvs};
3+
use clippy_utils::{contains_return, higher, is_else_clause, is_lang_ctor, meets_msrv, msrvs};
44
use if_chain::if_chain;
55
use rustc_hir::LangItem::{OptionNone, OptionSome};
6-
use rustc_hir::{Expr, ExprKind};
6+
use rustc_hir::{Expr, ExprKind, Stmt, StmtKind};
77
use rustc_lint::{LateContext, LateLintPass, LintContext};
88
use rustc_middle::lint::in_external_macro;
99
use rustc_semver::RustcVersion;
@@ -82,6 +82,7 @@ impl LateLintPass<'_> for IfThenSomeElseNone {
8282
if let Some(els_expr) = els_block.expr;
8383
if let ExprKind::Path(ref qpath) = els_expr.kind;
8484
if is_lang_ctor(cx, qpath, OptionNone);
85+
if !stmts_contains_early_return(then_block.stmts);
8586
then {
8687
let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
8788
let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
@@ -114,3 +115,11 @@ impl LateLintPass<'_> for IfThenSomeElseNone {
114115

115116
extract_msrv_attr!(LateContext);
116117
}
118+
119+
fn stmts_contains_early_return(stmts: &[Stmt<'_>]) -> bool {
120+
stmts.iter().any(|stmt| {
121+
let Stmt { kind: StmtKind::Semi(e), .. } = stmt else { return false };
122+
123+
contains_return(e)
124+
})
125+
}

tests/ui/if_then_some_else_none.rs

+11
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,14 @@ fn into_some<T>(v: T) -> Option<T> {
102102
fn into_none<T>() -> Option<T> {
103103
None
104104
}
105+
106+
// Should not warn
107+
fn f(b: bool, v: Option<()>) -> Option<()> {
108+
if b {
109+
v?; // This is a potential early return, is not equivalent with `bool::then`
110+
111+
Some(())
112+
} else {
113+
None
114+
}
115+
}

0 commit comments

Comments
 (0)