fix: question_mark suggestion caused error

This commit is contained in:
irelaxcn
2026-03-02 00:34:09 +08:00
parent e492d02285
commit fd8bb21676
4 changed files with 55 additions and 3 deletions
+3 -2
View File
@@ -501,7 +501,8 @@ fn check_if_let_some_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr:
let mut applicability = Applicability::MachineApplicable;
let receiver_str = snippet_with_applicability(cx, let_expr.span, "..", &mut applicability);
let requires_semi = matches!(cx.tcx.parent_hir_node(expr.hir_id), Node::Stmt(_));
let parent = cx.tcx.parent_hir_node(expr.hir_id);
let requires_semi = matches!(parent, Node::Stmt(_)) || cx.typeck_results().expr_ty(expr).is_unit();
let method_call_str = match by_ref {
ByRef::Yes(_, Mutability::Mut) => ".as_mut()",
ByRef::Yes(_, Mutability::Not) => ".as_ref()",
@@ -512,7 +513,7 @@ fn check_if_let_some_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr:
"{receiver_str}{method_call_str}?{}",
if requires_semi { ";" } else { "" }
);
if is_else_clause(cx.tcx, expr) {
if is_else_clause(cx.tcx, expr) || (requires_semi && !matches!(parent, Node::Stmt(_) | Node::Block(_))) {
sugg = format!("{{ {sugg} }}");
}
+13
View File
@@ -524,3 +524,16 @@ fn issue16429(b: i32) -> Option<i32> {
Some(0)
}
fn issue16654() -> Result<(), i32> {
let result = func_returning_result();
#[allow(clippy::collapsible_if)]
if true {
result?;
}
_ = [{ result?; }];
Ok(())
}
+19
View File
@@ -649,3 +649,22 @@ fn issue16429(b: i32) -> Option<i32> {
Some(0)
}
fn issue16654() -> Result<(), i32> {
let result = func_returning_result();
#[allow(clippy::collapsible_if)]
if true {
if let Err(err) = result {
//~^ question_mark
return Err(err);
}
}
_ = [if let Err(err) = result {
//~^ question_mark
return Err(err);
}];
Ok(())
}
+20 -1
View File
@@ -362,5 +362,24 @@ LL | | return None;
LL | | };
| |_____^ help: replace it with: `{ a? }`
error: aborting due to 38 previous errors
error: this block may be rewritten with the `?` operator
--> tests/ui/question_mark.rs:658:9
|
LL | / if let Err(err) = result {
LL | |
LL | | return Err(err);
LL | | }
| |_________^ help: replace it with: `result?;`
error: this block may be rewritten with the `?` operator
--> tests/ui/question_mark.rs:664:10
|
LL | _ = [if let Err(err) = result {
| __________^
LL | |
LL | | return Err(err);
LL | | }];
| |_____^ help: replace it with: `{ result?; }`
error: aborting due to 40 previous errors