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