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