rust/clippy_lints/src/assertions_on_constants.rs

70 lines
2.6 KiB
Rust
Raw Normal View History

use clippy_utils::consts::{constant, Constant};
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;
2020-01-12 00:08:41 -06:00
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 05:37:08 -06:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// Checks for `assert!(true)` and `assert!(false)` calls.
///
/// ### Why is this bad?
/// Will be optimized out by the compiler or should probably be replaced by a
2020-03-17 20:50:39 -05:00
/// `panic!()` or `unreachable!()`
///
/// ### Example
2019-03-10 17:01:56 -05:00
/// ```rust,ignore
2019-01-30 19:15:29 -06:00
/// assert!(false)
/// assert!(true)
/// const B: bool = false;
2019-01-30 19:15:29 -06:00
/// assert!(B)
/// ```
#[clippy::version = "1.34.0"]
pub ASSERTIONS_ON_CONSTANTS,
style,
2019-03-10 12:19:47 -05:00
"`assert!(true)` / `assert!(false)` will be optimized out by the compiler, and should probably be replaced by a `panic!()` or `unreachable!()`"
}
2019-04-08 15:43:55 -05:00
declare_lint_pass!(AssertionsOnConstants => [ASSERTIONS_ON_CONSTANTS]);
impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
let Some(macro_call) = root_macro_call_first_node(cx, e) else { return };
let is_debug = match cx.tcx.get_diagnostic_name(macro_call.def_id) {
Some(sym::debug_assert_macro) => true,
Some(sym::assert_macro) => false,
_ => return,
2019-10-07 15:08:00 -05:00
};
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 { return };
if val {
span_lint_and_help(
2019-10-07 15:08:00 -05:00
cx,
ASSERTIONS_ON_CONSTANTS,
macro_call.span,
&format!(
"`{}!(true)` will be optimized out by the compiler",
cx.tcx.item_name(macro_call.def_id)
),
None,
"remove it",
2019-10-07 15:08:00 -05:00
);
} else if !is_debug {
let (assert_arg, panic_arg) = match panic_expn {
PanicExpn::Empty => ("", ""),
_ => (", ..", ".."),
};
span_lint_and_help(
2019-10-07 15:08:00 -05:00
cx,
ASSERTIONS_ON_CONSTANTS,
macro_call.span,
&format!("`assert!(false{assert_arg})` should probably be replaced"),
None,
&format!("use `panic!({panic_arg})` or `unreachable!({panic_arg})`"),
);
}
}
2019-10-06 13:10:30 -05:00
}