Skip to content

Commit

Permalink
change the applicability of obfuscated_if_else depending on whether…
Browse files Browse the repository at this point in the history
… the original code can have side effects
  • Loading branch information
lapla-cogito committed Jan 22, 2025
1 parent 396de57 commit 8e31f2f
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
7 changes: 6 additions & 1 deletion clippy_lints/src/methods/obfuscated_if_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ pub(super) fn check<'tcx>(
let recv_ty = cx.typeck_results().expr_ty(then_recv);

if recv_ty.is_bool() {
let mut applicability = Applicability::MachineApplicable;
let mut applicability = if then_arg.can_have_side_effects() || unwrap_arg.can_have_side_effects() {
Applicability::MaybeIncorrect
} else {
Applicability::MachineApplicable
};

let sugg = format!(
"if {} {{ {} }} else {{ {} }}",
snippet_with_applicability(cx, then_recv.span, "..", &mut applicability),
Expand Down
5 changes: 5 additions & 0 deletions tests/ui/obfuscated_if_else.fixed
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
#![warn(clippy::obfuscated_if_else)]
#![allow(clippy::unit_arg)]

fn main() {
if true { "a" } else { "b" };

let mut a = 0;
if true { a += 1 } else { () };
if true { () } else { a += 2 };
}
5 changes: 5 additions & 0 deletions tests/ui/obfuscated_if_else.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
#![warn(clippy::obfuscated_if_else)]
#![allow(clippy::unit_arg)]

fn main() {
true.then_some("a").unwrap_or("b");

let mut a = 0;
true.then_some(a += 1).unwrap_or(());
true.then_some(()).unwrap_or(a += 2);
}
16 changes: 14 additions & 2 deletions tests/ui/obfuscated_if_else.stderr
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
error: use of `.then_some(..).unwrap_or(..)` can be written more clearly with `if .. else ..`
--> tests/ui/obfuscated_if_else.rs:4:5
--> tests/ui/obfuscated_if_else.rs:5:5
|
LL | true.then_some("a").unwrap_or("b");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `if true { "a" } else { "b" }`
|
= note: `-D clippy::obfuscated-if-else` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::obfuscated_if_else)]`

error: aborting due to 1 previous error
error: use of `.then_some(..).unwrap_or(..)` can be written more clearly with `if .. else ..`
--> tests/ui/obfuscated_if_else.rs:8:5
|
LL | true.then_some(a += 1).unwrap_or(());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `if true { a += 1 } else { () }`

error: use of `.then_some(..).unwrap_or(..)` can be written more clearly with `if .. else ..`
--> tests/ui/obfuscated_if_else.rs:9:5
|
LL | true.then_some(()).unwrap_or(a += 2);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `if true { () } else { a += 2 }`

error: aborting due to 3 previous errors

0 comments on commit 8e31f2f

Please sign in to comment.