]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
Merge pull request #1345 from EpocSquadron/epocsquadron-documentation
[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 rustc::lint::*;
6 use rustc::hir::*;
7 use syntax::ast::LitKind;
8 use syntax::codemap::Spanned;
9 use utils::{span_lint, span_lint_and_then, snippet};
10 use utils::sugg::Sugg;
11
12 /// **What it does:** Checks for expressions of the form `if c { true } else { false }`
13 /// (or vice versa) and suggest using the condition directly.
14 ///
15 /// **Why is this bad?** Redundant code.
16 ///
17 /// **Known problems:** Maybe false positives: Sometimes, the two branches are
18 /// painstakingly documented (which we of course do not detect), so they *may*
19 /// have some value. Even then, the documentation can be rewritten to match the
20 /// shorter code.
21 ///
22 /// **Example:**
23 /// ```rust
24 /// if x { false } else { true }
25 /// ```
26 declare_lint! {
27     pub NEEDLESS_BOOL,
28     Warn,
29     "if-statements with plain booleans in the then- and else-clause, e.g. \
30      `if p { true } else { false }`"
31 }
32
33 /// **What it does:** Checks for expressions of the form `x == true` (or vice
34 /// versa) and suggest using the variable directly.
35 ///
36 /// **Why is this bad?** Unnecessary code.
37 ///
38 /// **Known problems:** None.
39 ///
40 /// **Example:**
41 /// ```rust
42 /// if x == true { }  // could be `if x { }`
43 /// ```
44 declare_lint! {
45     pub BOOL_COMPARISON,
46     Warn,
47     "comparing a variable to a boolean, e.g. `if x == true`"
48 }
49
50 #[derive(Copy,Clone)]
51 pub struct NeedlessBool;
52
53 impl LintPass for NeedlessBool {
54     fn get_lints(&self) -> LintArray {
55         lint_array!(NEEDLESS_BOOL)
56     }
57 }
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 ExprIf(ref pred, ref then_block, Some(ref else_expr)) = e.node {
63             let reduce = |ret, not| {
64                 let snip = Sugg::hir(cx, pred, "<predicate>");
65                 let snip = if not {
66                     !snip
67                 } else {
68                     snip
69                 };
70
71                 let hint = if ret {
72                     format!("return {}", snip)
73                 } else {
74                     snip.to_string()
75                 };
76
77                 span_lint_and_then(cx,
78                                    NEEDLESS_BOOL,
79                                    e.span,
80                                    "this if-then-else expression returns a bool literal",
81                                    |db| {
82                                        db.span_suggestion(e.span, "you can reduce it to", hint);
83                                    });
84             };
85             match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
86                 (RetBool(true), RetBool(true)) |
87                 (Bool(true), Bool(true)) => {
88                     span_lint(cx,
89                               NEEDLESS_BOOL,
90                               e.span,
91                               "this if-then-else expression will always return true");
92                 }
93                 (RetBool(false), RetBool(false)) |
94                 (Bool(false), Bool(false)) => {
95                     span_lint(cx,
96                               NEEDLESS_BOOL,
97                               e.span,
98                               "this if-then-else expression will always return false");
99                 }
100                 (RetBool(true), RetBool(false)) => reduce(true, false),
101                 (Bool(true), Bool(false)) => reduce(false, false),
102                 (RetBool(false), RetBool(true)) => reduce(true, true),
103                 (Bool(false), Bool(true)) => reduce(false, true),
104                 _ => (),
105             }
106         }
107     }
108 }
109
110 #[derive(Copy,Clone)]
111 pub struct BoolComparison;
112
113 impl LintPass for BoolComparison {
114     fn get_lints(&self) -> LintArray {
115         lint_array!(BOOL_COMPARISON)
116     }
117 }
118
119 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
120     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
121         use self::Expression::*;
122         if let ExprBinary(Spanned { node: BiEq, .. }, ref left_side, ref right_side) = e.node {
123             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
124                 (Bool(true), Other) => {
125                     let hint = snippet(cx, right_side.span, "..").into_owned();
126                     span_lint_and_then(cx,
127                                        BOOL_COMPARISON,
128                                        e.span,
129                                        "equality checks against true are unnecessary",
130                                        |db| {
131                                            db.span_suggestion(e.span, "try simplifying it as shown:", hint);
132                                        });
133                 }
134                 (Other, Bool(true)) => {
135                     let hint = snippet(cx, left_side.span, "..").into_owned();
136                     span_lint_and_then(cx,
137                                        BOOL_COMPARISON,
138                                        e.span,
139                                        "equality checks against true are unnecessary",
140                                        |db| {
141                                            db.span_suggestion(e.span, "try simplifying it as shown:", hint);
142                                        });
143                 }
144                 (Bool(false), Other) => {
145                     let hint = Sugg::hir(cx, right_side, "..");
146                     span_lint_and_then(cx,
147                                        BOOL_COMPARISON,
148                                        e.span,
149                                        "equality checks against false can be replaced by a negation",
150                                        |db| {
151                                            db.span_suggestion(e.span, "try simplifying it as shown:", (!hint).to_string());
152                                        });
153                 }
154                 (Other, Bool(false)) => {
155                     let hint = Sugg::hir(cx, left_side, "..");
156                     span_lint_and_then(cx,
157                                        BOOL_COMPARISON,
158                                        e.span,
159                                        "equality checks against false can be replaced by a negation",
160                                        |db| {
161                                            db.span_suggestion(e.span, "try simplifying it as shown:", (!hint).to_string());
162                                        });
163                 }
164                 _ => (),
165             }
166         }
167     }
168 }
169
170 enum Expression {
171     Bool(bool),
172     RetBool(bool),
173     Other,
174 }
175
176 fn fetch_bool_block(block: &Block) -> Expression {
177     match (&*block.stmts, block.expr.as_ref()) {
178         (&[], Some(e)) => fetch_bool_expr(&**e),
179         (&[ref e], None) => {
180             if let StmtSemi(ref e, _) = e.node {
181                 if let ExprRet(_) = e.node {
182                     fetch_bool_expr(&**e)
183                 } else {
184                     Expression::Other
185                 }
186             } else {
187                 Expression::Other
188             }
189         }
190         _ => Expression::Other,
191     }
192 }
193
194 fn fetch_bool_expr(expr: &Expr) -> Expression {
195     match expr.node {
196         ExprBlock(ref block) => fetch_bool_block(block),
197         ExprLit(ref lit_ptr) => {
198             if let LitKind::Bool(value) = lit_ptr.node {
199                 Expression::Bool(value)
200             } else {
201                 Expression::Other
202             }
203         }
204         ExprRet(Some(ref expr)) => {
205             match fetch_bool_expr(expr) {
206                 Expression::Bool(value) => Expression::RetBool(value),
207                 _ => Expression::Other,
208             }
209         }
210         _ => Expression::Other,
211     }
212 }