Skip to content

Commit

Permalink
Auto merge of rust-lang#17471 - davidsemakula:fix-remove-parenthesis,…
Browse files Browse the repository at this point in the history
… r=Veykril

fix: don't remove parentheses for calls of function-like pointers that are members of a struct or union

Fixes rust-lang#17111
  • Loading branch information
bors committed Jun 24, 2024
2 parents f9a337c + f1debd9 commit 1cd8bc0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,33 @@ mod tests {

check_assist_not_applicable(remove_parentheses, r#"fn f() { $0(return 2) + 2 }"#);
}

#[test]
fn remove_parens_indirect_calls() {
check_assist(
remove_parentheses,
r#"fn f(call: fn(usize), arg: usize) { $0(call)(arg); }"#,
r#"fn f(call: fn(usize), arg: usize) { call(arg); }"#,
);
check_assist(
remove_parentheses,
r#"fn f<F>(call: F, arg: usize) where F: Fn(usize) { $0(call)(arg); }"#,
r#"fn f<F>(call: F, arg: usize) where F: Fn(usize) { call(arg); }"#,
);

// Parentheses are necessary when calling a function-like pointer that is a member of a struct or union.
check_assist_not_applicable(
remove_parentheses,
r#"
struct Foo<T> {
t: T,
}
impl Foo<fn(usize)> {
fn foo(&self, arg: usize) {
$0(self.t)(arg);
}
}"#,
);
}
}
8 changes: 8 additions & 0 deletions src/tools/rust-analyzer/crates/syntax/src/ast/prec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ impl Expr {
}

fn needs_parens_in_expr(&self, parent: &Expr) -> bool {
// Parentheses are necessary when calling a function-like pointer that is a member of a struct or union
// (e.g. `(a.f)()`).
let is_parent_call_expr = matches!(parent, ast::Expr::CallExpr(_));
let is_field_expr = matches!(self, ast::Expr::FieldExpr(_));
if is_parent_call_expr && is_field_expr {
return true;
}

// Special-case block weirdness
if parent.child_is_followed_by_a_block() {
use Expr::*;
Expand Down

0 comments on commit 1cd8bc0

Please sign in to comment.