Skip to content

FP bool-to-int-with-if in const context #10452

Closed
@matthiaskrgr

Description

Summary

.

Lint Name

bool-to-int-with-if

Reproducer

I tried this code:

fn main() {
    let _ = [0; { 
         if false { 0 } else { 1 }
    }];
}

I saw this happen:

 --> feature-gate-const-if-match.rs:3:10
  |
3 |          if false { 0 } else { 1 }
  |          ^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with from: `usize::from(!false)`

The problem here is that the lint probably just checks "am I inside a const fn" but this is some which is false, BUT we are inside an array which still is some sort of const context and the lint misses this.
So the if false { 0 } else { 1 } is probably const-eval'd but this does not work with

fn main() {
    let _ = [0; { 
         usize::from(!false)
    }];
}
error[E0015]: cannot call non-const fn `<usize as std::convert::From<bool>>::from` in constants
 --> feature-gate-const-if-match.rs:3:10
  |
3 |          usize::from(!false)
  |          ^^^^^^^^^^^^^^^^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants
  = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable

Version

rustc 1.69.0-nightly (44cfafe2f 2023-03-03)
binary: rustc
commit-hash: 44cfafe2fafe816395d3acc434663a45d5178c41
commit-date: 2023-03-03
host: x86_64-unknown-linux-gnu
release: 1.69.0-nightly
LLVM version: 15.0.7

Additional Labels

No response

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions