|
| 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::{is_direct_expn_of, span_help_and_lint}; |
| 7 | +use if_chain::if_chain; |
| 8 | + |
| 9 | +/// **What it does:** Check to call assert!(true/false) |
| 10 | +/// |
| 11 | +/// **Why is this bad?** Will be optimized out by the compiler or should probably be replaced by a |
| 12 | +/// panic!() or unreachable!() |
| 13 | +/// |
| 14 | +/// **Known problems:** None |
| 15 | +/// |
| 16 | +/// **Example:** |
| 17 | +/// ```rust |
| 18 | +/// assert!(false) |
| 19 | +/// // or |
| 20 | +/// assert!(true) |
| 21 | +/// // or |
| 22 | +/// const B: bool = false; |
| 23 | +/// assert!(B) |
| 24 | +/// ``` |
| 25 | +declare_clippy_lint! { |
| 26 | + pub ASSERTIONS_ON_CONSTANTS, |
| 27 | + style, |
| 28 | + "assert!(true/false) will be optimized out by the compiler/should probably be replaced by a panic!() or unreachable!()" |
| 29 | +} |
| 30 | + |
| 31 | +pub struct AssertionsOnConstants; |
| 32 | + |
| 33 | +impl LintPass for AssertionsOnConstants { |
| 34 | + fn get_lints(&self) -> LintArray { |
| 35 | + lint_array![ASSERTIONS_ON_CONSTANTS] |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants { |
| 40 | + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) { |
| 41 | + if_chain! { |
| 42 | + if is_direct_expn_of(e.span, "assert").is_some(); |
| 43 | + if let ExprKind::Unary(_, ref lit) = e.node; |
| 44 | + then { |
| 45 | + if let ExprKind::Lit(ref inner) = lit.node { |
| 46 | + match inner.node { |
| 47 | + LitKind::Bool(true) => { |
| 48 | + span_help_and_lint(cx, ASSERTIONS_ON_CONSTANTS, e.span, |
| 49 | + "assert!(true) will be optimized out by the compiler", |
| 50 | + "remove it"); |
| 51 | + }, |
| 52 | + LitKind::Bool(false) => { |
| 53 | + span_help_and_lint( |
| 54 | + cx, ASSERTIONS_ON_CONSTANTS, e.span, |
| 55 | + "assert!(false) should probably be replaced", |
| 56 | + "use panic!() or unreachable!()"); |
| 57 | + }, |
| 58 | + _ => (), |
| 59 | + } |
| 60 | + } else if let Some(bool_const) = constant(cx, cx.tables, lit) { |
| 61 | + match bool_const.0 { |
| 62 | + Constant::Bool(true) => { |
| 63 | + span_help_and_lint(cx, ASSERTIONS_ON_CONSTANTS, e.span, |
| 64 | + "assert!(const: true) will be optimized out by the compiler", |
| 65 | + "remove it"); |
| 66 | + }, |
| 67 | + Constant::Bool(false) => { |
| 68 | + span_help_and_lint(cx, ASSERTIONS_ON_CONSTANTS, e.span, |
| 69 | + "assert!(const: false) should probably be replaced", |
| 70 | + "use panic!() or unreachable!()"); |
| 71 | + }, |
| 72 | + _ => (), |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments