@@ -56,14 +56,23 @@ pub(crate) fn convert_to_guarded_return(acc: &mut Assists, ctx: &AssistContext<'
5656fn if_expr_to_guarded_return (
5757 if_expr : ast:: IfExpr ,
5858 acc : & mut Assists ,
59- _ctx : & AssistContext < ' _ > ,
59+ ctx : & AssistContext < ' _ > ,
6060) -> Option < ( ) > {
6161 if if_expr. else_branch ( ) . is_some ( ) {
6262 return None ;
6363 }
6464
6565 let cond = if_expr. condition ( ) ?;
6666
67+ let if_token_range = if_expr. if_token ( ) ?. text_range ( ) ;
68+ let if_cond_range = cond. syntax ( ) . text_range ( ) ;
69+
70+ let cursor_in_range =
71+ if_token_range. cover ( if_cond_range) . contains_range ( ctx. selection_trimmed ( ) ) ;
72+ if !cursor_in_range {
73+ return None ;
74+ }
75+
6776 // Check if there is an IfLet that we can handle.
6877 let ( if_let_pat, cond_expr) = if is_pattern_cond ( cond. clone ( ) ) {
6978 let let_ = single_let ( cond) ?;
@@ -172,6 +181,15 @@ fn let_stmt_to_guarded_return(
172181 let pat = let_stmt. pat ( ) ?;
173182 let expr = let_stmt. initializer ( ) ?;
174183
184+ let let_token_range = let_stmt. let_token ( ) ?. text_range ( ) ;
185+ let let_pattern_range = pat. syntax ( ) . text_range ( ) ;
186+ let cursor_in_range =
187+ let_token_range. cover ( let_pattern_range) . contains_range ( ctx. selection_trimmed ( ) ) ;
188+
189+ if !cursor_in_range {
190+ return None ;
191+ }
192+
175193 let try_enum =
176194 ctx. sema . type_of_expr ( & expr) . and_then ( |ty| TryEnum :: from_ty ( & ctx. sema , & ty. adjusted ( ) ) ) ?;
177195
@@ -713,6 +731,37 @@ fn main() {
713731 }
714732 }
715733}
734+ "# ,
735+ ) ;
736+ }
737+
738+ #[ test]
739+ fn ignore_inside_if_stmt ( ) {
740+ check_assist_not_applicable (
741+ convert_to_guarded_return,
742+ r#"
743+ fn main() {
744+ if false {
745+ foo()$0;
746+ }
747+ }
748+ "# ,
749+ ) ;
750+ }
751+
752+ #[ test]
753+ fn ignore_inside_let_initializer ( ) {
754+ check_assist_not_applicable (
755+ convert_to_guarded_return,
756+ r#"
757+ //- minicore: option
758+ fn foo() -> Option<i32> {
759+ None
760+ }
761+
762+ fn main() {
763+ let x = foo()$0;
764+ }
716765"# ,
717766 ) ;
718767 }
0 commit comments