Extend question_mark to cover else if (#16455)

Closes rust-lang/rust-clippy#16429

changelog: [`question_mark`] enhance to cover `else if`
This commit is contained in:
Jason Newcomb
2026-02-03 01:07:28 +00:00
committed by GitHub
4 changed files with 42 additions and 3 deletions
+6 -2
View File
@@ -474,7 +474,6 @@ fn check_if_let_some_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr:
if_else,
..
}) = higher::IfLet::hir(cx, expr)
&& !is_else_clause(cx.tcx, expr)
&& let PatKind::TupleStruct(ref path1, [field], ddpos) = let_pat.kind
&& ddpos.as_opt_usize().is_none()
&& let PatKind::Binding(BindingMode(by_ref, _), bind_id, ident, None) = field.kind
@@ -509,10 +508,15 @@ fn check_if_let_some_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr:
ByRef::Yes(_, Mutability::Not) => ".as_ref()",
ByRef::No => "",
};
let sugg = format!(
let mut sugg = format!(
"{receiver_str}{method_call_str}?{}",
if requires_semi { ";" } else { "" }
);
if is_else_clause(cx.tcx, expr) {
sugg = format!("{{ {sugg} }}");
}
span_lint_and_sugg(
cx,
QUESTION_MARK,
+9
View File
@@ -515,3 +515,12 @@ fn wrongly_unmangled_macros() -> Option<i32> {
test_expr!(42)?;
test_expr!(42)
}
fn issue16429(b: i32) -> Option<i32> {
let a = Some(5);
let _ = if b == 1 {
b
} else { a? };
Some(0)
}
+14
View File
@@ -635,3 +635,17 @@ macro_rules! test_expr {
}
test_expr!(42)
}
fn issue16429(b: i32) -> Option<i32> {
let a = Some(5);
let _ = if b == 1 {
b
} else if let Some(x) = a {
//~^ question_mark
x
} else {
return None;
};
Some(0)
}
+13 -1
View File
@@ -350,5 +350,17 @@ LL | | return None;
LL | | }
| |_____^ help: replace it with: `test_expr!(42)?;`
error: aborting due to 37 previous errors
error: this block may be rewritten with the `?` operator
--> tests/ui/question_mark.rs:643:12
|
LL | } else if let Some(x) = a {
| ____________^
LL | |
LL | | x
LL | | } else {
LL | | return None;
LL | | };
| |_____^ help: replace it with: `{ a? }`
error: aborting due to 38 previous errors