]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_bool.rs
rustfmt fallout in doc comments
[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 { !snip } else { snip };
66
67                 let hint = if ret {
68                     format!("return {}", snip)
69                 } else {
70                     snip.to_string()
71                 };
72
73                 span_lint_and_then(cx,
74                                    NEEDLESS_BOOL,
75                                    e.span,
76                                    "this if-then-else expression returns a bool literal",
77                                    |db| {
78                                        db.span_suggestion(e.span, "you can reduce it to", hint);
79                                    });
80             };
81             match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
82                 (RetBool(true), RetBool(true)) |
83                 (Bool(true), Bool(true)) => {
84                     span_lint(cx,
85                               NEEDLESS_BOOL,
86                               e.span,
87                               "this if-then-else expression will always return true");
88                 },
89                 (RetBool(false), RetBool(false)) |
90                 (Bool(false), Bool(false)) => {
91                     span_lint(cx,
92                               NEEDLESS_BOOL,
93                               e.span,
94                               "this if-then-else expression will always return false");
95                 },
96                 (RetBool(true), RetBool(false)) => reduce(true, false),
97                 (Bool(true), Bool(false)) => reduce(false, false),
98                 (RetBool(false), RetBool(true)) => reduce(true, true),
99                 (Bool(false), Bool(true)) => reduce(false, true),
100                 _ => (),
101             }
102         }
103     }
104 }
105
106 #[derive(Copy,Clone)]
107 pub struct BoolComparison;
108
109 impl LintPass for BoolComparison {
110     fn get_lints(&self) -> LintArray {
111         lint_array!(BOOL_COMPARISON)
112     }
113 }
114
115 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoolComparison {
116     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
117         use self::Expression::*;
118         if let ExprBinary(Spanned { node: BiEq, .. }, ref left_side, ref right_side) = e.node {
119             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
120                 (Bool(true), Other) => {
121                     let hint = snippet(cx, right_side.span, "..").into_owned();
122                     span_lint_and_then(cx,
123                                        BOOL_COMPARISON,
124                                        e.span,
125                                        "equality checks against true are unnecessary",
126                                        |db| {
127                                            db.span_suggestion(e.span, "try simplifying it as shown:", hint);
128                                        });
129                 },
130                 (Other, Bool(true)) => {
131                     let hint = snippet(cx, left_side.span, "..").into_owned();
132                     span_lint_and_then(cx,
133                                        BOOL_COMPARISON,
134                                        e.span,
135                                        "equality checks against true are unnecessary",
136                                        |db| {
137                                            db.span_suggestion(e.span, "try simplifying it as shown:", hint);
138                                        });
139                 },
140                 (Bool(false), Other) => {
141                     let hint = Sugg::hir(cx, right_side, "..");
142                     span_lint_and_then(cx,
143                                        BOOL_COMPARISON,
144                                        e.span,
145                                        "equality checks against false can be replaced by a negation",
146                                        |db| {
147                                            db.span_suggestion(e.span,
148                                                               "try simplifying it as shown:",
149                                                               (!hint).to_string());
150                                        });
151                 },
152                 (Other, Bool(false)) => {
153                     let hint = Sugg::hir(cx, left_side, "..");
154                     span_lint_and_then(cx,
155                                        BOOL_COMPARISON,
156                                        e.span,
157                                        "equality checks against false can be replaced by a negation",
158                                        |db| {
159                                            db.span_suggestion(e.span,
160                                                               "try simplifying it as shown:",
161                                                               (!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 }