Skip to content

Commit

Permalink
Add parenthesis around closure method call
Browse files Browse the repository at this point in the history
  • Loading branch information
Centri3 committed Jul 18, 2023
1 parent e0e633e commit 7149aa8
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,7 @@ impl ChainItemKind {
return (
ChainItemKind::Parent {
expr: expr.clone(),
parens: is_method_call_receiver
&& matches!(
&expr.kind,
ast::ExprKind::Lit(lit) if crate::expr::lit_ends_in_dot(lit)
),
parens: is_method_call_receiver && should_add_parens(expr),
},
expr.span,
);
Expand Down Expand Up @@ -982,3 +978,22 @@ fn trim_tries(s: &str) -> String {
}
result
}

/// Whether a method call's receiver needs parenthesis, like
/// ```rust,ignore
/// || .. .method();
/// || 1.. .method();
/// 1. .method();
/// ```
/// Which all need parenthesis or a space before `.method()`.
fn should_add_parens(expr: &ast::Expr) -> bool {
match expr.kind {
ast::ExprKind::Lit(ref lit) => crate::expr::lit_ends_in_dot(lit),
ast::ExprKind::Closure(ref cl) => match cl.body.kind {
ast::ExprKind::Range(_, _, ast::RangeLimits::HalfOpen) => true,
ast::ExprKind::Lit(ref lit) => crate::expr::lit_ends_in_dot(lit),
_ => false,
},
_ => false,
}
}
19 changes: 19 additions & 0 deletions tests/source/issue-4808.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
trait Trait {
fn method(&self);
}

impl<F: Fn() -> T, T> Trait for F {
fn method(&self) {}
}

trait Trait {
fn method(&self) {}
}

impl Trait for f32 {}

fn main() {
|| 10. .method();
|| .. .method();
|| 1.. .method();
}
19 changes: 19 additions & 0 deletions tests/target/issue-4808.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
trait Trait {
fn method(&self);
}

impl<F: Fn() -> T, T> Trait for F {
fn method(&self) {}
}

trait Trait {
fn method(&self) {}
}

impl Trait for f32 {}

fn main() {
|| (10.).method();
(|| ..).method();
(|| 1..).method();
}

0 comments on commit 7149aa8

Please sign in to comment.