]> git.lizzy.rs Git - rust.git/blob - src/needless_bool.rs
Merge pull request #940 from oli-obk/simplify/mut_mut
[rust.git] / 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, snippet_opt};
10
11 /// **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.
12 ///
13 /// **Why is this bad?** Redundant code.
14 ///
15 /// **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.
16 ///
17 /// **Example:** `if x { false } else { true }`
18 declare_lint! {
19     pub NEEDLESS_BOOL,
20     Warn,
21     "if-statements with plain booleans in the then- and else-clause, e.g. \
22      `if p { true } else { false }`"
23 }
24
25 /// **What it does:** This lint checks for expressions of the form `x == true` (or vice versa) and suggest using the variable directly.
26 ///
27 /// **Why is this bad?** Unnecessary code.
28 ///
29 /// **Known problems:** None.
30 ///
31 /// **Example:** `if x == true { }` could be `if x { }`
32 declare_lint! {
33     pub BOOL_COMPARISON,
34     Warn,
35     "comparing a variable to a boolean, e.g. \
36      `if x == true`"
37 }
38
39 #[derive(Copy,Clone)]
40 pub struct NeedlessBool;
41
42 impl LintPass for NeedlessBool {
43     fn get_lints(&self) -> LintArray {
44         lint_array!(NEEDLESS_BOOL)
45     }
46 }
47
48 impl LateLintPass for NeedlessBool {
49     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
50         use self::Expression::*;
51         if let ExprIf(ref pred, ref then_block, Some(ref else_expr)) = e.node {
52             let reduce = |hint: &str, not| {
53                 let hint = match snippet_opt(cx, pred.span) {
54                     Some(pred_snip) => format!("`{}{}`", not, pred_snip),
55                     None => hint.into(),
56                 };
57                 span_lint_and_then(cx,
58                                    NEEDLESS_BOOL,
59                                    e.span,
60                                    "this if-then-else expression returns a bool literal",
61                                    |db| {
62                                        db.span_suggestion(e.span, "you can reduce it to", hint);
63                                    });
64             };
65             match (fetch_bool_block(then_block), fetch_bool_expr(else_expr)) {
66                 (RetBool(true), RetBool(true)) |
67                 (Bool(true), Bool(true)) => {
68                     span_lint(cx,
69                               NEEDLESS_BOOL,
70                               e.span,
71                               "this if-then-else expression will always return true");
72                 }
73                 (RetBool(false), RetBool(false)) |
74                 (Bool(false), Bool(false)) => {
75                     span_lint(cx,
76                               NEEDLESS_BOOL,
77                               e.span,
78                               "this if-then-else expression will always return false");
79                 }
80                 (RetBool(true), RetBool(false)) => reduce("its predicate", "return "),
81                 (Bool(true), Bool(false)) => reduce("its predicate", ""),
82                 (RetBool(false), RetBool(true)) => reduce("`!` and its predicate", "return !"),
83                 (Bool(false), Bool(true)) => reduce("`!` and its predicate", "!"),
84                 _ => (),
85             }
86         }
87     }
88 }
89
90 #[derive(Copy,Clone)]
91 pub struct BoolComparison;
92
93 impl LintPass for BoolComparison {
94     fn get_lints(&self) -> LintArray {
95         lint_array!(BOOL_COMPARISON)
96     }
97 }
98
99 impl LateLintPass for BoolComparison {
100     fn check_expr(&mut self, cx: &LateContext, e: &Expr) {
101         use self::Expression::*;
102         if let ExprBinary(Spanned { node: BiEq, .. }, ref left_side, ref right_side) = e.node {
103             match (fetch_bool_expr(left_side), fetch_bool_expr(right_side)) {
104                 (Bool(true), Other) => {
105                     let hint = snippet(cx, right_side.span, "..").into_owned();
106                     span_lint_and_then(cx,
107                                        BOOL_COMPARISON,
108                                        e.span,
109                                        "equality checks against true are unnecessary",
110                                        |db| {
111                                            db.span_suggestion(e.span, "try simplifying it as shown:", hint);
112                                        });
113                 }
114                 (Other, Bool(true)) => {
115                     let hint = snippet(cx, left_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                 (Bool(false), Other) => {
125                     let hint = format!("!{}", snippet(cx, right_side.span, ".."));
126                     span_lint_and_then(cx,
127                                        BOOL_COMPARISON,
128                                        e.span,
129                                        "equality checks against false can be replaced by a negation",
130                                        |db| {
131                                            db.span_suggestion(e.span, "try simplifying it as shown:", hint);
132                                        });
133                 }
134                 (Other, Bool(false)) => {
135                     let hint = format!("!{}", snippet(cx, left_side.span, ".."));
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);
142                                        });
143                 }
144                 _ => (),
145             }
146         }
147     }
148 }
149
150 enum Expression {
151     Bool(bool),
152     RetBool(bool),
153     Other,
154 }
155
156 fn fetch_bool_block(block: &Block) -> Expression {
157     match (&*block.stmts, block.expr.as_ref()) {
158         ([], Some(e)) => fetch_bool_expr(&**e),
159         ([ref e], None) => {
160             if let StmtSemi(ref e, _) = e.node {
161                 if let ExprRet(_) = e.node {
162                     fetch_bool_expr(&**e)
163                 } else {
164                     Expression::Other
165                 }
166             } else {
167                 Expression::Other
168             }
169         }
170         _ => Expression::Other,
171     }
172 }
173
174 fn fetch_bool_expr(expr: &Expr) -> Expression {
175     match expr.node {
176         ExprBlock(ref block) => fetch_bool_block(block),
177         ExprLit(ref lit_ptr) => {
178             if let LitKind::Bool(value) = lit_ptr.node {
179                 Expression::Bool(value)
180             } else {
181                 Expression::Other
182             }
183         }
184         ExprRet(Some(ref expr)) => {
185             match fetch_bool_expr(expr) {
186                 Expression::Bool(value) => Expression::RetBool(value),
187                 _ => Expression::Other,
188             }
189         }
190         _ => Expression::Other,
191     }
192 }