@@ -2,8 +2,12 @@ use either::Either;
2
2
use hir:: { db:: ExpandDatabase , ClosureStyle , HirDisplay , HirFileIdExt , InFile , Type } ;
3
3
use ide_db:: { famous_defs:: FamousDefs , source_change:: SourceChange } ;
4
4
use syntax:: {
5
- ast:: { self , BlockExpr , ExprStmt } ,
6
- AstNode , AstPtr ,
5
+ ast:: {
6
+ self ,
7
+ edit:: { AstNodeEdit , IndentLevel } ,
8
+ BlockExpr , Expr , ExprStmt ,
9
+ } ,
10
+ AstNode , AstPtr , TextSize ,
7
11
} ;
8
12
use text_edit:: TextEdit ;
9
13
@@ -119,6 +123,38 @@ fn add_missing_ok_or_some(
119
123
return None ;
120
124
}
121
125
126
+ if d. actual . is_unit ( ) {
127
+ if let Expr :: BlockExpr ( block) = & expr {
128
+ if block. tail_expr ( ) . is_none ( ) {
129
+ let mut builder = TextEdit :: builder ( ) ;
130
+ let block_indent = block. indent_level ( ) ;
131
+
132
+ if block. statements ( ) . count ( ) == 0 {
133
+ // Empty block
134
+ let indent = block_indent + 1 ;
135
+ builder. insert (
136
+ block. syntax ( ) . text_range ( ) . start ( ) + TextSize :: from ( 1 ) ,
137
+ format ! ( "\n {indent}{variant_name}(())\n {block_indent}" ) ,
138
+ ) ;
139
+ } else {
140
+ let indent = IndentLevel :: from ( 1 ) ;
141
+ builder. insert (
142
+ block. syntax ( ) . text_range ( ) . end ( ) - TextSize :: from ( 1 ) ,
143
+ format ! ( "{indent}{variant_name}(())\n {block_indent}" ) ,
144
+ ) ;
145
+ }
146
+
147
+ let source_change = SourceChange :: from_text_edit (
148
+ expr_ptr. file_id . original_file ( ctx. sema . db ) ,
149
+ builder. finish ( ) ,
150
+ ) ;
151
+ let name = format ! ( "Insert {variant_name}(()) as the tail of this block" ) ;
152
+ acc. push ( fix ( "insert_wrapped_unit" , & name, source_change, expr_range) ) ;
153
+ }
154
+ return Some ( ( ) ) ;
155
+ }
156
+ }
157
+
122
158
let mut builder = TextEdit :: builder ( ) ;
123
159
builder. insert ( expr. syntax ( ) . text_range ( ) . start ( ) , format ! ( "{variant_name}(" ) ) ;
124
160
builder. insert ( expr. syntax ( ) . text_range ( ) . end ( ) , ")" . to_owned ( ) ) ;
@@ -533,6 +569,36 @@ fn div(x: i32, y: i32) -> MyResult<i32> {
533
569
) ;
534
570
}
535
571
572
+ #[ test]
573
+ fn test_wrapped_unit_as_block_tail_expr ( ) {
574
+ check_fix (
575
+ r#"
576
+ //- minicore: result
577
+ fn foo() -> Result<(), ()> {
578
+ foo();
579
+ }$0
580
+ "# ,
581
+ r#"
582
+ fn foo() -> Result<(), ()> {
583
+ foo();
584
+ Ok(())
585
+ }
586
+ "# ,
587
+ ) ;
588
+
589
+ check_fix (
590
+ r#"
591
+ //- minicore: result
592
+ fn foo() -> Result<(), ()> {}$0
593
+ "# ,
594
+ r#"
595
+ fn foo() -> Result<(), ()> {
596
+ Ok(())
597
+ }
598
+ "# ,
599
+ ) ;
600
+ }
601
+
536
602
#[ test]
537
603
fn test_in_const_and_static ( ) {
538
604
check_fix (
0 commit comments