]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assertions_on_constants.rs
Auto merge of #4635 - Lythenas:suggestions-for-assert-false, 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_def_path, snippet_opt, span_help_and_lint};
4 use if_chain::if_chain;
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{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 = || {
37             span_help_and_lint(
38                 cx,
39                 ASSERTIONS_ON_CONSTANTS,
40                 e.span,
41                 "`assert!(true)` will be optimized out by the compiler",
42                 "remove it",
43             );
44         };
45         let lint_false_without_message = || {
46             span_help_and_lint(
47                 cx,
48                 ASSERTIONS_ON_CONSTANTS,
49                 e.span,
50                 "`assert!(false)` should probably be replaced",
51                 "use `panic!()` or `unreachable!()`",
52             );
53         };
54         let lint_false_with_message = |panic_message: String| {
55             span_help_and_lint(
56                 cx,
57                 ASSERTIONS_ON_CONSTANTS,
58                 e.span,
59                 &format!("`assert!(false, {})` should probably be replaced", panic_message),
60                 &format!("use `panic!({})` or `unreachable!({})`", panic_message, panic_message),
61             )
62         };
63
64         if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") {
65             if debug_assert_span.from_expansion() {
66                 return;
67             }
68             if_chain! {
69                 if let ExprKind::Unary(_, ref lit) = e.kind;
70                 if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, lit);
71                 if is_true;
72                 then {
73                     lint_true();
74                 }
75             };
76         } else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") {
77             if assert_span.from_expansion() {
78                 return;
79             }
80             if let Some(assert_match) = match_assert_with_message(&cx, e) {
81                 match assert_match {
82                     // matched assert but not message
83                     AssertKind::WithoutMessage(false) => lint_false_without_message(),
84                     AssertKind::WithoutMessage(true) | AssertKind::WithMessage(_, true) => lint_true(),
85                     AssertKind::WithMessage(panic_message, false) => lint_false_with_message(panic_message),
86                 };
87             }
88         }
89     }
90 }
91
92 /// Result of calling `match_assert_with_message`.
93 enum AssertKind {
94     WithMessage(String, bool),
95     WithoutMessage(bool),
96 }
97
98 /// Check if the expression matches
99 ///
100 /// ```rust,ignore
101 /// match { let _t = !c; _t } {
102 ///     true => {
103 ///         {
104 ///             ::std::rt::begin_panic(message, _)
105 ///         }
106 ///     }
107 ///     _ => { }
108 /// };
109 /// ```
110 ///
111 /// where `message` is any expression and `c` is a constant bool.
112 fn match_assert_with_message<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<AssertKind> {
113     if_chain! {
114         if let ExprKind::Match(ref expr, ref arms, _) = expr.kind;
115         // matches { let _t = expr; _t }
116         if let ExprKind::DropTemps(ref expr) = expr.kind;
117         if let ExprKind::Unary(UnOp::UnNot, ref expr) = expr.kind;
118         // bind the first argument of the `assert!` macro
119         if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, expr);
120         // arm 1 pattern
121         if let PatKind::Lit(ref lit_expr) = arms[0].pat.kind;
122         if let ExprKind::Lit(ref lit) = lit_expr.kind;
123         if let LitKind::Bool(true) = lit.node;
124         // arm 1 block
125         if let ExprKind::Block(ref block, _) = arms[0].body.kind;
126         if block.stmts.len() == 0;
127         if let Some(block_expr) = &block.expr;
128         if let ExprKind::Block(ref inner_block, _) = block_expr.kind;
129         if let Some(begin_panic_call) = &inner_block.expr;
130         // function call
131         if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
132         if args.len() == 2;
133         // bind the second argument of the `assert!` macro if it exists
134         if let panic_message = snippet_opt(cx, args[0].span);
135         // second argument of begin_panic is irrelevant
136         // as is the second match arm
137         then {
138             // an empty message occurs when it was generated by the macro
139             // (and not passed by the user)
140             return panic_message
141                 .filter(|msg| !msg.is_empty())
142                 .map(|msg| AssertKind::WithMessage(msg, is_true))
143                 .or(Some(AssertKind::WithoutMessage(is_true)));
144         }
145     }
146     None
147 }
148
149 /// Matches a function call with the given path and returns the arguments.
150 ///
151 /// Usage:
152 ///
153 /// ```rust,ignore
154 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
155 /// ```
156 fn match_function_call<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, path: &[&str]) -> Option<&'a [Expr]> {
157     if_chain! {
158         if let ExprKind::Call(ref fun, ref args) = expr.kind;
159         if let ExprKind::Path(ref qpath) = fun.kind;
160         if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
161         if match_def_path(cx, fun_def_id, path);
162         then {
163             return Some(&args)
164         }
165     };
166     None
167 }