Skip to content

Commit d381df4

Browse files
committed
fix: autofix for missing wrapped unit in return expr
1 parent 12d63d9 commit d381df4

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs

+38
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ fn add_missing_ok_or_some(
130130
if d.actual.is_unit() {
131131
if let Expr::BlockExpr(block) = &expr {
132132
if block.tail_expr().is_none() {
133+
// Fix for forms like `fn foo() -> Result<(), String> {}`
133134
let mut builder = TextEdit::builder();
134135
let block_indent = block.indent_level();
135136

@@ -156,6 +157,20 @@ fn add_missing_ok_or_some(
156157
acc.push(fix("insert_wrapped_unit", &name, source_change, expr_range));
157158
}
158159
return Some(());
160+
} else if let Expr::ReturnExpr(ret_expr) = &expr {
161+
// Fix for forms like `fn foo() -> Result<(), String> { return; }`
162+
if ret_expr.expr().is_none() {
163+
let mut builder = TextEdit::builder();
164+
builder
165+
.insert(ret_expr.syntax().text_range().end(), format!(" {variant_name}(())"));
166+
let source_change = SourceChange::from_text_edit(
167+
expr_ptr.file_id.original_file(ctx.sema.db),
168+
builder.finish(),
169+
);
170+
let name = format!("Insert {variant_name}(()) as the return value");
171+
acc.push(fix("insert_wrapped_unit", &name, source_change, expr_range));
172+
}
173+
return Some(());
159174
}
160175
}
161176

@@ -603,6 +618,29 @@ fn foo() -> Result<(), ()> {
603618
);
604619
}
605620

621+
#[test]
622+
fn test_wrapped_unit_as_return_expr() {
623+
check_fix(
624+
r#"
625+
//- minicore: result
626+
fn foo(b: bool) -> Result<(), String> {
627+
if b {
628+
return$0;
629+
}
630+
631+
Err("oh dear".to_owned())
632+
}"#,
633+
r#"
634+
fn foo(b: bool) -> Result<(), String> {
635+
if b {
636+
return Ok(());
637+
}
638+
639+
Err("oh dear".to_owned())
640+
}"#,
641+
);
642+
}
643+
606644
#[test]
607645
fn test_in_const_and_static() {
608646
check_fix(

0 commit comments

Comments
 (0)