Auto merge of #15651 - rmehri01:15639_fix_inline_local_closure, r=lnicola

Fix inlining closures from local variables and functions

Previously, closures were not properly wrapped in parentheses for the `inline_local_variable` and `inline_call` assists, leading to the usages being incorrectly called:

```rust
fn main() {
    let $0f = || 2;
    let _ = f();
}
```

Now produces:

```rust
fn main() {
    let _ = (|| 2)();
}
```

Instead of:

```rust
fn main() {
    let _ = || 2();
}
```

Closes #15639
This commit is contained in:
bors 2023-09-22 05:07:51 +00:00
commit c22bb0338a
2 changed files with 49 additions and 3 deletions

View File

@ -481,8 +481,12 @@ fn inline(
};
body.reindent_to(original_indentation);
let no_stmts = body.statements().next().is_none();
match body.tail_expr() {
Some(expr) if !is_async_fn && body.statements().next().is_none() => expr,
Some(expr) if matches!(expr, ast::Expr::ClosureExpr(_)) && no_stmts => {
make::expr_paren(expr).clone_for_update()
}
Some(expr) if !is_async_fn && no_stmts => expr,
_ => match node
.syntax()
.parent()
@ -1471,6 +1475,31 @@ fn main() {
}
});
}
"#,
);
}
#[test]
fn inline_call_closure_body() {
check_assist(
inline_call,
r#"
fn f() -> impl Fn() -> i32 {
|| 2
}
fn main() {
let _ = $0f()();
}
"#,
r#"
fn f() -> impl Fn() -> i32 {
|| 2
}
fn main() {
let _ = (|| 2)();
}
"#,
);
}

View File

@ -96,8 +96,7 @@ pub(crate) fn inline_local_variable(acc: &mut Assists, ctx: &AssistContext<'_>)
);
let parent = matches!(
usage_parent,
ast::Expr::CallExpr(_)
| ast::Expr::TupleExpr(_)
ast::Expr::TupleExpr(_)
| ast::Expr::ArrayExpr(_)
| ast::Expr::ParenExpr(_)
| ast::Expr::ForExpr(_)
@ -949,6 +948,24 @@ fn f() {
let S$0 = S;
S;
}
"#,
);
}
#[test]
fn test_inline_closure() {
check_assist(
inline_local_variable,
r#"
fn main() {
let $0f = || 2;
let _ = f();
}
"#,
r#"
fn main() {
let _ = (|| 2)();
}
"#,
);
}