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