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