Skip to content

Commit bafba95

Browse files
committed
fix: if_then_some_else_none FP when require type coercion
1 parent 7e2d26f commit bafba95

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

clippy_lints/src/if_then_some_else_none.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ use clippy_utils::msrvs::{self, Msrv};
55
use clippy_utils::source::snippet_with_context;
66
use clippy_utils::sugg::Sugg;
77
use clippy_utils::{
8-
contains_return, higher, is_else_clause, is_in_const_context, is_res_lang_ctor, path_res, peel_blocks,
8+
contains_return, expr_requires_coercion, higher, is_else_clause, is_in_const_context, is_res_lang_ctor, path_res,
9+
peel_blocks,
910
};
1011
use rustc_errors::Applicability;
1112
use rustc_hir::LangItem::{OptionNone, OptionSome};
@@ -92,6 +93,10 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
9293
expr.span,
9394
format!("this could be simplified with `bool::{method_name}`"),
9495
|diag| {
96+
if expr_requires_coercion(cx, then_expr) {
97+
return;
98+
}
99+
95100
let mut app = Applicability::MachineApplicable;
96101
let cond_snip = Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "[condition]", &mut app)
97102
.maybe_paren()
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//@no-rustfix
2+
3+
#![warn(clippy::if_then_some_else_none)]
4+
#![allow(clippy::manual_is_multiple_of)]
5+
6+
mod issue15257 {
7+
#[derive(Default)]
8+
pub struct Foo {}
9+
pub trait Bar {}
10+
impl Bar for Foo {}
11+
12+
fn maybe_get_bar(i: u32) -> Option<Box<dyn Bar>> {
13+
if i % 2 == 0 {
14+
//~^ if_then_some_else_none
15+
Some(Box::new(Foo::default()))
16+
} else {
17+
None
18+
}
19+
}
20+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: this could be simplified with `bool::then`
2+
--> tests/ui/if_then_some_else_none_unfixable.rs:13:9
3+
|
4+
LL | / if i % 2 == 0 {
5+
LL | |
6+
LL | | Some(Box::new(Foo::default()))
7+
LL | | } else {
8+
LL | | None
9+
LL | | }
10+
| |_________^
11+
|
12+
= note: `-D clippy::if-then-some-else-none` implied by `-D warnings`
13+
= help: to override `-D warnings` add `#[allow(clippy::if_then_some_else_none)]`
14+
15+
error: aborting due to 1 previous error
16+

0 commit comments

Comments
 (0)