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