Skip to content

Commit 5be653d

Browse files
bors[bot]Brandon
andauthored
Merge #9108
9108: Don't show extract into variable assist for unit expressions r=jonas-schievink a=brandondong **Reproduction:** ```rust fn main() { let mut i = 3; $0if i >= 0 { i += 1; } else { i -= 1; }$0 } ``` 1. Select the snippet of code between the $0's. 2. The extract into variable assist shows up, pushing down the more useful extract into function assist. 3. The resulting output of selecting the extract into variable assist is valid but with the extracted variable having the unit type: ```rust fn main() { let mut i = 3; let var_name = if i >= 0 { i += 1; } else { i -= 1; }; var_name } ``` **Fix:** - Don't show the extract into variable assist for unit expressions. I could not think of any scenarios where such a variable extraction would be desired. Co-authored-by: Brandon <[email protected]>
2 parents a421482 + 7d27102 commit 5be653d

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

crates/ide_assists/src/handlers/extract_variable.rs

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option
3636
return None;
3737
}
3838
let to_extract = node.ancestors().find_map(valid_target_expr)?;
39+
if let Some(ty) = ctx.sema.type_of_expr(&to_extract) {
40+
if ty.is_unit() {
41+
return None;
42+
}
43+
}
3944
let anchor = Anchor::from(&to_extract)?;
4045
let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
4146
let target = to_extract.syntax().text_range();
@@ -275,15 +280,23 @@ fn foo() {
275280
check_assist(
276281
extract_variable,
277282
r#"
278-
fn foo() {
283+
fn foo() -> i32 {
279284
$0bar(1 + 1)$0
280285
}
286+
287+
fn bar(i: i32) -> i32 {
288+
i
289+
}
281290
"#,
282291
r#"
283-
fn foo() {
292+
fn foo() -> i32 {
284293
let $0bar = bar(1 + 1);
285294
bar
286295
}
296+
297+
fn bar(i: i32) -> i32 {
298+
i
299+
}
287300
"#,
288301
)
289302
}
@@ -796,6 +809,22 @@ fn foo() {
796809
check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
797810
}
798811

812+
#[test]
813+
fn test_extract_var_unit_expr_not_applicable() {
814+
check_assist_not_applicable(
815+
extract_variable,
816+
r#"
817+
fn foo() {
818+
let mut i = 3;
819+
$0if i >= 0 {
820+
i += 1;
821+
} else {
822+
i -= 1;
823+
}$0
824+
}"#,
825+
);
826+
}
827+
799828
// FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
800829
#[test]
801830
fn extract_var_target() {

0 commit comments

Comments
 (0)