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