From a72613be50f8afa39c2d46f732252463dc9cc14f Mon Sep 17 00:00:00 2001 From: Catherine <114838443+Centri3@users.noreply.github.com> Date: Tue, 18 Jul 2023 09:41:56 -0500 Subject: [PATCH] Add parenthesis around closure method call --- src/chains.rs | 25 ++++++++++++++++++++----- tests/source/issue-4808.rs | 13 +++++++++++++ tests/target/issue-4808.rs | 13 +++++++++++++ 3 files changed, 46 insertions(+), 5 deletions(-) create mode 100644 tests/source/issue-4808.rs create mode 100644 tests/target/issue-4808.rs diff --git a/src/chains.rs b/src/chains.rs index bf09d817ed1..d4876389c86 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -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, ); @@ -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, + } +} diff --git a/tests/source/issue-4808.rs b/tests/source/issue-4808.rs new file mode 100644 index 00000000000..93076edcdce --- /dev/null +++ b/tests/source/issue-4808.rs @@ -0,0 +1,13 @@ +trait Trait { + fn method(&self) {} +} + +impl T, T> Trait for F {} + +impl Trait for f32 {} + +fn main() { + || 10. .method(); + || .. .method(); + || 1.. .method(); +} diff --git a/tests/target/issue-4808.rs b/tests/target/issue-4808.rs new file mode 100644 index 00000000000..cdef53a1bfc --- /dev/null +++ b/tests/target/issue-4808.rs @@ -0,0 +1,13 @@ +trait Trait { + fn method(&self) {} +} + +impl T, T> Trait for F {} + +impl Trait for f32 {} + +fn main() { + || (10.).method(); + (|| ..).method(); + (|| 1..).method(); +}