Skip to content

Commit

Permalink
Auto merge of rust-lang#11966 - StackOverflowExcept1on:issue-8159, r=…
Browse files Browse the repository at this point in the history
…Jarcho

Do not lint `assertions_on_constants` for `const _: () = assert!(expr)`

Fixes rust-lang#8159

```rust
pub fn f() {
    // warning
    assert!(true);
    assert!(usize::BITS >= 32);

    // ok
    const _: () = assert!(usize::BITS >= 32);
}
```

changelog: Fix `const _: () = assert!(expr)` false positive on `assertions_on_constants` lint
  • Loading branch information
bors committed Dec 17, 2023
2 parents f9b5def + 90ece56 commit dd857f8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
15 changes: 12 additions & 3 deletions clippy_lints/src/assertions_on_constants.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clippy_utils::consts::{constant, Constant};
use clippy_utils::consts::{constant_with_source, Constant, ConstantSource};
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn};
use rustc_hir::Expr;
use rustc_hir::{Expr, Item, ItemKind, Node};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::sym;
Expand Down Expand Up @@ -42,9 +42,18 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn) else {
return;
};
let Some(Constant::Bool(val)) = constant(cx, cx.typeck_results(), condition) else {
let Some((Constant::Bool(val), source)) = constant_with_source(cx, cx.typeck_results(), condition) else {
return;
};
if let ConstantSource::Constant = source
&& let Some(node) = cx.tcx.hir().find_parent(e.hir_id)
&& let Node::Item(Item {
kind: ItemKind::Const(..),
..
}) = node
{
return;
}
if val {
span_lint_and_help(
cx,
Expand Down
7 changes: 7 additions & 0 deletions tests/ui/assertions_on_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,11 @@ fn main() {

const CFG_FLAG: &bool = &cfg!(feature = "hey");
assert!(!CFG_FLAG);

const _: () = assert!(true);
//~^ ERROR: `assert!(true)` will be optimized out by the compiler

// Don't lint if the value is dependent on a defined constant:
const N: usize = 1024;
const _: () = assert!(N.is_power_of_two());
}
10 changes: 9 additions & 1 deletion tests/ui/assertions_on_constants.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,13 @@ LL | debug_assert!(true);
|
= help: remove it

error: aborting due to 9 previous errors
error: `assert!(true)` will be optimized out by the compiler
--> $DIR/assertions_on_constants.rs:49:19
|
LL | const _: () = assert!(true);
| ^^^^^^^^^^^^^
|
= help: remove it

error: aborting due to 10 previous errors

0 comments on commit dd857f8

Please sign in to comment.