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