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