]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Rustfmt
[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, NodeId};
5 use syntax::codemap::{DUMMY_SP, dummy_spanned, Span};
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_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) => {
100                     match binop.node {
101                         BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
102                         BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
103                         _ => (),
104                     }
105                 },
106                 ExprLit(ref lit) => {
107                     match lit.node {
108                         LitKind::Bool(true) => return Ok(Bool::True),
109                         LitKind::Bool(false) => return Ok(Bool::False),
110                         _ => (),
111                     }
112                 },
113                 _ => (),
114             }
115         }
116         for (n, expr) in self.terminals.iter().enumerate() {
117             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
118                 #[allow(cast_possible_truncation)] return Ok(Bool::Term(n as u8));
119             }
120             let negated = match e.node {
121                 ExprBinary(binop, ref lhs, ref rhs) => {
122                     let mk_expr = |op| {
123                         Expr {
124                             id: DUMMY_NODE_ID,
125                             span: DUMMY_SP,
126                             attrs: ThinVec::new(),
127                             node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
128                         }
129                     };
130                     match binop.node {
131                         BiEq => mk_expr(BiNe),
132                         BiNe => mk_expr(BiEq),
133                         BiGt => mk_expr(BiLe),
134                         BiGe => mk_expr(BiLt),
135                         BiLt => mk_expr(BiGe),
136                         BiLe => mk_expr(BiGt),
137                         _ => continue,
138                     }
139                 },
140                 _ => continue,
141             };
142             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
143                 #[allow(cast_possible_truncation)] return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
144             }
145         }
146         let n = self.terminals.len();
147         self.terminals.push(e);
148         if n < 32 {
149             #[allow(cast_possible_truncation)] 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) => {
170                 match **inner {
171                     And(_) | Or(_) => {
172                         s.push('!');
173                         recurse(true, cx, inner, terminals, s)
174                     },
175                     Term(n) => {
176                         if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
177                             let op = match binop.node {
178                                 BiEq => " != ",
179                                 BiNe => " == ",
180                                 BiLt => " >= ",
181                                 BiGt => " <= ",
182                                 BiLe => " > ",
183                                 BiGe => " < ",
184                                 _ => {
185                                     s.push('!');
186                                     return recurse(true, cx, inner, terminals, s);
187                                 },
188                             };
189                             s.push_str(&snip(lhs));
190                             s.push_str(op);
191                             s.push_str(&snip(rhs));
192                             s
193                         } else {
194                             s.push('!');
195                             recurse(false, cx, inner, terminals, s)
196                         }
197                     },
198                     _ => {
199                         s.push('!');
200                         recurse(false, cx, inner, terminals, s)
201                     },
202                 }
203             },
204             And(ref v) => {
205                 if brackets {
206                     s.push('(');
207                 }
208                 if let Or(_) = v[0] {
209                     s = recurse(true, cx, &v[0], terminals, s);
210                 } else {
211                     s = recurse(false, cx, &v[0], terminals, s);
212                 }
213                 for inner in &v[1..] {
214                     s.push_str(" && ");
215                     if let Or(_) = *inner {
216                         s = recurse(true, cx, inner, terminals, s);
217                     } else {
218                         s = recurse(false, cx, inner, terminals, s);
219                     }
220                 }
221                 if brackets {
222                     s.push(')');
223                 }
224                 s
225             },
226             Or(ref v) => {
227                 if brackets {
228                     s.push('(');
229                 }
230                 s = recurse(false, cx, &v[0], terminals, s);
231                 for inner in &v[1..] {
232                     s.push_str(" || ");
233                     s = recurse(false, cx, inner, terminals, s);
234                 }
235                 if brackets {
236                     s.push(')');
237                 }
238                 s
239             },
240             Term(n) => {
241                 if brackets {
242                     if let ExprBinary(..) = terminals[n as usize].node {
243                         s.push('(');
244                     }
245                 }
246                 s.push_str(&snip(terminals[n as usize]));
247                 if brackets {
248                     if let ExprBinary(..) = terminals[n as usize].node {
249                         s.push(')');
250                     }
251                 }
252                 s
253             },
254         }
255     }
256     recurse(false, cx, suggestion, terminals, String::new())
257 }
258
259 fn simple_negate(b: Bool) -> Bool {
260     use quine_mc_cluskey::Bool::*;
261     match b {
262         True => False,
263         False => True,
264         t @ Term(_) => Not(Box::new(t)),
265         And(mut v) => {
266             for el in &mut v {
267                 *el = simple_negate(::std::mem::replace(el, True));
268             }
269             Or(v)
270         },
271         Or(mut v) => {
272             for el in &mut v {
273                 *el = simple_negate(::std::mem::replace(el, True));
274             }
275             And(v)
276         },
277         Not(inner) => *inner,
278     }
279 }
280
281 #[derive(Default)]
282 struct Stats {
283     terminals: [usize; 32],
284     negations: usize,
285     ops: usize,
286 }
287
288 fn terminal_stats(b: &Bool) -> Stats {
289     fn recurse(b: &Bool, stats: &mut Stats) {
290         match *b {
291             True | False => stats.ops += 1,
292             Not(ref inner) => {
293                 match **inner {
294                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
295                     _ => stats.negations += 1,
296                 }
297                 recurse(inner, stats);
298             },
299             And(ref v) | Or(ref v) => {
300                 stats.ops += v.len() - 1;
301                 for inner in v {
302                     recurse(inner, stats);
303                 }
304             },
305             Term(n) => stats.terminals[n as usize] += 1,
306         }
307     }
308     use quine_mc_cluskey::Bool::*;
309     let mut stats = Stats::default();
310     recurse(b, &mut stats);
311     stats
312 }
313
314 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
315     fn bool_expr(&self, e: &Expr) {
316         let mut h2q = Hir2Qmm {
317             terminals: Vec::new(),
318             cx: self.cx,
319         };
320         if let Ok(expr) = h2q.run(e) {
321
322             if h2q.terminals.len() > 8 {
323                 // QMC has exponentially slow behavior as the number of terminals increases
324                 // 8 is reasonable, it takes approximately 0.2 seconds.
325                 // See #825
326                 return;
327             }
328
329             let stats = terminal_stats(&expr);
330             let mut simplified = expr.simplify();
331             for simple in Bool::Not(Box::new(expr.clone())).simplify() {
332                 match simple {
333                     Bool::Not(_) | Bool::True | Bool::False => {},
334                     _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
335                 }
336                 let simple_negated = simple_negate(simple);
337                 if simplified.iter().any(|s| *s == simple_negated) {
338                     continue;
339                 }
340                 simplified.push(simple_negated);
341             }
342             let mut improvements = Vec::new();
343             'simplified: for suggestion in &simplified {
344                 let simplified_stats = terminal_stats(suggestion);
345                 let mut improvement = false;
346                 for i in 0..32 {
347                     // ignore any "simplifications" that end up requiring a terminal more often
348                     // than in the original expression
349                     if stats.terminals[i] < simplified_stats.terminals[i] {
350                         continue 'simplified;
351                     }
352                     if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
353                         span_lint_and_then(
354                             self.cx,
355                             LOGIC_BUG,
356                             e.span,
357                             "this boolean expression contains a logic bug",
358                             |db| {
359                                 db.span_help(
360                                     h2q.terminals[i].span,
361                                     "this expression can be optimized out by applying boolean operations to the \
362                                           outer expression",
363                                 );
364                                 db.span_suggestion(
365                                     e.span,
366                                     "it would look like the following",
367                                     suggest(self.cx, suggestion, &h2q.terminals),
368                                 );
369                             },
370                         );
371                         // don't also lint `NONMINIMAL_BOOL`
372                         return;
373                     }
374                     // if the number of occurrences of a terminal decreases or any of the stats
375                     // decreases while none increases
376                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i]) ||
377                         (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops) ||
378                         (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
379                 }
380                 if improvement {
381                     improvements.push(suggestion);
382                 }
383             }
384             if !improvements.is_empty() {
385                 span_lint_and_then(
386                     self.cx,
387                     NONMINIMAL_BOOL,
388                     e.span,
389                     "this boolean expression can be simplified",
390                     |db| {
391                         db.span_suggestions(
392                             e.span,
393                             "try",
394                             improvements
395                                 .into_iter()
396                                 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
397                                 .collect(),
398                         );
399                     },
400                 );
401             }
402         }
403     }
404 }
405
406 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
407     fn visit_expr(&mut self, e: &'tcx Expr) {
408         if in_macro(e.span) {
409             return;
410         }
411         match e.node {
412             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
413             ExprUnary(UnNot, ref inner) => {
414                 if self.cx.tables.node_types[&inner.id].is_bool() {
415                     self.bool_expr(e);
416                 } else {
417                     walk_expr(self, e);
418                 }
419             },
420             _ => walk_expr(self, e),
421         }
422     }
423     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
424         NestedVisitorMap::None
425     }
426 }