]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assertions_on_constants.rs
Documented constant expression evaluation for `repeat_once`
[rust.git] / clippy_lints / src / assertions_on_constants.rs
1 use clippy_utils::consts::{constant, Constant};
2 use clippy_utils::diagnostics::span_lint_and_help;
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::{is_direct_expn_of, is_expn_of, match_panic_call};
5 use if_chain::if_chain;
6 use rustc_hir::{Expr, ExprKind, UnOp};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for `assert!(true)` and `assert!(false)` calls.
12     ///
13     /// **Why is this bad?** Will be optimized out by the compiler or should probably be replaced by a
14     /// `panic!()` or `unreachable!()`
15     ///
16     /// **Known problems:** None
17     ///
18     /// **Example:**
19     /// ```rust,ignore
20     /// assert!(false)
21     /// assert!(true)
22     /// const B: bool = false;
23     /// assert!(B)
24     /// ```
25     pub ASSERTIONS_ON_CONSTANTS,
26     style,
27     "`assert!(true)` / `assert!(false)` will be optimized out by the compiler, and should probably be replaced by a `panic!()` or `unreachable!()`"
28 }
29
30 declare_lint_pass!(AssertionsOnConstants => [ASSERTIONS_ON_CONSTANTS]);
31
32 impl<'tcx> LateLintPass<'tcx> for AssertionsOnConstants {
33     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
34         let lint_true = |is_debug: bool| {
35             span_lint_and_help(
36                 cx,
37                 ASSERTIONS_ON_CONSTANTS,
38                 e.span,
39                 if is_debug {
40                     "`debug_assert!(true)` will be optimized out by the compiler"
41                 } else {
42                     "`assert!(true)` will be optimized out by the compiler"
43                 },
44                 None,
45                 "remove it",
46             );
47         };
48         let lint_false_without_message = || {
49             span_lint_and_help(
50                 cx,
51                 ASSERTIONS_ON_CONSTANTS,
52                 e.span,
53                 "`assert!(false)` should probably be replaced",
54                 None,
55                 "use `panic!()` or `unreachable!()`",
56             );
57         };
58         let lint_false_with_message = |panic_message: String| {
59             span_lint_and_help(
60                 cx,
61                 ASSERTIONS_ON_CONSTANTS,
62                 e.span,
63                 &format!("`assert!(false, {})` should probably be replaced", panic_message),
64                 None,
65                 &format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message),
66             );
67         };
68
69         if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") {
70             if debug_assert_span.from_expansion() {
71                 return;
72             }
73             if_chain! {
74                 if let ExprKind::Unary(_, lit) = e.kind;
75                 if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.typeck_results(), lit);
76                 if is_true;
77                 then {
78                     lint_true(true);
79                 }
80             };
81         } else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") {
82             if assert_span.from_expansion() {
83                 return;
84             }
85             if let Some(assert_match) = match_assert_with_message(cx, e) {
86                 match assert_match {
87                     // matched assert but not message
88                     AssertKind::WithoutMessage(false) => lint_false_without_message(),
89                     AssertKind::WithoutMessage(true) | AssertKind::WithMessage(_, true) => lint_true(false),
90                     AssertKind::WithMessage(panic_message, false) => lint_false_with_message(panic_message),
91                 };
92             }
93         }
94     }
95 }
96
97 /// Result of calling `match_assert_with_message`.
98 enum AssertKind {
99     WithMessage(String, bool),
100     WithoutMessage(bool),
101 }
102
103 /// Check if the expression matches
104 ///
105 /// ```rust,ignore
106 /// if !c {
107 ///   {
108 ///     ::std::rt::begin_panic(message, _)
109 ///   }
110 /// }
111 /// ```
112 ///
113 /// where `message` is any expression and `c` is a constant bool.
114 fn match_assert_with_message<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<AssertKind> {
115     if_chain! {
116         if let ExprKind::If(cond, then, _) = expr.kind;
117         if let ExprKind::Unary(UnOp::Not, expr) = cond.kind;
118         // bind the first argument of the `assert!` macro
119         if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.typeck_results(), expr);
120         // block
121         if let ExprKind::Block(block, _) = then.kind;
122         if block.stmts.is_empty();
123         if let Some(block_expr) = &block.expr;
124         // inner block is optional. unwrap it if it exists, or use the expression as is otherwise.
125         if let Some(begin_panic_call) = match block_expr.kind {
126             ExprKind::Block(inner_block, _) => &inner_block.expr,
127             _ => &block.expr,
128         };
129         // function call
130         if let Some(arg) = match_panic_call(cx, begin_panic_call);
131         // bind the second argument of the `assert!` macro if it exists
132         if let panic_message = snippet_opt(cx, arg.span);
133         // second argument of begin_panic is irrelevant
134         // as is the second match arm
135         then {
136             // an empty message occurs when it was generated by the macro
137             // (and not passed by the user)
138             return panic_message
139                 .filter(|msg| !msg.is_empty())
140                 .map(|msg| AssertKind::WithMessage(msg, is_true))
141                 .or(Some(AssertKind::WithoutMessage(is_true)));
142         }
143     }
144     None
145 }