Skip to content

checked_conversions suggestions in const contexts are not const #8898

@rusty-snake

Description

@rusty-snake

Summary

checked_conversions (default allow; pedantic) suggestions in const contexts are not const.

Lint Name

checked_conversions

Reproducer

I tried this code:

#![allow(dead_code)]
#![warn(clippy::checked_conversions)]

const fn foo(i: u32) -> bool {
    i <= i32::MAX as u32
}
 
fn main() {}

I saw this happen:

    Checking checked_conversions_false_positive v0.1.0 (/home/rusty-snake/checked_conversions_false_positive)
warning: checked cast can be simplified
 --> src/main.rs:5:5
  |
5 |     i <= i32::MAX as u32
  |     ^^^^^^^^^^^^^^^^^^^^ help: try: `i32::try_from(i).is_ok()`
  |
note: the lint level is defined here
 --> src/main.rs:2:9
  |
2 | #![warn(clippy::checked_conversions)]
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#checked_conversions

warning: `checked_conversions_false_positive` (bin "checked_conversions_false_positive") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s

Applied the suggestion an got:

    Checking checked_conversions_false_positive v0.1.0 (/home/rusty-snake/checked_conversions_false_positive)
error[E0015]: cannot call non-const fn `<i32 as std::convert::TryFrom<u32>>::try_from` in constant functions
 --> src/main.rs:5:5
  |
5 |     i32::try_from(i).is_ok()
  |     ^^^^^^^^^^^^^^^^
  |
  = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants

For more information about this error, try `rustc --explain E0015`.
error: could not compile `checked_conversions_false_positive` due to previous error

I expected to see this happen: Suggestion can be applied or lint does not trigger.

Version

rustc 1.61.0 (fe5b13d68 2022-05-18)
binary: rustc
commit-hash: fe5b13d681f25ee6474be29d748c65adcd91f69e
commit-date: 2022-05-18
host: x86_64-unknown-linux-gnu
release: 1.61.0
LLVM version: 14.0.0

Additional Labels

@rusbot label +I-suggestion-causes-error

Metadata

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 have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions