]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Cargo fmt
[rust.git] / clippy_lints / src / booleans.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::hir::*;
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
5 use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
6 use syntax::util::ThinVec;
7 use utils::{in_macro, snippet_opt, span_lint_and_then, 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_fn(
58         &mut self,
59         cx: &LateContext<'a, 'tcx>,
60         _: intravisit::FnKind<'tcx>,
61         _: &'tcx FnDecl,
62         body: &'tcx Body,
63         _: Span,
64         _: NodeId,
65     ) {
66         NonminimalBoolVisitor { cx: cx }.visit_body(body)
67     }
68 }
69
70 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
71     cx: &'a LateContext<'a, 'tcx>,
72 }
73
74 use quine_mc_cluskey::Bool;
75 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
76     terminals: Vec<&'v Expr>,
77     cx: &'a LateContext<'a, 'tcx>,
78 }
79
80 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
81     fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
82         for a in a {
83             if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
84                 if binop.node == op {
85                     v = self.extract(op, &[lhs, rhs], v)?;
86                     continue;
87                 }
88             }
89             v.push(self.run(a)?);
90         }
91         Ok(v)
92     }
93
94     fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
95         // prevent folding of `cfg!` macros and the like
96         if !in_macro(e.span) {
97             match e.node {
98                 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
99                 ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
100                     BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
101                     BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
102                     _ => (),
103                 },
104                 ExprLit(ref lit) => match lit.node {
105                     LitKind::Bool(true) => return Ok(Bool::True),
106                     LitKind::Bool(false) => return Ok(Bool::False),
107                     _ => (),
108                 },
109                 _ => (),
110             }
111         }
112         for (n, expr) in self.terminals.iter().enumerate() {
113             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
114                 #[allow(cast_possible_truncation)]
115                 return Ok(Bool::Term(n as u8));
116             }
117             let negated = match e.node {
118                 ExprBinary(binop, ref lhs, ref rhs) => {
119                     let mk_expr = |op| {
120                         Expr {
121                             id: DUMMY_NODE_ID,
122                             hir_id: DUMMY_HIR_ID,
123                             span: DUMMY_SP,
124                             attrs: ThinVec::new(),
125                             node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
126                         }
127                     };
128                     match binop.node {
129                         BiEq => mk_expr(BiNe),
130                         BiNe => mk_expr(BiEq),
131                         BiGt => mk_expr(BiLe),
132                         BiGe => mk_expr(BiLt),
133                         BiLt => mk_expr(BiGe),
134                         BiLe => mk_expr(BiGt),
135                         _ => continue,
136                     }
137                 },
138                 _ => continue,
139             };
140             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
141                 #[allow(cast_possible_truncation)]
142                 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
143             }
144         }
145         let n = self.terminals.len();
146         self.terminals.push(e);
147         if n < 32 {
148             #[allow(cast_possible_truncation)]
149             Ok(Bool::Term(n as u8))
150         } else {
151             Err("too many literals".to_owned())
152         }
153     }
154 }
155
156 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
157     fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
158         use quine_mc_cluskey::Bool::*;
159         let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
160         match *suggestion {
161             True => {
162                 s.push_str("true");
163                 s
164             },
165             False => {
166                 s.push_str("false");
167                 s
168             },
169             Not(ref inner) => match **inner {
170                 And(_) | Or(_) => {
171                     s.push('!');
172                     recurse(true, cx, inner, terminals, s)
173                 },
174                 Term(n) => if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
175                     let op = match binop.node {
176                         BiEq => " != ",
177                         BiNe => " == ",
178                         BiLt => " >= ",
179                         BiGt => " <= ",
180                         BiLe => " > ",
181                         BiGe => " < ",
182                         _ => {
183                             s.push('!');
184                             return recurse(true, cx, inner, terminals, s);
185                         },
186                     };
187                     s.push_str(&snip(lhs));
188                     s.push_str(op);
189                     s.push_str(&snip(rhs));
190                     s
191                 } else {
192                     s.push('!');
193                     recurse(false, cx, inner, terminals, s)
194                 },
195                 _ => {
196                     s.push('!');
197                     recurse(false, cx, inner, terminals, s)
198                 },
199             },
200             And(ref v) => {
201                 if brackets {
202                     s.push('(');
203                 }
204                 if let Or(_) = v[0] {
205                     s = recurse(true, cx, &v[0], terminals, s);
206                 } else {
207                     s = recurse(false, cx, &v[0], terminals, s);
208                 }
209                 for inner in &v[1..] {
210                     s.push_str(" && ");
211                     if let Or(_) = *inner {
212                         s = recurse(true, cx, inner, terminals, s);
213                     } else {
214                         s = recurse(false, cx, inner, terminals, s);
215                     }
216                 }
217                 if brackets {
218                     s.push(')');
219                 }
220                 s
221             },
222             Or(ref v) => {
223                 if brackets {
224                     s.push('(');
225                 }
226                 s = recurse(false, cx, &v[0], terminals, s);
227                 for inner in &v[1..] {
228                     s.push_str(" || ");
229                     s = recurse(false, cx, inner, terminals, s);
230                 }
231                 if brackets {
232                     s.push(')');
233                 }
234                 s
235             },
236             Term(n) => {
237                 if brackets {
238                     if let ExprBinary(..) = terminals[n as usize].node {
239                         s.push('(');
240                     }
241                 }
242                 s.push_str(&snip(terminals[n as usize]));
243                 if brackets {
244                     if let ExprBinary(..) = terminals[n as usize].node {
245                         s.push(')');
246                     }
247                 }
248                 s
249             },
250         }
251     }
252     recurse(false, cx, suggestion, terminals, String::new())
253 }
254
255 fn simple_negate(b: Bool) -> Bool {
256     use quine_mc_cluskey::Bool::*;
257     match b {
258         True => False,
259         False => True,
260         t @ Term(_) => Not(Box::new(t)),
261         And(mut v) => {
262             for el in &mut v {
263                 *el = simple_negate(::std::mem::replace(el, True));
264             }
265             Or(v)
266         },
267         Or(mut v) => {
268             for el in &mut v {
269                 *el = simple_negate(::std::mem::replace(el, True));
270             }
271             And(v)
272         },
273         Not(inner) => *inner,
274     }
275 }
276
277 #[derive(Default)]
278 struct Stats {
279     terminals: [usize; 32],
280     negations: usize,
281     ops: usize,
282 }
283
284 fn terminal_stats(b: &Bool) -> Stats {
285     fn recurse(b: &Bool, stats: &mut Stats) {
286         match *b {
287             True | False => stats.ops += 1,
288             Not(ref inner) => {
289                 match **inner {
290                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
291                     _ => stats.negations += 1,
292                 }
293                 recurse(inner, stats);
294             },
295             And(ref v) | Or(ref v) => {
296                 stats.ops += v.len() - 1;
297                 for inner in v {
298                     recurse(inner, stats);
299                 }
300             },
301             Term(n) => stats.terminals[n as usize] += 1,
302         }
303     }
304     use quine_mc_cluskey::Bool::*;
305     let mut stats = Stats::default();
306     recurse(b, &mut stats);
307     stats
308 }
309
310 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
311     fn bool_expr(&self, e: &Expr) {
312         let mut h2q = Hir2Qmm {
313             terminals: Vec::new(),
314             cx: self.cx,
315         };
316         if let Ok(expr) = h2q.run(e) {
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(
349                             self.cx,
350                             LOGIC_BUG,
351                             e.span,
352                             "this boolean expression contains a logic bug",
353                             |db| {
354                                 db.span_help(
355                                     h2q.terminals[i].span,
356                                     "this expression can be optimized out by applying boolean operations to the \
357                                      outer expression",
358                                 );
359                                 db.span_suggestion(
360                                     e.span,
361                                     "it would look like the following",
362                                     suggest(self.cx, suggestion, &h2q.terminals),
363                                 );
364                             },
365                         );
366                         // don't also lint `NONMINIMAL_BOOL`
367                         return;
368                     }
369                     // if the number of occurrences of a terminal decreases or any of the stats
370                     // decreases while none increases
371                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
372                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
373                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
374                 }
375                 if improvement {
376                     improvements.push(suggestion);
377                 }
378             }
379             if !improvements.is_empty() {
380                 span_lint_and_then(
381                     self.cx,
382                     NONMINIMAL_BOOL,
383                     e.span,
384                     "this boolean expression can be simplified",
385                     |db| {
386                         db.span_suggestions(
387                             e.span,
388                             "try",
389                             improvements
390                                 .into_iter()
391                                 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
392                                 .collect(),
393                         );
394                     },
395                 );
396             }
397         }
398     }
399 }
400
401 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
402     fn visit_expr(&mut self, e: &'tcx Expr) {
403         if in_macro(e.span) {
404             return;
405         }
406         match e.node {
407             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
408             ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
409                 self.bool_expr(e);
410             } else {
411                 walk_expr(self, e);
412             },
413             _ => walk_expr(self, e),
414         }
415     }
416     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
417         NestedVisitorMap::None
418     }
419 }