rust-lang / rust-lang/rust-clippy

Wrong suggestion of `const fn` if member of member implements Drop

Open
#4,979 2 comments 12 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug E-hard L-nursery
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

cargo clippy -V: clippy 0.0.212 (c807fbc 2019-12-29)
rustc -V: rustc 1.40.0 (73528e339 2019-12-16)

Summary

A warning "this could be a const_fn" is triggered for a function of a struct that doesn't implement Drop, but on some level of depth contains a member that does implement it. Adding const to such function results in compilation error.

Steps to reproduce

Run the following code with cargo clippy -- -W clippy::missing-const-for-fn:

#![allow(dead_code)]

struct Foo {
    field: String
}

impl Foo {
    fn take(self) -> String {
        self.field
    }
}

fn main() {
}

It results in a warning:

warning: this could be a const_fn
  --> src/main.rs:8:5
   |
8  | /     fn take(self) -> String {
9  | |         self.field
10 | |     }
   | |_____^
   |
   = note: requested on the command line with `-W clippy::missing-const-for-fn`
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn

After adding const to the function Foo::take we get an error:

error[E0493]: destructors cannot be evaluated at compile-time
 --> src/main.rs:8:19
  |
8 |     const fn take(self) -> String {
  |                   ^^^^ constant functions cannot evaluate destructors

Note that Foo doesn't implement Drop, its field String also doesn't, but String's field Vec does implement it.
Also note there was already a similar fixed issue, but for structs that implement Drop: https://github.com/rust-lang/rust-clippy/issues/4449

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 by reproducing the report with cargo clippy and -W clippy::missing-const-for-fn using the Rust example in the issue. Trace the missing-const-for-fn lint and verify that it no longer suggests const fn when a nested member has a destructor, while valid suggestions remain unaffected.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.