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