]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Raise a lint when suggest has simplified the expression.
[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 // The boolean part of the return indicates whether some simplifications have been applied.
163 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
164     fn recurse(
165         brackets: bool,
166         cx: &LateContext,
167         suggestion: &Bool,
168         terminals: &[&Expr],
169         mut s: String,
170         simplified: &mut bool,
171     ) -> String {
172         use quine_mc_cluskey::Bool::*;
173         let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
174         match *suggestion {
175             True => {
176                 s.push_str("true");
177                 s
178             },
179             False => {
180                 s.push_str("false");
181                 s
182             },
183             Not(ref inner) => match **inner {
184                 And(_) | Or(_) => {
185                     s.push('!');
186                     recurse(true, cx, inner, terminals, s, simplified)
187                 },
188                 Term(n) => match terminals[n as usize].node {
189                     ExprBinary(binop, ref lhs, ref rhs) => {
190                         let op = match binop.node {
191                             BiEq => " != ",
192                             BiNe => " == ",
193                             BiLt => " >= ",
194                             BiGt => " <= ",
195                             BiLe => " > ",
196                             BiGe => " < ",
197                             _ => {
198                                 s.push('!');
199                                 return recurse(true, cx, inner, terminals, s, simplified);
200                             },
201                         };
202                         *simplified = true;
203                         s.push_str(&snip(lhs));
204                         s.push_str(op);
205                         s.push_str(&snip(rhs));
206                         s
207                     },
208                     ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
209                         let negation = METHODS_WITH_NEGATION
210                             .iter().cloned()
211                             .flat_map(|(a, b)| vec![(a, b), (b, a)])
212                             .find(|&(a, _)| a == path.name.as_str());
213                         if let Some((_, negation_method)) = negation {
214                             *simplified = true;
215                             s.push_str(&snip(&args[0]));
216                             s.push('.');
217                             s.push_str(negation_method);
218                             s.push_str("()");
219                             s
220                         } else {
221                             s.push('!');
222                             recurse(false, cx, inner, terminals, s, simplified)
223                         }
224                     },
225                     _ => {
226                         s.push('!');
227                         recurse(false, cx, inner, terminals, s, simplified)
228                     },
229                 },
230                 _ => {
231                     s.push('!');
232                     recurse(false, cx, inner, terminals, s, simplified)
233                 },
234             },
235             And(ref v) => {
236                 if brackets {
237                     s.push('(');
238                 }
239                 if let Or(_) = v[0] {
240                     s = recurse(true, cx, &v[0], terminals, s, simplified);
241                 } else {
242                     s = recurse(false, cx, &v[0], terminals, s, simplified);
243                 }
244                 for inner in &v[1..] {
245                     s.push_str(" && ");
246                     if let Or(_) = *inner {
247                         s = recurse(true, cx, inner, terminals, s, simplified);
248                     } else {
249                         s = recurse(false, cx, inner, terminals, s, simplified);
250                     }
251                 }
252                 if brackets {
253                     s.push(')');
254                 }
255                 s
256             },
257             Or(ref v) => {
258                 if brackets {
259                     s.push('(');
260                 }
261                 s = recurse(false, cx, &v[0], terminals, s, simplified);
262                 for inner in &v[1..] {
263                     s.push_str(" || ");
264                     s = recurse(false, cx, inner, terminals, s, simplified);
265                 }
266                 if brackets {
267                     s.push(')');
268                 }
269                 s
270             },
271             Term(n) => {
272                 if brackets {
273                     if let ExprBinary(..) = terminals[n as usize].node {
274                         s.push('(');
275                     }
276                 }
277                 s.push_str(&snip(terminals[n as usize]));
278                 if brackets {
279                     if let ExprBinary(..) = terminals[n as usize].node {
280                         s.push(')');
281                     }
282                 }
283                 s
284             },
285         }
286     }
287     let mut simplified = false;
288     let s = recurse(false, cx, suggestion, terminals, String::new(), &mut simplified);
289     (s, simplified)
290 }
291
292 fn simple_negate(b: Bool) -> Bool {
293     use quine_mc_cluskey::Bool::*;
294     match b {
295         True => False,
296         False => True,
297         t @ Term(_) => Not(Box::new(t)),
298         And(mut v) => {
299             for el in &mut v {
300                 *el = simple_negate(::std::mem::replace(el, True));
301             }
302             Or(v)
303         },
304         Or(mut v) => {
305             for el in &mut v {
306                 *el = simple_negate(::std::mem::replace(el, True));
307             }
308             And(v)
309         },
310         Not(inner) => *inner,
311     }
312 }
313
314 #[derive(Default)]
315 struct Stats {
316     terminals: [usize; 32],
317     negations: usize,
318     ops: usize,
319 }
320
321 fn terminal_stats(b: &Bool) -> Stats {
322     fn recurse(b: &Bool, stats: &mut Stats) {
323         match *b {
324             True | False => stats.ops += 1,
325             Not(ref inner) => {
326                 match **inner {
327                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
328                     _ => stats.negations += 1,
329                 }
330                 recurse(inner, stats);
331             },
332             And(ref v) | Or(ref v) => {
333                 stats.ops += v.len() - 1;
334                 for inner in v {
335                     recurse(inner, stats);
336                 }
337             },
338             Term(n) => stats.terminals[n as usize] += 1,
339         }
340     }
341     use quine_mc_cluskey::Bool::*;
342     let mut stats = Stats::default();
343     recurse(b, &mut stats);
344     stats
345 }
346
347 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
348     fn bool_expr(&self, e: &Expr) {
349         let mut h2q = Hir2Qmm {
350             terminals: Vec::new(),
351             cx: self.cx,
352         };
353         if let Ok(expr) = h2q.run(e) {
354             if h2q.terminals.len() > 8 {
355                 // QMC has exponentially slow behavior as the number of terminals increases
356                 // 8 is reasonable, it takes approximately 0.2 seconds.
357                 // See #825
358                 return;
359             }
360
361             let stats = terminal_stats(&expr);
362             let mut simplified = expr.simplify();
363             for simple in Bool::Not(Box::new(expr.clone())).simplify() {
364                 match simple {
365                     Bool::Not(_) | Bool::True | Bool::False => {},
366                     _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
367                 }
368                 let simple_negated = simple_negate(simple);
369                 if simplified.iter().any(|s| *s == simple_negated) {
370                     continue;
371                 }
372                 simplified.push(simple_negated);
373             }
374             let mut improvements = Vec::new();
375             'simplified: for suggestion in &simplified {
376                 let simplified_stats = terminal_stats(suggestion);
377                 let mut improvement = false;
378                 for i in 0..32 {
379                     // ignore any "simplifications" that end up requiring a terminal more often
380                     // than in the original expression
381                     if stats.terminals[i] < simplified_stats.terminals[i] {
382                         continue 'simplified;
383                     }
384                     if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
385                         span_lint_and_then(
386                             self.cx,
387                             LOGIC_BUG,
388                             e.span,
389                             "this boolean expression contains a logic bug",
390                             |db| {
391                                 db.span_help(
392                                     h2q.terminals[i].span,
393                                     "this expression can be optimized out by applying boolean operations to the \
394                                      outer expression",
395                                 );
396                                 db.span_suggestion(
397                                     e.span,
398                                     "it would look like the following",
399                                     suggest(self.cx, suggestion, &h2q.terminals).0,
400                                 );
401                             },
402                         );
403                         // don't also lint `NONMINIMAL_BOOL`
404                         return;
405                     }
406                     // if the number of occurrences of a terminal decreases or any of the stats
407                     // decreases while none increases
408                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
409                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
410                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
411                 }
412                 if improvement {
413                     improvements.push(suggestion);
414                 }
415             }
416             let nonminimal_bool_lint = |suggestions| {
417                 span_lint_and_then(
418                     self.cx,
419                     NONMINIMAL_BOOL,
420                     e.span,
421                     "this boolean expression can be simplified",
422                     |db| { db.span_suggestions(e.span, "try", suggestions); },
423                 );
424             };
425             if improvements.is_empty() {
426                 let suggest = suggest(self.cx, &expr, &h2q.terminals);
427                 if suggest.1 {
428                     nonminimal_bool_lint(vec![suggest.0])
429                 }
430             } else {
431                 nonminimal_bool_lint(
432                     improvements
433                         .into_iter()
434                         .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
435                         .collect()
436                 );
437             }
438         }
439     }
440 }
441
442 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
443     fn visit_expr(&mut self, e: &'tcx Expr) {
444         if in_macro(e.span) {
445             return;
446         }
447         match e.node {
448             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
449             ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
450                 self.bool_expr(e);
451             } else {
452                 walk_expr(self, e);
453             },
454             _ => walk_expr(self, e),
455         }
456     }
457     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
458         NestedVisitorMap::None
459     }
460 }