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