]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assertions_on_constants.rs
Auto merge of #4879 - matthiaskrgr:rustup_23, 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_help_and_lint};
4 use if_chain::if_chain;
5 use rustc::declare_lint_pass;
6 use rustc::hir::*;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc_session::declare_tool_lint;
9 use syntax::ast::LitKind;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for `assert!(true)` and `assert!(false)` calls.
13     ///
14     /// **Why is this bad?** Will be optimized out by the compiler or should probably be replaced by a
15     /// panic!() or unreachable!()
16     ///
17     /// **Known problems:** None
18     ///
19     /// **Example:**
20     /// ```rust,ignore
21     /// assert!(false)
22     /// // or
23     /// assert!(true)
24     /// // or
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<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants {
36     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
37         let lint_true = || {
38             span_help_and_lint(
39                 cx,
40                 ASSERTIONS_ON_CONSTANTS,
41                 e.span,
42                 "`assert!(true)` will be optimized out by the compiler",
43                 "remove it",
44             );
45         };
46         let lint_false_without_message = || {
47             span_help_and_lint(
48                 cx,
49                 ASSERTIONS_ON_CONSTANTS,
50                 e.span,
51                 "`assert!(false)` should probably be replaced",
52                 "use `panic!()` or `unreachable!()`",
53             );
54         };
55         let lint_false_with_message = |panic_message: String| {
56             span_help_and_lint(
57                 cx,
58                 ASSERTIONS_ON_CONSTANTS,
59                 e.span,
60                 &format!("`assert!(false, {})` should probably be replaced", panic_message),
61                 &format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message),
62             )
63         };
64
65         if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") {
66             if debug_assert_span.from_expansion() {
67                 return;
68             }
69             if_chain! {
70                 if let ExprKind::Unary(_, ref lit) = e.kind;
71                 if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, lit);
72                 if is_true;
73                 then {
74                     lint_true();
75                 }
76             };
77         } else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") {
78             if assert_span.from_expansion() {
79                 return;
80             }
81             if let Some(assert_match) = match_assert_with_message(&cx, e) {
82                 match assert_match {
83                     // matched assert but not message
84                     AssertKind::WithoutMessage(false) => lint_false_without_message(),
85                     AssertKind::WithoutMessage(true) | AssertKind::WithMessage(_, true) => lint_true(),
86                     AssertKind::WithMessage(panic_message, false) => lint_false_with_message(panic_message),
87                 };
88             }
89         }
90     }
91 }
92
93 /// Result of calling `match_assert_with_message`.
94 enum AssertKind {
95     WithMessage(String, bool),
96     WithoutMessage(bool),
97 }
98
99 /// Check if the expression matches
100 ///
101 /// ```rust,ignore
102 /// match { let _t = !c; _t } {
103 ///     true => {
104 ///         {
105 ///             ::std::rt::begin_panic(message, _)
106 ///         }
107 ///     }
108 ///     _ => { }
109 /// };
110 /// ```
111 ///
112 /// where `message` is any expression and `c` is a constant bool.
113 fn match_assert_with_message<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<AssertKind> {
114     if_chain! {
115         if let ExprKind::Match(ref expr, ref arms, _) = expr.kind;
116         // matches { let _t = expr; _t }
117         if let ExprKind::DropTemps(ref expr) = expr.kind;
118         if let ExprKind::Unary(UnOp::UnNot, ref expr) = expr.kind;
119         // bind the first argument of the `assert!` macro
120         if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, expr);
121         // arm 1 pattern
122         if let PatKind::Lit(ref lit_expr) = arms[0].pat.kind;
123         if let ExprKind::Lit(ref lit) = lit_expr.kind;
124         if let LitKind::Bool(true) = lit.node;
125         // arm 1 block
126         if let ExprKind::Block(ref block, _) = arms[0].body.kind;
127         if block.stmts.len() == 0;
128         if let Some(block_expr) = &block.expr;
129         if let ExprKind::Block(ref inner_block, _) = block_expr.kind;
130         if let Some(begin_panic_call) = &inner_block.expr;
131         // function call
132         if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
133         if args.len() == 2;
134         // bind the second argument of the `assert!` macro if it exists
135         if let panic_message = snippet_opt(cx, args[0].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 }