]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
9ab806f66ec559fdca5cf1c6bdfe705e6633b578
[rust.git] / clippy_lints / src / booleans.rs
1 use rustc::lint::{LintArray, LateLintPass, LateContext, LintPass};
2 use rustc::hir::*;
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, DUMMY_NODE_ID};
5 use syntax::codemap::{DUMMY_SP, dummy_spanned};
6 use utils::{span_lint_and_then, in_macro, snippet_opt, SpanlessEq};
7
8 /// **What it does:** This lint checks for boolean expressions that can be written more concisely
9 ///
10 /// **Why is this bad?** Readability of boolean expressions suffers from unnecesessary duplication
11 ///
12 /// **Known problems:** Ignores short circuting behavior of `||` and `&&`. Ignores `|`, `&` and `^`.
13 ///
14 /// **Example:** `if a && true` should be `if a` and `!(a == b)` should be `a != b`
15 declare_lint! {
16     pub NONMINIMAL_BOOL, Allow,
17     "checks for boolean expressions that can be written more concisely"
18 }
19
20 /// **What it does:** This lint checks for boolean expressions that contain terminals that can be eliminated
21 ///
22 /// **Why is this bad?** This is most likely a logic bug
23 ///
24 /// **Known problems:** Ignores short circuiting behavior
25 ///
26 /// **Example:** The `b` in `if a && b || a` is unnecessary because the expression is equivalent to `if a`
27 declare_lint! {
28     pub LOGIC_BUG, Warn,
29     "checks for boolean expressions that contain terminals which can be eliminated"
30 }
31
32 #[derive(Copy,Clone)]
33 pub struct NonminimalBool;
34
35 impl LintPass for NonminimalBool {
36     fn get_lints(&self) -> LintArray {
37         lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
38     }
39 }
40
41 impl LateLintPass for NonminimalBool {
42     fn check_item(&mut self, cx: &LateContext, item: &Item) {
43         NonminimalBoolVisitor(cx).visit_item(item)
44     }
45 }
46
47 struct NonminimalBoolVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
48
49 use quine_mc_cluskey::Bool;
50 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
51     terminals: Vec<&'v Expr>,
52     cx: &'a LateContext<'a, 'tcx>,
53 }
54
55 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
56     fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
57         for a in a {
58             if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
59                 if binop.node == op {
60                     v = self.extract(op, &[lhs, rhs], v)?;
61                     continue;
62                 }
63             }
64             v.push(self.run(a)?);
65         }
66         Ok(v)
67     }
68
69     fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
70         // prevent folding of `cfg!` macros and the like
71         if !in_macro(self.cx, e.span) {
72             match e.node {
73                 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
74                 ExprBinary(binop, ref lhs, ref rhs) => {
75                     match binop.node {
76                         BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
77                         BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
78                         _ => (),
79                     }
80                 }
81                 ExprLit(ref lit) => {
82                     match lit.node {
83                         LitKind::Bool(true) => return Ok(Bool::True),
84                         LitKind::Bool(false) => return Ok(Bool::False),
85                         _ => (),
86                     }
87                 }
88                 _ => (),
89             }
90         }
91         for (n, expr) in self.terminals.iter().enumerate() {
92             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
93                 #[allow(cast_possible_truncation)]
94                 return Ok(Bool::Term(n as u8));
95             }
96             let negated = match e.node {
97                 ExprBinary(binop, ref lhs, ref rhs) => {
98                     let mk_expr = |op| {
99                         Expr {
100                             id: DUMMY_NODE_ID,
101                             span: DUMMY_SP,
102                             attrs: None,
103                             node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
104                         }
105                     };
106                     match binop.node {
107                         BiEq => mk_expr(BiNe),
108                         BiNe => mk_expr(BiEq),
109                         BiGt => mk_expr(BiLe),
110                         BiGe => mk_expr(BiLt),
111                         BiLt => mk_expr(BiGe),
112                         BiLe => mk_expr(BiGt),
113                         _ => continue,
114                     }
115                 }
116                 _ => continue,
117             };
118             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
119                 #[allow(cast_possible_truncation)]
120                 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
121             }
122         }
123         let n = self.terminals.len();
124         self.terminals.push(e);
125         if n < 32 {
126             #[allow(cast_possible_truncation)]
127             Ok(Bool::Term(n as u8))
128         } else {
129             Err("too many literals".to_owned())
130         }
131     }
132 }
133
134 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
135     fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
136         use quine_mc_cluskey::Bool::*;
137         let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
138         match *suggestion {
139             True => {
140                 s.push_str("true");
141                 s
142             }
143             False => {
144                 s.push_str("false");
145                 s
146             }
147             Not(ref inner) => {
148                 match **inner {
149                     And(_) | Or(_) => {
150                         s.push('!');
151                         recurse(true, cx, inner, terminals, s)
152                     }
153                     Term(n) => {
154                         if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
155                             let op = match binop.node {
156                                 BiEq => " != ",
157                                 BiNe => " == ",
158                                 BiLt => " >= ",
159                                 BiGt => " <= ",
160                                 BiLe => " > ",
161                                 BiGe => " < ",
162                                 _ => {
163                                     s.push('!');
164                                     return recurse(true, cx, inner, terminals, s);
165                                 }
166                             };
167                             s.push_str(&snip(lhs));
168                             s.push_str(op);
169                             s.push_str(&snip(rhs));
170                             s
171                         } else {
172                             s.push('!');
173                             recurse(false, cx, inner, terminals, s)
174                         }
175                     }
176                     _ => {
177                         s.push('!');
178                         recurse(false, cx, inner, terminals, s)
179                     }
180                 }
181             }
182             And(ref v) => {
183                 if brackets {
184                     s.push('(');
185                 }
186                 if let Or(_) = v[0] {
187                     s = recurse(true, cx, &v[0], terminals, s);
188                 } else {
189                     s = recurse(false, cx, &v[0], terminals, s);
190                 }
191                 for inner in &v[1..] {
192                     s.push_str(" && ");
193                     if let Or(_) = *inner {
194                         s = recurse(true, cx, inner, terminals, s);
195                     } else {
196                         s = recurse(false, cx, inner, terminals, s);
197                     }
198                 }
199                 if brackets {
200                     s.push(')');
201                 }
202                 s
203             }
204             Or(ref v) => {
205                 if brackets {
206                     s.push('(');
207                 }
208                 s = recurse(false, cx, &v[0], terminals, s);
209                 for inner in &v[1..] {
210                     s.push_str(" || ");
211                     s = recurse(false, cx, inner, terminals, s);
212                 }
213                 if brackets {
214                     s.push(')');
215                 }
216                 s
217             }
218             Term(n) => {
219                 if brackets {
220                     if let ExprBinary(..) = terminals[n as usize].node {
221                         s.push('(');
222                     }
223                 }
224                 s.push_str(&snip(terminals[n as usize]));
225                 if brackets {
226                     if let ExprBinary(..) = terminals[n as usize].node {
227                         s.push(')');
228                     }
229                 }
230                 s
231             }
232         }
233     }
234     recurse(false, cx, suggestion, terminals, String::new())
235 }
236
237 fn simple_negate(b: Bool) -> Bool {
238     use quine_mc_cluskey::Bool::*;
239     match b {
240         True => False,
241         False => True,
242         t @ Term(_) => Not(Box::new(t)),
243         And(mut v) => {
244             for el in &mut v {
245                 *el = simple_negate(::std::mem::replace(el, True));
246             }
247             Or(v)
248         }
249         Or(mut v) => {
250             for el in &mut v {
251                 *el = simple_negate(::std::mem::replace(el, True));
252             }
253             And(v)
254         }
255         Not(inner) => *inner,
256     }
257 }
258
259 #[derive(Default)]
260 struct Stats {
261     terminals: [usize; 32],
262     negations: usize,
263     ops: usize,
264 }
265
266 fn terminal_stats(b: &Bool) -> Stats {
267     fn recurse(b: &Bool, stats: &mut Stats) {
268         match *b {
269             True | False => stats.ops += 1,
270             Not(ref inner) => {
271                 match **inner {
272                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
273                     _ => stats.negations += 1,
274                 }
275                 recurse(inner, stats);
276             }
277             And(ref v) | Or(ref v) => {
278                 stats.ops += v.len() - 1;
279                 for inner in v {
280                     recurse(inner, stats);
281                 }
282             }
283             Term(n) => stats.terminals[n as usize] += 1,
284         }
285     }
286     use quine_mc_cluskey::Bool::*;
287     let mut stats = Stats::default();
288     recurse(b, &mut stats);
289     stats
290 }
291
292 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
293     fn bool_expr(&self, e: &Expr) {
294         let mut h2q = Hir2Qmm {
295             terminals: Vec::new(),
296             cx: self.0,
297         };
298         if let Ok(expr) = h2q.run(e) {
299
300             if h2q.terminals.len() > 8 {
301                 // QMC has exponentially slow behavior as the number of terminals increases
302                 // 8 is reasonable, it takes approximately 0.2 seconds.
303                 // See #825
304                 return;
305             }
306
307             let stats = terminal_stats(&expr);
308             let mut simplified = expr.simplify();
309             for simple in Bool::Not(Box::new(expr.clone())).simplify() {
310                 match simple {
311                     Bool::Not(_) | Bool::True | Bool::False => {}
312                     _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
313                 }
314                 let simple_negated = simple_negate(simple);
315                 if simplified.iter().any(|s| *s == simple_negated) {
316                     continue;
317                 }
318                 simplified.push(simple_negated);
319             }
320             let mut improvements = Vec::new();
321             'simplified: for suggestion in &simplified {
322                 let simplified_stats = terminal_stats(suggestion);
323                 let mut improvement = false;
324                 for i in 0..32 {
325                     // ignore any "simplifications" that end up requiring a terminal more often than in the original expression
326                     if stats.terminals[i] < simplified_stats.terminals[i] {
327                         continue 'simplified;
328                     }
329                     if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
330                         span_lint_and_then(self.0,
331                                            LOGIC_BUG,
332                                            e.span,
333                                            "this boolean expression contains a logic bug",
334                                            |db| {
335                                                db.span_help(h2q.terminals[i].span,
336                                                             "this expression can be optimized out by applying \
337                                                              boolean operations to the outer expression");
338                                                db.span_suggestion(e.span,
339                                                                   "it would look like the following",
340                                                                   suggest(self.0, suggestion, &h2q.terminals));
341                                            });
342                         // don't also lint `NONMINIMAL_BOOL`
343                         return;
344                     }
345                     // if the number of occurrences of a terminal decreases or any of the stats decreases while none increases
346                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
347                                    (stats.negations > simplified_stats.negations &&
348                                     stats.ops == simplified_stats.ops) ||
349                                    (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
350                 }
351                 if improvement {
352                     improvements.push(suggestion);
353                 }
354             }
355             if !improvements.is_empty() {
356                 span_lint_and_then(self.0,
357                                    NONMINIMAL_BOOL,
358                                    e.span,
359                                    "this boolean expression can be simplified",
360                                    |db| {
361                                        for suggestion in &improvements {
362                                            db.span_suggestion(e.span,
363                                                               "try",
364                                                               suggest(self.0, suggestion, &h2q.terminals));
365                                        }
366                                    });
367             }
368         }
369     }
370 }
371
372 impl<'a, 'v, 'tcx> Visitor<'v> for NonminimalBoolVisitor<'a, 'tcx> {
373     fn visit_expr(&mut self, e: &'v Expr) {
374         if in_macro(self.0, e.span) {
375             return;
376         }
377         match e.node {
378             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
379             ExprUnary(UnNot, ref inner) => {
380                 if self.0.tcx.node_types()[&inner.id].is_bool() {
381                     self.bool_expr(e);
382                 } else {
383                     walk_expr(self, e);
384                 }
385             }
386             _ => walk_expr(self, e),
387         }
388     }
389 }