rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`missing_const_for_fn` falsely claims Iterator can be dropped in const context

Open Lars-Schumann opened this issue 11 months ago • 1 comments

Summary

This lint disagrees with rustc if a function can be const in certain situations involving the nightly #![feature(const_trait_impl)].

Lint Name

missing_const_for_fn

Reproducer

I tried this code:

#![feature(const_trait_impl)]
pub const trait All {
    fn all() -> impl Iterator<Item = Self>;
}
impl const All for i32 {
    fn all() -> impl Iterator<Item = Self> {
        Self::MIN..=Self::MAX
    }
}

#[deny(clippy::missing_const_for_fn)]
fn breaks() {
    let x = i32::all();
}

I saw this happen:

error: this could be a `const fn`
  --> src/lib.rs:12:1
   |
12 | / fn breaks() {
13 | |     let x = i32::all();
14 | | }
   | |_^

I expected to see this happen:

This lint is a false positive here, as following the suggestion leads to:

error[E0493]: destructor of `impl std::iter::Iterator<Item = i32>` cannot be evaluated at compile-time
  --> src/lib.rs:13:9
   |
13 |     let x = i32::all();
   |         ^ the destructor for this type cannot be evaluated in constant functions
14 | }
   | - value is dropped here

Version

rustc 1.94.0-nightly (21cf7fb3f 2025-12-28)
binary: rustc
commit-hash: 21cf7fb3ff9159b0b562431312969dd548ae8782
commit-date: 2025-12-28
host: x86_64-unknown-linux-gnu
release: 1.94.0-nightly
LLVM version: 21.1.8

Additional Labels

@rustbot label +I-suggestion-causes-error

Lars-Schumann avatar Dec 30 '25 02:12 Lars-Schumann

The MIR for the reproducer:

fn <impl at ./src/main.rs:6:1: 6:23>::all() -> std::ops::RangeInclusive<i32> {
    let mut _0: std::ops::RangeInclusive<i32>;

    bb0: {
        _0 = std::ops::RangeInclusive::<i32>::new(const core::num::<impl i32>::MIN, const core::num::<impl i32>::MAX) -> [return: bb1, unwind continue];
    }

    bb1: {
        return;
    }
}

// MIR FOR CTFE
fn <impl at ./src/main.rs:6:1: 6:23>::all() -> std::ops::RangeInclusive<i32> {
    let mut _0: std::ops::RangeInclusive<i32>;

    bb0: {
        ConstEvalCounter;
        _0 = std::ops::RangeInclusive::<i32>::new(const core::num::<impl i32>::MIN, const core::num::<impl i32>::MAX) -> [return: bb1, unwind continue];
    }

    bb1: {
        return;
    }
}

fn breaks() -> () {
    let mut _0: ();
    let _1: std::ops::RangeInclusive<i32>;
    scope 1 {
        debug x => _1;
    }

    bb0: {
        _1 = <i32 as All>::all() -> [return: bb1, unwind continue];
    }

    bb1: {
        return;
    }
}

I doubt if this is a compiler bug

profetia avatar Dec 30 '25 20:12 profetia