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!()`
17 /// ### Known problems
24 /// const B: bool = false;
27 #[clippy::version = "1.34.0"]
28 pub ASSERTIONS_ON_CONSTANTS,
30 "`assert!(true)` / `assert!(false)` will be optimized out by the compiler, and should probably be replaced by a `panic!()` or `unreachable!()`"
33 declare_lint_pass!(AssertionsOnConstants => [ASSERTIONS_ON_CONSTANTS]);
35 impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
36 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
37 let Some(macro_call) = root_macro_call_first_node(cx, e) else { return };
38 let is_debug = match cx.tcx.get_diagnostic_name(macro_call.def_id) {
39 Some(sym::debug_assert_macro) => true,
40 Some(sym::assert_macro) => false,
43 let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn) else { return };
44 let Some((Constant::Bool(val), _)) = constant(cx, cx.typeck_results(), condition) else { return };
48 ASSERTIONS_ON_CONSTANTS,
51 "`{}!(true)` will be optimized out by the compiler",
52 cx.tcx.item_name(macro_call.def_id)
58 let (assert_arg, panic_arg) = match panic_expn {
59 PanicExpn::Empty => ("", ""),
64 ASSERTIONS_ON_CONSTANTS,
66 &format!("`assert!(false{})` should probably be replaced", assert_arg),
68 &format!("use `panic!({})` or `unreachable!({0})`", panic_arg),