Rust-clippy: False positive with `clippy::needless-lifetimes` when lifetime is used in `where` clause with assoc type

Created on 11 Oct 2020  路  3Comments  路  Source: rust-lang/rust-clippy

I tried this code:

use core::ops::Deref;

pub fn apply_deref<'a, T, F, R>(x: &'a T, f: F) -> R
where
    T: Deref,
    F: FnOnce(&'a T::Target) -> R,
{
    f(x.deref())
}

I expected to see this happen: no warnings

Instead, this happened: needless lifetimes warning

warning: explicit lifetimes given in parameter types where they could be elided (or replaced with `'_` if needed by type declaration)
 --> src/lib.rs:3:1
  |
3 | pub fn apply_deref<'a, T, F, R>(x: &'a T, f: F) -> R
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(clippy::needless_lifetimes)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes

Meta

  • cargo clippy -V: clippy 0.0.212 (38d911d 2020-10-09)
  • rustc -Vv:
    rustc 1.49.0-nightly (38d911dfc 2020-10-09) binary: rustc commit-hash: 38d911dfc55a7a1eea1c80139113ed2ff0151087 commit-date: 2020-10-09 host: x86_64-unknown-linux-gnu release: 1.49.0-nightly LLVM version: 11.0
L-bug L-suggestion-causes-error

Most helpful comment

This is a regression of #5978. I've prepared a fix.

All 3 comments

Removing the lifetime will cause a compilation error if the returned value borrows from the closure parameter or is the closure parameter itself:

use core::ops::Deref;

pub fn apply_deref<T, F, R>(x: &T, f: F) -> R
where
    T: Deref,
    F: FnOnce(&T::Target) -> R,
{
    f(x.deref())
}

fn main() {
    let x: Vec<i32> = vec![];
    apply_deref(&x, |v| v);
}

(playground)

cc @montrivo as you may have an idea of what the problem could be

This is a regression of #5978. I've prepared a fix.

The lint bails out on named lifetimes found in the where clause predicates. The regression caused the lint to shortcircuit after the first predicate (T: Deref, in the example) and not walk the following ones (F: FnOnce(&'a T::Target) -> R,).

Was this page helpful?
0 / 5 - 0 ratings