Skip to content

False positive assertions_on_constants #8159

Closed
@rukai

Description

@rukai

Summary

assert!(true) will be optimized out by the compiler is given when asserting on constants.
Asserting on constants is very important for ensuring various kinds of invariants are upheld.

The example given in the recent announcement for panic in const contexts functionality doesn't reproduce the issue but the issue can still be reproduced in const contexts.

Lint Name

assertions_on_constants

Reproducer

I tried this code:

const FOO: usize = 100;
const BAR: usize = 0;

pub fn main() {
    assert!(FOO > BAR); // false positive
    const _: () = assert!(FOO > BAR); // false positive
    const _: () = assert!(std::mem::size_of::<u8>() > BAR); // true negative
    const _: () = assert!(std::mem::size_of::<u8>() == 1); // true negative
}

I saw this happen:

 1  warning: `assert!(true)` will be optimized out by the compiler
  --> src/main.rs:5:5
   |
 5 |     assert!(FOO > BAR); // false positive
   |     ^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(clippy::assertions_on_constants)]` on by default
   = help: remove it
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants
   = note: this warning originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)
 
 2  warning: `assert!(true)` will be optimized out by the compiler
  --> src/main.rs:6:19
   |
 6 |     const _: () = assert!(FOO > BAR); // false positive
   |                   ^^^^^^^^^^^^^^^^^^
   |
   = help: remove it
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants
   = note: this warning originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)
 
 3  warning: `foo` (bin "foo") generated 2 warnings
 4  warning: `foo` (bin "foo" test) generated 2 warnings (2 duplicates)

I expected to see this happen: No warnings

Version

rustc 1.57.0 (f1edd0429 2021-11-29)
binary: rustc
commit-hash: f1edd0429582dd29cccacaf50fd134b05593bd9c
commit-date: 2021-11-29
host: x86_64-unknown-linux-gnu
release: 1.57.0
LLVM version: 13.0.0

Additional Labels

No response

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