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