1 use crate::consts::{constant, Constant};
2 use crate::rustc::hir::{Expr, ExprKind};
3 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use crate::rustc::{declare_tool_lint, lint_array};
5 use crate::syntax::ast::LitKind;
6 use crate::utils::{in_macro, is_direct_expn_of, span_help_and_lint};
7 use if_chain::if_chain;
10 /// **What it does:** Check to call assert!(true/false)
12 /// **Why is this bad?** Will be optimized out by the compiler or should probably be replaced by a
13 /// panic!() or unreachable!()
15 /// **Known problems:** None
23 /// const B: bool = false;
26 pub ASSERTIONS_ON_CONSTANTS,
28 "assert!(true/false) will be optimized out by the compiler/should probably be replaced by a panic!() or unreachable!()"
31 pub struct AssertionsOnConstants;
33 impl LintPass for AssertionsOnConstants {
34 fn get_lints(&self) -> LintArray {
35 lint_array![ASSERTIONS_ON_CONSTANTS]
38 fn name(&self) -> &'static str {
39 "AssertionsOnConstants"
43 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
44 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
46 if let Some(assert_span) = is_direct_expn_of(e.span, "assert");
47 if !in_macro(assert_span)
48 || is_direct_expn_of(assert_span, "debug_assert").map_or(false, |span| !in_macro(span));
49 if let ExprKind::Unary(_, ref lit) = e.node;
51 if let ExprKind::Lit(ref inner) = lit.node {
53 LitKind::Bool(true) => {
54 span_help_and_lint(cx, ASSERTIONS_ON_CONSTANTS, e.span,
55 "assert!(true) will be optimized out by the compiler",
58 LitKind::Bool(false) => {
60 cx, ASSERTIONS_ON_CONSTANTS, e.span,
61 "assert!(false) should probably be replaced",
62 "use panic!() or unreachable!()");
66 } else if let Some(bool_const) = constant(cx, cx.tables, lit) {
68 Constant::Bool(true) => {
69 span_help_and_lint(cx, ASSERTIONS_ON_CONSTANTS, e.span,
70 "assert!(const: true) will be optimized out by the compiler",
73 Constant::Bool(false) => {
74 span_help_and_lint(cx, ASSERTIONS_ON_CONSTANTS, e.span,
75 "assert!(const: false) should probably be replaced",
76 "use panic!() or unreachable!()");