11use either:: Either ;
22use syntax:: {
3- AstNode ,
3+ AstNode , T ,
44 ast:: { self , edit:: AstNodeEdit , syntax_factory:: SyntaxFactory } ,
5+ match_ast,
56} ;
67
78use crate :: { AssistContext , AssistId , Assists } ;
@@ -37,6 +38,7 @@ pub(crate) fn add_braces(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
3738 match expr_type {
3839 ParentType :: ClosureExpr => "Add braces to this closure body" ,
3940 ParentType :: MatchArmExpr => "Add braces to this match arm expression" ,
41+ ParentType :: Assignment => "Add braces to this assignment expression" ,
4042 } ,
4143 expr. syntax ( ) . text_range ( ) ,
4244 |builder| {
@@ -57,29 +59,38 @@ pub(crate) fn add_braces(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
5759enum ParentType {
5860 MatchArmExpr ,
5961 ClosureExpr ,
62+ Assignment ,
6063}
6164
6265fn get_replacement_node ( ctx : & AssistContext < ' _ > ) -> Option < ( ParentType , ast:: Expr ) > {
63- let node = ctx. find_node_at_offset :: < Either < ast:: MatchArm , ast:: ClosureExpr > > ( ) ?;
64- if let Either :: Left ( match_arm) = & node {
66+ let node = ctx. find_node_at_offset :: < Either < ast:: MatchArm , ast:: ClosureExpr > > ( ) ;
67+ let ( parent_type, body) = if let Some ( eq_token) = ctx. find_token_syntax_at_offset ( T ! [ =] ) {
68+ let parent = eq_token. parent ( ) ?;
69+ let body = match_ast ! {
70+ match parent {
71+ ast:: LetStmt ( it) => it. initializer( ) ?,
72+ ast:: LetExpr ( it) => it. expr( ) ?,
73+ ast:: Static ( it) => it. body( ) ?,
74+ ast:: Const ( it) => it. body( ) ?,
75+ _ => return None ,
76+ }
77+ } ;
78+ ( ParentType :: Assignment , body)
79+ } else if let Some ( Either :: Left ( match_arm) ) = & node {
6580 let match_arm_expr = match_arm. expr ( ) ?;
66-
67- if matches ! ( match_arm_expr, ast:: Expr :: BlockExpr ( _) ) {
68- return None ;
69- }
70-
71- return Some ( ( ParentType :: MatchArmExpr , match_arm_expr) ) ;
72- } else if let Either :: Right ( closure_expr) = & node {
81+ ( ParentType :: MatchArmExpr , match_arm_expr)
82+ } else if let Some ( Either :: Right ( closure_expr) ) = & node {
7383 let body = closure_expr. body ( ) ?;
84+ ( ParentType :: ClosureExpr , body)
85+ } else {
86+ return None ;
87+ } ;
7488
75- if matches ! ( body, ast:: Expr :: BlockExpr ( _) ) {
76- return None ;
77- }
78-
79- return Some ( ( ParentType :: ClosureExpr , body) ) ;
89+ if matches ! ( body, ast:: Expr :: BlockExpr ( _) ) {
90+ return None ;
8091 }
8192
82- None
93+ Some ( ( parent_type , body ) )
8394}
8495
8596#[ cfg( test) ]
@@ -134,6 +145,25 @@ fn foo() {
134145 ) ;
135146 }
136147
148+ #[ test]
149+ fn suggest_add_braces_for_assignment ( ) {
150+ check_assist (
151+ add_braces,
152+ r#"
153+ fn foo() {
154+ let x =$0 n + 100;
155+ }
156+ "# ,
157+ r#"
158+ fn foo() {
159+ let x = {
160+ n + 100
161+ };
162+ }
163+ "# ,
164+ ) ;
165+ }
166+
137167 #[ test]
138168 fn no_assist_for_closures_with_braces ( ) {
139169 check_assist_not_applicable (
0 commit comments