Skip to content

Commit 11fbafd

Browse files
committed
Narrow "if-let to match" assist available range
1 parent 4badd2f commit 11fbafd

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed

crates/ide_assists/src/handlers/replace_if_let_with_match.rs

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use syntax::{
88
edit::{AstNodeEdit, IndentLevel},
99
make, NameOwner,
1010
},
11-
AstNode,
11+
AstNode, TextRange,
1212
};
1313

1414
use crate::{
@@ -44,6 +44,14 @@ use crate::{
4444
// ```
4545
pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
4646
let if_expr: ast::IfExpr = ctx.find_node_at_offset()?;
47+
let available_range = TextRange::new(
48+
if_expr.syntax().text_range().start(),
49+
if_expr.then_branch()?.syntax().text_range().start(),
50+
);
51+
let cursor_in_range = available_range.contains_range(ctx.frange.range);
52+
if !cursor_in_range {
53+
return None;
54+
}
4755
let mut else_block = None;
4856
let if_exprs = successors(Some(if_expr.clone()), |expr| match expr.else_branch()? {
4957
ast::ElseBranch::IfExpr(expr) => Some(expr),
@@ -79,11 +87,10 @@ pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext)
7987
return None;
8088
}
8189

82-
let target = if_expr.syntax().text_range();
8390
acc.add(
8491
AssistId("replace_if_let_with_match", AssistKind::RefactorRewrite),
8592
"Replace if let with match",
86-
target,
93+
available_range,
8794
move |edit| {
8895
let match_expr = {
8996
let else_arm = make_else_arm(ctx, else_block, &cond_bodies);
@@ -330,6 +337,38 @@ impl VariantData {
330337
)
331338
}
332339

340+
#[test]
341+
fn test_if_let_with_match_available_range_left() {
342+
check_assist_not_applicable(
343+
replace_if_let_with_match,
344+
r#"
345+
impl VariantData {
346+
pub fn foo(&self) {
347+
$0 if let VariantData::Struct(..) = *self {
348+
self.foo();
349+
}
350+
}
351+
}
352+
"#,
353+
)
354+
}
355+
356+
#[test]
357+
fn test_if_let_with_match_available_range_right() {
358+
check_assist_not_applicable(
359+
replace_if_let_with_match,
360+
r#"
361+
impl VariantData {
362+
pub fn foo(&self) {
363+
if let VariantData::Struct(..) = *self {$0
364+
self.foo();
365+
}
366+
}
367+
}
368+
"#,
369+
)
370+
}
371+
333372
#[test]
334373
fn test_if_let_with_match_basic() {
335374
check_assist(

0 commit comments

Comments
 (0)