]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/assertions_on_constants.rs
Make if_chain more readable
[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, resolve_node, 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 use syntax::source_map::symbol::LocalInternedString;
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_assert_cb = |is_debug_assert: bool| {
38             if let ExprKind::Unary(_, ref lit) = e.kind {
39                 if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, lit) {
40                     if is_true {
41                         span_help_and_lint(
42                             cx,
43                             ASSERTIONS_ON_CONSTANTS,
44                             e.span,
45                             "`assert!(true)` will be optimized out by the compiler",
46                             "remove it",
47                         );
48                     } else if !is_debug_assert {
49                         span_help_and_lint(
50                             cx,
51                             ASSERTIONS_ON_CONSTANTS,
52                             e.span,
53                             "`assert!(false)` should probably be replaced",
54                             "use `panic!()` or `unreachable!()`",
55                         );
56                     }
57                 }
58             }
59         };
60         if let Some(debug_assert_span) = is_expn_of(e.span, "debug_assert") {
61             if debug_assert_span.from_expansion() {
62                 return;
63             }
64             lint_assert_cb(true);
65         } else if let Some(assert_span) = is_direct_expn_of(e.span, "assert") {
66             if assert_span.from_expansion() {
67                 return;
68             }
69             if let Some((panic_message, is_true)) = assert_with_message(&cx, e) {
70                 if is_true {
71                     span_help_and_lint(
72                         cx,
73                         ASSERTIONS_ON_CONSTANTS,
74                         e.span,
75                         "`assert!(true)` will be optimized out by the compiler",
76                         "remove it",
77                     );
78                 } else if panic_message.starts_with("assertion failed: ") {
79                     span_help_and_lint(
80                         cx,
81                         ASSERTIONS_ON_CONSTANTS,
82                         e.span,
83                         "`assert!(false)` should probably be replaced",
84                         "use `panic!()` or `unreachable!()`",
85                     );
86                 } else {
87                     span_help_and_lint(
88                         cx,
89                         ASSERTIONS_ON_CONSTANTS,
90                         e.span,
91                         &format!("`assert!(false, \"{}\")` should probably be replaced", panic_message,),
92                         &format!(
93                             "use `panic!(\"{}\")` or `unreachable!(\"{}\")`",
94                             panic_message, panic_message,
95                         ),
96                     );
97                 }
98             }
99         }
100     }
101 }
102
103 /// Check if the expression matches
104 ///
105 /// ```rust,ignore
106 /// match { let _t = !c; _t } {
107 ///     true => {
108 ///         {
109 ///             ::std::rt::begin_panic(message, _)
110 ///         }
111 ///     }
112 ///     _ => { }
113 /// };
114 /// ```
115 ///
116 /// where `message` is a string literal and `c` is a constant bool.
117 ///
118 /// TODO extend this to match anything as message not just string literals
119 ///
120 /// Returns the `message` argument of `begin_panic` and the value of `c` which is the
121 /// first argument of `assert!`.
122 fn assert_with_message<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<(LocalInternedString, bool)> {
123     if_chain! {
124         if let ExprKind::Match(ref expr, ref arms, _) = expr.kind;
125         // matches { let _t = expr; _t }
126         if let ExprKind::DropTemps(ref expr) = expr.kind;
127         if let ExprKind::Unary(UnOp::UnNot, ref expr) = expr.kind;
128         // bind the first argument of the `assert!` macro
129         if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables, expr);
130         // arm 1 pattern
131         if let PatKind::Lit(ref lit_expr) = arms[0].pat.kind;
132         if let ExprKind::Lit(ref lit) = lit_expr.kind;
133         if let LitKind::Bool(true) = lit.node;
134         // arm 1 block
135         if let ExprKind::Block(ref block, _) = arms[0].body.kind;
136         if block.stmts.len() == 0;
137         if let Some(block_expr) = &block.expr;
138         if let ExprKind::Block(ref inner_block, _) = block_expr.kind;
139         if let Some(begin_panic_call) = &inner_block.expr;
140         // function call
141         if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
142         if args.len() == 2;
143         if let ExprKind::Lit(ref lit) = args[0].kind;
144         if let LitKind::Str(ref s, _) = lit.node;
145         // bind the second argument of the `assert!` macro
146         let panic_message = s.as_str();
147         // second argument of begin_panic is irrelevant
148         // as is the second match arm
149         then {
150             return Some((panic_message, is_true));
151         }
152     }
153     None
154 }
155
156 /// Matches a function call with the given path and returns the arguments.
157 ///
158 /// Usage:
159 ///
160 /// ```rust,ignore
161 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
162 /// ```
163 fn match_function_call<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, path: &[&str]) -> Option<&'a [Expr]> {
164     if_chain! {
165         if let ExprKind::Call(ref fun, ref args) = expr.kind;
166         if let ExprKind::Path(ref qpath) = fun.kind;
167         if let Some(fun_def_id) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
168         if match_def_path(cx, fun_def_id, path);
169         then {
170             return Some(&args)
171         }
172     };
173     None
174 }