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 <brandondong604@hotmail.com>
This commit is contained in:
bors[bot] 2021-06-02 17:25:11 +00:00 committed by GitHub
commit 5be653d426
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -36,6 +36,11 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option
return None;
}
let to_extract = node.ancestors().find_map(valid_target_expr)?;
if let Some(ty) = ctx.sema.type_of_expr(&to_extract) {
if ty.is_unit() {
return None;
}
}
let anchor = Anchor::from(&to_extract)?;
let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
let target = to_extract.syntax().text_range();
@ -275,15 +280,23 @@ fn foo() {
check_assist(
extract_variable,
r#"
fn foo() {
fn foo() -> i32 {
$0bar(1 + 1)$0
}
fn bar(i: i32) -> i32 {
i
}
"#,
r#"
fn foo() {
fn foo() -> i32 {
let $0bar = bar(1 + 1);
bar
}
fn bar(i: i32) -> i32 {
i
}
"#,
)
}
@ -796,6 +809,22 @@ fn foo() {
check_assist_not_applicable(extract_variable, "fn main() { loop { $0break$0; }; }");
}
#[test]
fn test_extract_var_unit_expr_not_applicable() {
check_assist_not_applicable(
extract_variable,
r#"
fn foo() {
let mut i = 3;
$0if i >= 0 {
i += 1;
} else {
i -= 1;
}$0
}"#,
);
}
// FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
#[test]
fn extract_var_target() {