Skip to content

Commit dd857f8

Browse files
committed
Auto merge of #11966 - StackOverflowExcept1on:issue-8159, r=Jarcho
Do not lint `assertions_on_constants` for `const _: () = assert!(expr)` Fixes #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
2 parents f9b5def + 90ece56 commit dd857f8

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

clippy_lints/src/assertions_on_constants.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use clippy_utils::consts::{constant, Constant};
1+
use clippy_utils::consts::{constant_with_source, Constant, ConstantSource};
22
use clippy_utils::diagnostics::span_lint_and_help;
33
use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn};
4-
use rustc_hir::Expr;
4+
use rustc_hir::{Expr, Item, ItemKind, Node};
55
use rustc_lint::{LateContext, LateLintPass};
66
use rustc_session::declare_lint_pass;
77
use rustc_span::sym;
@@ -42,9 +42,18 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
4242
let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn) else {
4343
return;
4444
};
45-
let Some(Constant::Bool(val)) = constant(cx, cx.typeck_results(), condition) else {
45+
let Some((Constant::Bool(val), source)) = constant_with_source(cx, cx.typeck_results(), condition) else {
4646
return;
4747
};
48+
if let ConstantSource::Constant = source
49+
&& let Some(node) = cx.tcx.hir().find_parent(e.hir_id)
50+
&& let Node::Item(Item {
51+
kind: ItemKind::Const(..),
52+
..
53+
}) = node
54+
{
55+
return;
56+
}
4857
if val {
4958
span_lint_and_help(
5059
cx,

tests/ui/assertions_on_constants.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,11 @@ fn main() {
4545

4646
const CFG_FLAG: &bool = &cfg!(feature = "hey");
4747
assert!(!CFG_FLAG);
48+
49+
const _: () = assert!(true);
50+
//~^ ERROR: `assert!(true)` will be optimized out by the compiler
51+
52+
// Don't lint if the value is dependent on a defined constant:
53+
const N: usize = 1024;
54+
const _: () = assert!(N.is_power_of_two());
4855
}

tests/ui/assertions_on_constants.stderr

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,5 +72,13 @@ LL | debug_assert!(true);
7272
|
7373
= help: remove it
7474

75-
error: aborting due to 9 previous errors
75+
error: `assert!(true)` will be optimized out by the compiler
76+
--> $DIR/assertions_on_constants.rs:49:19
77+
|
78+
LL | const _: () = assert!(true);
79+
| ^^^^^^^^^^^^^
80+
|
81+
= help: remove it
82+
83+
error: aborting due to 10 previous errors
7684

0 commit comments

Comments
 (0)