rust-lang / rust-lang/rust-clippy

`needless_lifetimes` removes lifetimes that are actually necessary

Open
#12,908 5 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

The lifetimes seem to be unavoidable in the function I defined, but clippy still suggests removing them. If I run cargo clippy --fix, the resulting code fails to compile.

Lint Name

needless_lifetimes

Reproducer

I tried this code:

#![allow(dead_code)]

use std::collections::hash_map::{Entry, HashMap};

use petgraph::matrix_graph::{NodeIndex, UnMatrix};
use winnow::{
    ascii::line_ending,
    ascii::{alpha1, dec_uint},
    combinator::{opt, separated, seq, terminated},
    error::ParserError,
    PResult, Parser,
};

pub fn lines<'a, Output, Error>(
    parser: impl Parser<&'a str, Output, Error>,
) -> impl Parser<&'a str, Vec<Output>, Error>
where
    Error: ParserError<&'a str>,
{
    terminated(separated(.., parser, line_ending), opt(line_ending))
}

type G<'s> = UnMatrix<&'s str, u32>;

fn edge<'s>(input: &mut &'s str) -> PResult<(&'s str, &'s str, u32)> {
    seq!(
        alpha1,
        _: " to ",
        alpha1,
        _: " = ",
        dec_uint
    )
    .parse_next(input)
}

fn parse<'s>(input: &'s str) -> G<'s> {
    lines(edge)
        .map(|edges| {
            let mut g = G::default();

            let mut nodes = HashMap::<&'s str, NodeIndex<u16>>::default();
            let mut node = |g: &mut G<'s>, tag: &'s str| match nodes.entry(tag) {
                Entry::Occupied(e) => *e.get(),
                Entry::Vacant(e) => *e.insert(g.add_node(tag)),
            };

            for (a, b, weight) in edges {
                let a = node(&mut g, a);
                let b = node(&mut g, b);
                g.add_edge(a, b, weight);
            }

            g
        })
        .parse(input)
        .unwrap()
}

I saw this happen:

rygno@Alfred-Desktop:~/aoc/test_clippy$ cargo clippy --fix --allow-dirty
    Checking test_clippy v0.1.0 (/home/rygno/aoc/test_clippy)
warning: failed to automatically apply fixes suggested by rustc to crate `test_clippy`

after fixes were automatically applied the compiler reported errors within these files:

  * test_clippy/src/lib.rs

This likely indicates a bug in either rustc or cargo itself,
and we would appreciate a bug report! You're likely to see
a number of compiler warnings after this message which cargo
attempted to fix but failed. If you could open an issue at
https://github.com/rust-lang/rust-clippy/issues
quoting the full output of this command we'd be very appreciative!
Note that you may be able to make some more progress in the near-term
fixing code with the `--broken-code` flag

The following errors were reported:
error[E0261]: use of undeclared lifetime name `'s`
  --> test_clippy/src/lib.rs:41:40
   |
36 | fn parse(input: &str) -> G<'_> {
   |         - help: consider introducing lifetime `'s` here: `<'s>`
...
41 |             let mut nodes = HashMap::<&'s str, NodeIndex<u16>>::default();
   |                                        ^^ undeclared lifetime

error[E0261]: use of undeclared lifetime name `'s`
  --> test_clippy/src/lib.rs:42:39
   |
36 | fn parse(input: &str) -> G<'_> {
   |         - help: consider introducing lifetime `'s` here: `<'s>`
...
42 |             let mut node = |g: &mut G<'s>, tag: &'s str| match nodes.entry(tag) {
   |                                       ^^ undeclared lifetime

error[E0261]: use of undeclared lifetime name `'s`
  --> test_clippy/src/lib.rs:42:50
   |
36 | fn parse(input: &str) -> G<'_> {
   |         - help: consider introducing lifetime `'s` here: `<'s>`
...
42 |             let mut node = |g: &mut G<'s>, tag: &'s str| match nodes.entry(tag) {
   |                                                  ^^ undeclared lifetime

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0261`.
Original diagnostics will follow.

warning: the following explicit lifetimes could be elided: 's
  --> test_clippy/src/lib.rs:36:10
   |
36 | fn parse<'s>(input: &'s str) -> G<'s> {
   |          ^^          ^^           ^^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes
   = note: `#[warn(clippy::needless_lifetimes)]` on by default
help: elide the lifetimes
   |
36 - fn parse<'s>(input: &'s str) -> G<'s> {
36 + fn parse(input: &str) -> G<'_> {
   |

warning: `test_clippy` (lib) generated 1 warning (run `cargo clippy --fix --lib -p test_clippy` to apply 1 suggestion)
warning: failed to automatically apply fixes suggested by rustc to crate `test_clippy`

after fixes were automatically applied the compiler reported errors within these files:

  * test_clippy/src/lib.rs

This likely indicates a bug in either rustc or cargo itself,
and we would appreciate a bug report! You're likely to see
a number of compiler warnings after this message which cargo
attempted to fix but failed. If you could open an issue at
https://github.com/rust-lang/rust-clippy/issues
quoting the full output of this command we'd be very appreciative!
Note that you may be able to make some more progress in the near-term
fixing code with the `--broken-code` flag

The following errors were reported:
error[E0261]: use of undeclared lifetime name `'s`
  --> test_clippy/src/lib.rs:41:40
   |
36 | fn parse(input: &str) -> G<'_> {
   |         - help: consider introducing lifetime `'s` here: `<'s>`
...
41 |             let mut nodes = HashMap::<&'s str, NodeIndex<u16>>::default();
   |                                        ^^ undeclared lifetime

error[E0261]: use of undeclared lifetime name `'s`
  --> test_clippy/src/lib.rs:42:39
   |
36 | fn parse(input: &str) -> G<'_> {
   |         - help: consider introducing lifetime `'s` here: `<'s>`
...
42 |             let mut node = |g: &mut G<'s>, tag: &'s str| match nodes.entry(tag) {
   |                                       ^^ undeclared lifetime

error[E0261]: use of undeclared lifetime name `'s`
  --> test_clippy/src/lib.rs:42:50
   |
36 | fn parse(input: &str) -> G<'_> {
   |         - help: consider introducing lifetime `'s` here: `<'s>`
...
42 |             let mut node = |g: &mut G<'s>, tag: &'s str| match nodes.entry(tag) {
   |                                                  ^^ undeclared lifetime

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0261`.
Original diagnostics will follow.

warning: `test_clippy` (lib test) generated 1 warning (1 duplicate)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12s

I expected to see this happen:
No suggestions, as the lifetime annotation is necessary here as far as I know.

Version
rustc 1.78.0 (9b00956e5 2024-04-29)
binary: rustc
commit-hash: 9b00956e56009bab2aa15d7bff10916599e3d6d6
commit-date: 2024-04-29
host: x86_64-unknown-linux-gnu
release: 1.78.0
LLVM version: 18.1.2
Additional Labels

@rustbot label +l-suggestion-causes-error

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the failure using the code in test_clippy/src/lib.rs and cargo clippy --fix, focusing on the needless_lifetimes lint. Check that the suggested edit leaves the crate compiling and that the necessary 's references remain valid; done means no erroneous suggestion is emitted and cargo clippy --fix completes without E0261 errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.