|
| 1 | +// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 6 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 7 | +// option. This file may not be copied, modified, or distributed |
| 8 | +// except according to those terms. |
| 9 | + |
| 10 | +use crate::rustc::hir::{Expr, ExprKind}; |
| 11 | +use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; |
| 12 | +use crate::rustc::{declare_tool_lint, lint_array}; |
| 13 | +use crate::syntax::ast::LitKind; |
| 14 | +use crate::utils::{is_direct_expn_of, span_lint}; |
| 15 | +use if_chain::if_chain; |
| 16 | + |
| 17 | +/// **What it does:** Check explicit call assert!(true) |
| 18 | +/// |
| 19 | +/// **Why is this bad?** Will be optimized out by the compiler |
| 20 | +/// |
| 21 | +/// **Known problems:** None |
| 22 | +/// |
| 23 | +/// **Example:** |
| 24 | +/// ```rust |
| 25 | +/// assert!(true) |
| 26 | +/// ``` |
| 27 | +declare_clippy_lint! { |
| 28 | + pub EXPLICIT_TRUE, |
| 29 | + correctness, |
| 30 | + "assert!(true) will be optimized out by the compiler" |
| 31 | +} |
| 32 | + |
| 33 | +/// **What it does:** Check explicit call assert!(false) |
| 34 | +/// |
| 35 | +/// **Why is this bad?** Should probably be replaced by a panic!() |
| 36 | +/// |
| 37 | +/// **Known problems:** None |
| 38 | +/// |
| 39 | +/// **Example:** |
| 40 | +/// ```rust |
| 41 | +/// assert!(false) |
| 42 | +/// ``` |
| 43 | +declare_clippy_lint! { |
| 44 | + pub EXPLICIT_FALSE, |
| 45 | + correctness, |
| 46 | + "assert!(false) should probably be replaced by a panic!()r" |
| 47 | +} |
| 48 | + |
| 49 | +pub struct AssertChecks; |
| 50 | + |
| 51 | +impl LintPass for AssertChecks { |
| 52 | + fn get_lints(&self) -> LintArray { |
| 53 | + lint_array![EXPLICIT_TRUE, EXPLICIT_FALSE] |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertChecks { |
| 58 | + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) { |
| 59 | + if_chain! { |
| 60 | + if is_direct_expn_of(e.span, "assert").is_some(); |
| 61 | + if let ExprKind::Unary(_, ref lit) = e.node; |
| 62 | + if let ExprKind::Lit(ref inner) = lit.node; |
| 63 | + then { |
| 64 | + match inner.node { |
| 65 | + LitKind::Bool(true) => { |
| 66 | + span_lint(cx, EXPLICIT_TRUE, e.span, |
| 67 | + "assert!(true) will be optimized out by the compiler"); |
| 68 | + }, |
| 69 | + LitKind::Bool(false) => { |
| 70 | + span_lint(cx, EXPLICIT_FALSE, e.span, |
| 71 | + "assert!(false) should probably be replaced by a panic!()"); |
| 72 | + }, |
| 73 | + _ => (), |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments