]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Merge pull request #1931 from rust-lang-nursery/move_links
[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                             hir_id: DUMMY_HIR_ID,
126                             span: DUMMY_SP,
127                             attrs: ThinVec::new(),
128                             node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
129                         }
130                     };
131                     match binop.node {
132                         BiEq => mk_expr(BiNe),
133                         BiNe => mk_expr(BiEq),
134                         BiGt => mk_expr(BiLe),
135                         BiGe => mk_expr(BiLt),
136                         BiLt => mk_expr(BiGe),
137                         BiLe => mk_expr(BiGt),
138                         _ => continue,
139                     }
140                 },
141                 _ => continue,
142             };
143             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
144                 #[allow(cast_possible_truncation)] return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
145             }
146         }
147         let n = self.terminals.len();
148         self.terminals.push(e);
149         if n < 32 {
150             #[allow(cast_possible_truncation)] Ok(Bool::Term(n as u8))
151         } else {
152             Err("too many literals".to_owned())
153         }
154     }
155 }
156
157 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
158     fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
159         use quine_mc_cluskey::Bool::*;
160         let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
161         match *suggestion {
162             True => {
163                 s.push_str("true");
164                 s
165             },
166             False => {
167                 s.push_str("false");
168                 s
169             },
170             Not(ref inner) => {
171                 match **inner {
172                     And(_) | Or(_) => {
173                         s.push('!');
174                         recurse(true, cx, inner, terminals, s)
175                     },
176                     Term(n) => {
177                         if let ExprBinary(binop, ref lhs, ref rhs) = terminals[n as usize].node {
178                             let op = match binop.node {
179                                 BiEq => " != ",
180                                 BiNe => " == ",
181                                 BiLt => " >= ",
182                                 BiGt => " <= ",
183                                 BiLe => " > ",
184                                 BiGe => " < ",
185                                 _ => {
186                                     s.push('!');
187                                     return recurse(true, cx, inner, terminals, s);
188                                 },
189                             };
190                             s.push_str(&snip(lhs));
191                             s.push_str(op);
192                             s.push_str(&snip(rhs));
193                             s
194                         } else {
195                             s.push('!');
196                             recurse(false, cx, inner, terminals, s)
197                         }
198                     },
199                     _ => {
200                         s.push('!');
201                         recurse(false, cx, inner, terminals, s)
202                     },
203                 }
204             },
205             And(ref v) => {
206                 if brackets {
207                     s.push('(');
208                 }
209                 if let Or(_) = v[0] {
210                     s = recurse(true, cx, &v[0], terminals, s);
211                 } else {
212                     s = recurse(false, cx, &v[0], terminals, s);
213                 }
214                 for inner in &v[1..] {
215                     s.push_str(" && ");
216                     if let Or(_) = *inner {
217                         s = recurse(true, cx, inner, terminals, s);
218                     } else {
219                         s = recurse(false, cx, inner, terminals, s);
220                     }
221                 }
222                 if brackets {
223                     s.push(')');
224                 }
225                 s
226             },
227             Or(ref v) => {
228                 if brackets {
229                     s.push('(');
230                 }
231                 s = recurse(false, cx, &v[0], terminals, s);
232                 for inner in &v[1..] {
233                     s.push_str(" || ");
234                     s = recurse(false, cx, inner, terminals, s);
235                 }
236                 if brackets {
237                     s.push(')');
238                 }
239                 s
240             },
241             Term(n) => {
242                 if brackets {
243                     if let ExprBinary(..) = terminals[n as usize].node {
244                         s.push('(');
245                     }
246                 }
247                 s.push_str(&snip(terminals[n as usize]));
248                 if brackets {
249                     if let ExprBinary(..) = terminals[n as usize].node {
250                         s.push(')');
251                     }
252                 }
253                 s
254             },
255         }
256     }
257     recurse(false, cx, suggestion, terminals, String::new())
258 }
259
260 fn simple_negate(b: Bool) -> Bool {
261     use quine_mc_cluskey::Bool::*;
262     match b {
263         True => False,
264         False => True,
265         t @ Term(_) => Not(Box::new(t)),
266         And(mut v) => {
267             for el in &mut v {
268                 *el = simple_negate(::std::mem::replace(el, True));
269             }
270             Or(v)
271         },
272         Or(mut v) => {
273             for el in &mut v {
274                 *el = simple_negate(::std::mem::replace(el, True));
275             }
276             And(v)
277         },
278         Not(inner) => *inner,
279     }
280 }
281
282 #[derive(Default)]
283 struct Stats {
284     terminals: [usize; 32],
285     negations: usize,
286     ops: usize,
287 }
288
289 fn terminal_stats(b: &Bool) -> Stats {
290     fn recurse(b: &Bool, stats: &mut Stats) {
291         match *b {
292             True | False => stats.ops += 1,
293             Not(ref inner) => {
294                 match **inner {
295                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
296                     _ => stats.negations += 1,
297                 }
298                 recurse(inner, stats);
299             },
300             And(ref v) | Or(ref v) => {
301                 stats.ops += v.len() - 1;
302                 for inner in v {
303                     recurse(inner, stats);
304                 }
305             },
306             Term(n) => stats.terminals[n as usize] += 1,
307         }
308     }
309     use quine_mc_cluskey::Bool::*;
310     let mut stats = Stats::default();
311     recurse(b, &mut stats);
312     stats
313 }
314
315 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
316     fn bool_expr(&self, e: &Expr) {
317         let mut h2q = Hir2Qmm {
318             terminals: Vec::new(),
319             cx: self.cx,
320         };
321         if let Ok(expr) = h2q.run(e) {
322
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
407 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
408     fn visit_expr(&mut self, e: &'tcx Expr) {
409         if in_macro(e.span) {
410             return;
411         }
412         match e.node {
413             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
414             ExprUnary(UnNot, ref inner) => {
415                 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
416                     self.bool_expr(e);
417                 } else {
418                     walk_expr(self, e);
419                 }
420             },
421             _ => walk_expr(self, e),
422         }
423     }
424     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
425         NestedVisitorMap::None
426     }
427 }