about summary refs log tree commit diff
diff options
context:
space:
mode:
authordfireBird <me@dfirebird.dev>2024-02-05 18:53:40 +0530
committerdfireBird <me@dfirebird.dev>2024-02-05 18:53:40 +0530
commit53db37f9bffc7f20f1a23e45d172207580cfb9cb (patch)
treeaab2d52d4543bfaa9e82518cd16246c2906080e9
parente0446a0eb5471d28ec74630ecc43c2ae5da94b79 (diff)
downloadrust-53db37f9bffc7f20f1a23e45d172207580cfb9cb.tar.gz
rust-53db37f9bffc7f20f1a23e45d172207580cfb9cb.zip
restrict cursor range to show assists
-rw-r--r--crates/ide-assists/src/handlers/convert_to_guarded_return.rs51
1 files changed, 50 insertions, 1 deletions
diff --git a/crates/ide-assists/src/handlers/convert_to_guarded_return.rs b/crates/ide-assists/src/handlers/convert_to_guarded_return.rs
index 5fc1c1dda62..e1966d476c5 100644
--- a/crates/ide-assists/src/handlers/convert_to_guarded_return.rs
+++ b/crates/ide-assists/src/handlers/convert_to_guarded_return.rs
@@ -56,7 +56,7 @@ pub(crate) fn convert_to_guarded_return(acc: &mut Assists, ctx: &AssistContext<'
 fn if_expr_to_guarded_return(
     if_expr: ast::IfExpr,
     acc: &mut Assists,
-    _ctx: &AssistContext<'_>,
+    ctx: &AssistContext<'_>,
 ) -> Option<()> {
     if if_expr.else_branch().is_some() {
         return None;
@@ -64,6 +64,15 @@ fn if_expr_to_guarded_return(
 
     let cond = if_expr.condition()?;
 
+    let if_token_range = if_expr.if_token()?.text_range();
+    let if_cond_range = cond.syntax().text_range();
+
+    let cursor_in_range =
+        if_token_range.cover(if_cond_range).contains_range(ctx.selection_trimmed());
+    if !cursor_in_range {
+        return None;
+    }
+
     // Check if there is an IfLet that we can handle.
     let (if_let_pat, cond_expr) = if is_pattern_cond(cond.clone()) {
         let let_ = single_let(cond)?;
@@ -172,6 +181,15 @@ fn let_stmt_to_guarded_return(
     let pat = let_stmt.pat()?;
     let expr = let_stmt.initializer()?;
 
+    let let_token_range = let_stmt.let_token()?.text_range();
+    let let_pattern_range = pat.syntax().text_range();
+    let cursor_in_range =
+        let_token_range.cover(let_pattern_range).contains_range(ctx.selection_trimmed());
+
+    if !cursor_in_range {
+        return None;
+    }
+
     let try_enum =
         ctx.sema.type_of_expr(&expr).and_then(|ty| TryEnum::from_ty(&ctx.sema, &ty.adjusted()))?;
 
@@ -716,4 +734,35 @@ fn main() {
 "#,
         );
     }
+
+    #[test]
+    fn ignore_inside_if_stmt() {
+        check_assist_not_applicable(
+            convert_to_guarded_return,
+            r#"
+fn main() {
+    if false {
+        foo()$0;
+    }
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn ignore_inside_let_initializer() {
+        check_assist_not_applicable(
+            convert_to_guarded_return,
+            r#"
+//- minicore: option
+fn foo() -> Option<i32> {
+    None
+}
+
+fn main() {
+    let x = foo()$0;
+}
+"#,
+        );
+    }
 }