rust-lang / rust-lang/rust-clippy

FP: `unused_self` triggers if only the lifetime of `self` is used

Open
#4,928 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Tested on clippy shipping with Rust 1.40.0:

C:\>cargo clippy -V
clippy 0.0.212 (c8e3cfbd 2019-10-28)

Here's a contrived example that triggers the unused_self lint and fails to build:

#![deny(clippy::unused_self)]

use std::marker::PhantomData;

pub struct A;

pub struct B<'a>(PhantomData<&'a A>);

impl A {
    pub fn b(&self) -> B<'_> {
        B(PhantomData)
    }
}

This is actually a valid pattern. In FFI code for instance, A might be responsible for initialising and freeing some part of a library, and the function b is used to create objects that belong to the library, and therefore can't outlive it. So A can just be a ZST while B uses PhantomData<&'a A> to convey ownership semantics.

If we rewrite the example so it directly uses self it works:

#![deny(clippy::unused_self)]

pub struct A;

pub struct B<'a>(&'a A);

impl A {
    pub fn b(&self) -> B<'_> {
        B(self)
    }
}

But we don't want to hold pointers to A, we just want to express that instances of B belong to an instance of A.

tl;dr unused_self doesn't catch edge cases where self is used without actually being used.

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

Start at the Clippy unused_self lint and reproduce both Rust examples from the issue. Check that lifetime-only use through PhantomData<&'a A> is accepted while genuinely unused self is still reported; done means the false positive no longer prevents the first example from building.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.