Skip to content

Commit

Permalink
Auto merge of rust-lang#15651 - rmehri01:15639_fix_inline_local_closu…
Browse files Browse the repository at this point in the history
…re, 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 rust-lang#15639
  • Loading branch information
bors committed Sep 22, 2023
2 parents d6fef2c + ea11846 commit c22bb03
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
31 changes: 30 additions & 1 deletion crates/ide-assists/src/handlers/inline_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)();
}
"#,
);
}
Expand Down
21 changes: 19 additions & 2 deletions crates/ide-assists/src/handlers/inline_local_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(_)
Expand Down Expand Up @@ -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)();
}
"#,
);
}
Expand Down

0 comments on commit c22bb03

Please sign in to comment.