Skip to content

Commit ffefbf2

Browse files
author
Brandon
committed
Fix extract function with partial block selection
1 parent 10a243e commit ffefbf2

File tree

1 file changed

+62
-2
lines changed

1 file changed

+62
-2
lines changed

crates/ide_assists/src/handlers/extract_function.rs

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,12 @@ fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<Fu
599599
// we have selected a few statements in a block
600600
// so covering_element returns the whole block
601601
if node.kind() == BLOCK_EXPR {
602-
let body = FunctionBody::from_range(node.clone(), selection_range);
602+
// Extract the full statements.
603+
let statements_range = node
604+
.children()
605+
.filter(|c| selection_range.intersect(c.text_range()).is_some())
606+
.fold(selection_range, |acc, c| acc.cover(c.text_range()));
607+
let body = FunctionBody::from_range(node.clone(), statements_range);
603608
if body.is_some() {
604609
return body;
605610
}
@@ -610,7 +615,8 @@ fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<Fu
610615
// so we try to expand covering_element to parent and repeat the previous
611616
if let Some(parent) = node.parent() {
612617
if parent.kind() == BLOCK_EXPR {
613-
let body = FunctionBody::from_range(parent, selection_range);
618+
// Extract the full statement.
619+
let body = FunctionBody::from_range(parent, node.text_range());
614620
if body.is_some() {
615621
return body;
616622
}
@@ -1784,6 +1790,60 @@ fn $0fun_name() -> i32 {
17841790
);
17851791
}
17861792

1793+
#[test]
1794+
fn extract_partial_block_single_line() {
1795+
check_assist(
1796+
extract_function,
1797+
r#"
1798+
fn foo() {
1799+
let n = 1;
1800+
let mut v = $0n * n;$0
1801+
v += 1;
1802+
}"#,
1803+
r#"
1804+
fn foo() {
1805+
let n = 1;
1806+
let mut v = fun_name(n);
1807+
v += 1;
1808+
}
1809+
1810+
fn $0fun_name(n: i32) -> i32 {
1811+
let mut v = n * n;
1812+
v
1813+
}"#,
1814+
);
1815+
}
1816+
1817+
#[test]
1818+
fn extract_partial_block() {
1819+
check_assist(
1820+
extract_function,
1821+
r#"
1822+
fn foo() {
1823+
let m = 2;
1824+
let n = 1;
1825+
let mut v = m $0* n;
1826+
let mut w = 3;$0
1827+
v += 1;
1828+
w += 1;
1829+
}"#,
1830+
r#"
1831+
fn foo() {
1832+
let m = 2;
1833+
let n = 1;
1834+
let (mut v, mut w) = fun_name(m, n);
1835+
v += 1;
1836+
w += 1;
1837+
}
1838+
1839+
fn $0fun_name(m: i32, n: i32) -> (i32, i32) {
1840+
let mut v = m * n;
1841+
let mut w = 3;
1842+
(v, w)
1843+
}"#,
1844+
);
1845+
}
1846+
17871847
#[test]
17881848
fn argument_form_expr() {
17891849
check_assist(

0 commit comments

Comments
 (0)