]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
Doctests: Fix all complexity lint docs
[rust.git] / clippy_lints / src / needless_bool.rs
1 //! Checks for needless boolean results of if-else expressions
2 //!
3 //! This lint is **warn** by default
4
5 use crate::utils::sugg::Sugg;
6 use crate::utils::{higher, in_macro_or_desugar, span_lint, span_lint_and_sugg};
7 use rustc::hir::*;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_lint_pass, declare_tool_lint};
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::Spanned;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for expressions of the form `if c { true } else {
16     /// false }`
17     /// (or vice versa) and suggest using the condition directly.
18     ///
19     /// **Why is this bad?** Redundant code.
20     ///
21     /// **Known problems:** Maybe false positives: Sometimes, the two branches are
22     /// painstakingly documented (which we, of course, do not detect), so they *may*
23     /// have some value. Even then, the documentation can be rewritten to match the
24     /// shorter code.
25     ///
26     /// **Example:**
27     /// ```rust,ignore
28     /// if x {
29     ///     false
30     /// } else {
31     ///     true
32     /// }
33     /// ```
34     pub NEEDLESS_BOOL,
35     complexity,
36     "if-statements with plain booleans in the then- and else-clause, e.g., `if p { true } else { false }`"
37 }
38
39 declare_clippy_lint! {
40     /// **What it does:** Checks for expressions of the form `x == true`,
41     /// `x != true` and order comparisons such as `x < true` (or vice versa) and
42     /// suggest using the variable directly.
43     ///
44     /// **Why is this bad?** Unnecessary code.
45     ///
46     /// **Known problems:** None.
47     ///
48     /// **Example:**
49     /// ```rust,ignore
50     /// if x == true {} // could be `if x { }`
51     /// ```
52     pub BOOL_COMPARISON,
53     complexity,
54     "comparing a variable to a boolean, e.g., `if x == true` or `if x != true`"
55 }
56
57 declare_lint_pass!(NeedlessBool => [NEEDLESS_BOOL]);
58
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBool {
60     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
61         use self::Expression::*;
62         if let Some((ref pred, ref then_block, Some(ref else_expr))) = higher::if_block(&e) {
63             let reduce = |ret, not| {
64                 let mut applicability = Applicability::MachineApplicable;
65                 let snip = Sugg::hir_with_applicability(cx, pred, "<predicate>", &mut applicability);
66                 let mut snip = if not { !snip } else { snip };
67
68                 if ret {
69                     snip = snip.make_return();
70                 }
71
72                 if parent_node_is_if_expr(&e, &cx) {
73                     snip = snip.blockify()
74                 }
75
76                 span_lint_and_sugg(
77                     cx,
78                     NEEDLESS_BOOL,
79                     e.span,
80                     "this if-then-else expression returns a bool literal",
81                     "you can reduce it to",
82                     snip.to_string(),
83                     applicability,
84                 );
85             };
86             if let ExprKind::Block(ref then_block, _) = then_block.node {
87                 match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
88                     (RetBool(true), RetBool(true)) | (Bool(true), Bool(true)) => {
89                         span_lint(
90                             cx,
91                             NEEDLESS_BOOL,
92                             e.span,
93                             "this if-then-else expression will always return true",
94                         );
95                     },
96                     (RetBool(false), RetBool(false)) | (Bool(false), Bool(false)) => {
97                         span_lint(
98                             cx,
99                             NEEDLESS_BOOL,
100                             e.span,
101                             "this if-then-else expression will always return false",
102                         );
103                     },
104                     (RetBool(true), RetBool(false)) => reduce(true, false),
105                     (Bool(true), Bool(false)) => reduce(false, false),
106                     (RetBool(false), RetBool(true)) => reduce(true, true),
107                     (Bool(false), Bool(true)) => reduce(false, true),
108                     _ => (),
109                 }
110             } else {
111                 panic!("IfExpr 'then' node is not an ExprKind::Block");
112             }
113         }
114     }
115 }
116
117 fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
118     let parent_id = cx.tcx.hir().get_parent_node(expr.hir_id);
119     let parent_node = cx.tcx.hir().get(parent_id);
120
121     if let rustc::hir::Node::Expr(e) = parent_node {
122         if higher::if_block(&e).is_some() {
123             return true;
124         }
125     }
126
127     false
128 }
129
130 declare_lint_pass!(BoolComparison => [BOOL_COMPARISON]);
131
132 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
133     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
134         if in_macro_or_desugar(e.span) {
135             return;
136         }
137
138         if let ExprKind::Binary(Spanned { node, .. }, ..) = e.node {
139             let ignore_case = None::<(fn(_) -> _, &str)>;
140             let ignore_no_literal = None::<(fn(_, _) -> _, &str)>;
141             match node {
142                 BinOpKind::Eq => {
143                     let true_case = Some((|h| h, "equality checks against true are unnecessary"));
144                     let false_case = Some((
145                         |h: Sugg<'_>| !h,
146                         "equality checks against false can be replaced by a negation",
147                     ));
148                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
149                 },
150                 BinOpKind::Ne => {
151                     let true_case = Some((
152                         |h: Sugg<'_>| !h,
153                         "inequality checks against true can be replaced by a negation",
154                     ));
155                     let false_case = Some((|h| h, "inequality checks against false are unnecessary"));
156                     check_comparison(cx, e, true_case, false_case, true_case, false_case, ignore_no_literal)
157                 },
158                 BinOpKind::Lt => check_comparison(
159                     cx,
160                     e,
161                     ignore_case,
162                     Some((|h| h, "greater than checks against false are unnecessary")),
163                     Some((
164                         |h: Sugg<'_>| !h,
165                         "less than comparison against true can be replaced by a negation",
166                     )),
167                     ignore_case,
168                     Some((
169                         |l: Sugg<'_>, r: Sugg<'_>| (!l).bit_and(&r),
170                         "order comparisons between booleans can be simplified",
171                     )),
172                 ),
173                 BinOpKind::Gt => check_comparison(
174                     cx,
175                     e,
176                     Some((
177                         |h: Sugg<'_>| !h,
178                         "less than comparison against true can be replaced by a negation",
179                     )),
180                     ignore_case,
181                     ignore_case,
182                     Some((|h| h, "greater than checks against false are unnecessary")),
183                     Some((
184                         |l: Sugg<'_>, r: Sugg<'_>| l.bit_and(&(!r)),
185                         "order comparisons between booleans can be simplified",
186                     )),
187                 ),
188                 _ => (),
189             }
190         }
191     }
192 }
193
194 fn check_comparison<'a, 'tcx>(
195     cx: &LateContext<'a, 'tcx>,
196     e: &'tcx Expr,
197     left_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
198     left_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
199     right_true: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
200     right_false: Option<(impl FnOnce(Sugg<'a>) -> Sugg<'a>, &str)>,
201     no_literal: Option<(impl FnOnce(Sugg<'a>, Sugg<'a>) -> Sugg<'a>, &str)>,
202 ) {
203     use self::Expression::*;
204
205     if let ExprKind::Binary(_, ref left_side, ref right_side) = e.node {
206         let (l_ty, r_ty) = (cx.tables.expr_ty(left_side), cx.tables.expr_ty(right_side));
207         if l_ty.is_bool() && r_ty.is_bool() {
208             let mut applicability = Applicability::MachineApplicable;
209             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
210                 (Bool(true), Other) => left_true.map_or((), |(h, m)| {
211                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
212                 }),
213                 (Other, Bool(true)) => right_true.map_or((), |(h, m)| {
214                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
215                 }),
216                 (Bool(false), Other) => left_false.map_or((), |(h, m)| {
217                     suggest_bool_comparison(cx, e, right_side, applicability, m, h)
218                 }),
219                 (Other, Bool(false)) => right_false.map_or((), |(h, m)| {
220                     suggest_bool_comparison(cx, e, left_side, applicability, m, h)
221                 }),
222                 (Other, Other) => no_literal.map_or((), |(h, m)| {
223                     let left_side = Sugg::hir_with_applicability(cx, left_side, "..", &mut applicability);
224                     let right_side = Sugg::hir_with_applicability(cx, right_side, "..", &mut applicability);
225                     span_lint_and_sugg(
226                         cx,
227                         BOOL_COMPARISON,
228                         e.span,
229                         m,
230                         "try simplifying it as shown",
231                         h(left_side, right_side).to_string(),
232                         applicability,
233                     )
234                 }),
235                 _ => (),
236             }
237         }
238     }
239 }
240
241 fn suggest_bool_comparison<'a, 'tcx>(
242     cx: &LateContext<'a, 'tcx>,
243     e: &'tcx Expr,
244     expr: &Expr,
245     mut applicability: Applicability,
246     message: &str,
247     conv_hint: impl FnOnce(Sugg<'a>) -> Sugg<'a>,
248 ) {
249     let hint = Sugg::hir_with_applicability(cx, expr, "..", &mut applicability);
250     span_lint_and_sugg(
251         cx,
252         BOOL_COMPARISON,
253         e.span,
254         message,
255         "try simplifying it as shown",
256         conv_hint(hint).to_string(),
257         applicability,
258     );
259 }
260
261 enum Expression {
262     Bool(bool),
263     RetBool(bool),
264     Other,
265 }
266
267 fn fetch_bool_block(block: &Block) -> Expression {
268     match (&*block.stmts, block.expr.as_ref()) {
269         (&[], Some(e)) => fetch_bool_expr(&**e),
270         (&[ref e], None) => {
271             if let StmtKind::Semi(ref e) = e.node {
272                 if let ExprKind::Ret(_) = e.node {
273                     fetch_bool_expr(&**e)
274                 } else {
275                     Expression::Other
276                 }
277             } else {
278                 Expression::Other
279             }
280         },
281         _ => Expression::Other,
282     }
283 }
284
285 fn fetch_bool_expr(expr: &Expr) -> Expression {
286     match expr.node {
287         ExprKind::Block(ref block, _) => fetch_bool_block(block),
288         ExprKind::Lit(ref lit_ptr) => {
289             if let LitKind::Bool(value) = lit_ptr.node {
290                 Expression::Bool(value)
291             } else {
292                 Expression::Other
293             }
294         },
295         ExprKind::Ret(Some(ref expr)) => match fetch_bool_expr(expr) {
296             Expression::Bool(value) => Expression::RetBool(value),
297             _ => Expression::Other,
298         },
299         _ => Expression::Other,
300     }
301 }