1 use clippy_utils::consts::{constant, Constant};
2 use clippy_utils::diagnostics::span_lint_and_help;
3 use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 /// Checks for `assert!(true)` and `assert!(false)` calls.
13 /// ### Why is this bad?
14 /// Will be optimized out by the compiler or should probably be replaced by a
15 /// `panic!()` or `unreachable!()`
21 /// const B: bool = false;
24 #[clippy::version = "1.34.0"]
25 pub ASSERTIONS_ON_CONSTANTS,
27 "`assert!(true)` / `assert!(false)` will be optimized out by the compiler, and should probably be replaced by a `panic!()` or `unreachable!()`"
30 declare_lint_pass!(AssertionsOnConstants => [ASSERTIONS_ON_CONSTANTS]);
32 impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
33 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
34 let Some(macro_call) = root_macro_call_first_node(cx, e) else { return };
35 let is_debug = match cx.tcx.get_diagnostic_name(macro_call.def_id) {
36 Some(sym::debug_assert_macro) => true,
37 Some(sym::assert_macro) => false,
40 let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn) else { return };
41 let Some((Constant::Bool(val), _)) = constant(cx, cx.typeck_results(), condition) else { return };
45 ASSERTIONS_ON_CONSTANTS,
48 "`{}!(true)` will be optimized out by the compiler",
49 cx.tcx.item_name(macro_call.def_id)
55 let (assert_arg, panic_arg) = match panic_expn {
56 PanicExpn::Empty => ("", ""),
61 ASSERTIONS_ON_CONSTANTS,
63 &format!("`assert!(false{assert_arg})` should probably be replaced"),
65 &format!("use `panic!({panic_arg})` or `unreachable!({panic_arg})`"),