Auto merge of #9210 - evantypanski:issue9160, r=Manishearth

Fix suggestion causing error for [`needless_borrow`] function in field

Fixes #9160

changelog: [`needless_borrow`]: Fix suggestion removing parens from calling a field
This commit is contained in:
bors 2022-07-19 21:16:34 +00:00
commit e98b3ca87b
4 changed files with 65 additions and 2 deletions

View file

@ -1028,9 +1028,10 @@ fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data
let mut app = Applicability::MachineApplicable;
let (snip, snip_is_macro) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
span_lint_hir_and_then(cx, NEEDLESS_BORROW, data.hir_id, data.span, state.msg, |diag| {
let calls_field = matches!(expr.kind, ExprKind::Field(..)) && matches!(data.position, Position::Callee);
let sugg = if !snip_is_macro
&& expr.precedence().order() < data.position.precedence()
&& !has_enclosing_paren(&snip)
&& (expr.precedence().order() < data.position.precedence() || calls_field)
{
format!("({})", snip)
} else {

View file

@ -158,3 +158,28 @@ fn check_expect_suppression() {
#[expect(clippy::needless_borrow)]
let _ = x(&&a);
}
#[allow(dead_code)]
mod issue9160 {
pub struct S<F> {
f: F,
}
impl<T, F> S<F>
where
F: Fn() -> T,
{
fn calls_field(&self) -> T {
(self.f)()
}
}
impl<T, F> S<F>
where
F: FnMut() -> T,
{
fn calls_mut_field(&mut self) -> T {
(self.f)()
}
}
}

View file

@ -158,3 +158,28 @@ fn check_expect_suppression() {
#[expect(clippy::needless_borrow)]
let _ = x(&&a);
}
#[allow(dead_code)]
mod issue9160 {
pub struct S<F> {
f: F,
}
impl<T, F> S<F>
where
F: Fn() -> T,
{
fn calls_field(&self) -> T {
(&self.f)()
}
}
impl<T, F> S<F>
where
F: FnMut() -> T,
{
fn calls_mut_field(&mut self) -> T {
(&mut self.f)()
}
}
}

View file

@ -120,5 +120,17 @@ error: this expression creates a reference which is immediately dereferenced by
LL | (&&5).foo();
| ^^^^^ help: change this to: `(&5)`
error: aborting due to 20 previous errors
error: this expression borrows a value the compiler would automatically borrow
--> $DIR/needless_borrow.rs:173:13
|
LL | (&self.f)()
| ^^^^^^^^^ help: change this to: `(self.f)`
error: this expression borrows a value the compiler would automatically borrow
--> $DIR/needless_borrow.rs:182:13
|
LL | (&mut self.f)()
| ^^^^^^^^^^^^^ help: change this to: `(self.f)`
error: aborting due to 22 previous errors