]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Reformat random_state tests
[rust.git] / clippy_lints / src / booleans.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::{
11     get_trait_def_id, implements_trait, in_macro, match_type, paths, snippet_opt, span_lint_and_then, SpanlessEq,
12 };
13 use rustc::hir::intravisit::*;
14 use rustc::hir::*;
15 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use rustc::{declare_tool_lint, lint_array};
17 use rustc_data_structures::thin_vec::ThinVec;
18 use rustc_errors::Applicability;
19 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
20 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
21
22 /// **What it does:** Checks for boolean expressions that can be written more
23 /// concisely.
24 ///
25 /// **Why is this bad?** Readability of boolean expressions suffers from
26 /// unnecessary duplication.
27 ///
28 /// **Known problems:** Ignores short circuiting behavior of `||` and
29 /// `&&`. Ignores `|`, `&` and `^`.
30 ///
31 /// **Example:**
32 /// ```rust
33 /// if a && true  // should be: if a
34 /// if !(a == b)  // should be: if a != b
35 /// ```
36 declare_clippy_lint! {
37     pub NONMINIMAL_BOOL,
38     complexity,
39     "boolean expressions that can be written more concisely"
40 }
41
42 /// **What it does:** Checks for boolean expressions that contain terminals that
43 /// can be eliminated.
44 ///
45 /// **Why is this bad?** This is most likely a logic bug.
46 ///
47 /// **Known problems:** Ignores short circuiting behavior.
48 ///
49 /// **Example:**
50 /// ```rust
51 /// if a && b || a { ... }
52 /// ```
53 /// The `b` is unnecessary, the expression is equivalent to `if a`.
54 declare_clippy_lint! {
55     pub LOGIC_BUG,
56     correctness,
57     "boolean expressions that contain terminals which can be eliminated"
58 }
59
60 // For each pairs, both orders are considered.
61 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
62
63 #[derive(Copy, Clone)]
64 pub struct NonminimalBool;
65
66 impl LintPass for NonminimalBool {
67     fn get_lints(&self) -> LintArray {
68         lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
69     }
70 }
71
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
73     fn check_fn(
74         &mut self,
75         cx: &LateContext<'a, 'tcx>,
76         _: intravisit::FnKind<'tcx>,
77         _: &'tcx FnDecl,
78         body: &'tcx Body,
79         _: Span,
80         _: NodeId,
81     ) {
82         NonminimalBoolVisitor { cx }.visit_body(body)
83     }
84 }
85
86 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
87     cx: &'a LateContext<'a, 'tcx>,
88 }
89
90 use quine_mc_cluskey::Bool;
91 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
92     terminals: Vec<&'v Expr>,
93     cx: &'a LateContext<'a, 'tcx>,
94 }
95
96 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
97     fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
98         for a in a {
99             if let ExprKind::Binary(binop, ref lhs, ref rhs) = a.node {
100                 if binop.node == op {
101                     v = self.extract(op, &[lhs, rhs], v)?;
102                     continue;
103                 }
104             }
105             v.push(self.run(a)?);
106         }
107         Ok(v)
108     }
109
110     fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
111         // prevent folding of `cfg!` macros and the like
112         if !in_macro(e.span) {
113             match e.node {
114                 ExprKind::Unary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
115                 ExprKind::Binary(binop, ref lhs, ref rhs) => match binop.node {
116                     BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
117                     BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
118                     _ => (),
119                 },
120                 ExprKind::Lit(ref lit) => match lit.node {
121                     LitKind::Bool(true) => return Ok(Bool::True),
122                     LitKind::Bool(false) => return Ok(Bool::False),
123                     _ => (),
124                 },
125                 _ => (),
126             }
127         }
128         for (n, expr) in self.terminals.iter().enumerate() {
129             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
130                 #[allow(clippy::cast_possible_truncation)]
131                 return Ok(Bool::Term(n as u8));
132             }
133             let negated = match e.node {
134                 ExprKind::Binary(binop, ref lhs, ref rhs) => {
135                     if !implements_ord(self.cx, lhs) {
136                         continue;
137                     }
138
139                     let mk_expr = |op| Expr {
140                         id: DUMMY_NODE_ID,
141                         hir_id: DUMMY_HIR_ID,
142                         span: DUMMY_SP,
143                         attrs: ThinVec::new(),
144                         node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
145                     };
146                     match binop.node {
147                         BinOpKind::Eq => mk_expr(BinOpKind::Ne),
148                         BinOpKind::Ne => mk_expr(BinOpKind::Eq),
149                         BinOpKind::Gt => mk_expr(BinOpKind::Le),
150                         BinOpKind::Ge => mk_expr(BinOpKind::Lt),
151                         BinOpKind::Lt => mk_expr(BinOpKind::Ge),
152                         BinOpKind::Le => mk_expr(BinOpKind::Gt),
153                         _ => continue,
154                     }
155                 },
156                 _ => continue,
157             };
158             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
159                 #[allow(clippy::cast_possible_truncation)]
160                 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
161             }
162         }
163         let n = self.terminals.len();
164         self.terminals.push(e);
165         if n < 32 {
166             #[allow(clippy::cast_possible_truncation)]
167             Ok(Bool::Term(n as u8))
168         } else {
169             Err("too many literals".to_owned())
170         }
171     }
172 }
173
174 struct SuggestContext<'a, 'tcx: 'a, 'v> {
175     terminals: &'v [&'v Expr],
176     cx: &'a LateContext<'a, 'tcx>,
177     output: String,
178     simplified: bool,
179 }
180
181 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
182     fn snip(&self, e: &Expr) -> Option<String> {
183         snippet_opt(self.cx, e.span)
184     }
185
186     fn simplify_not(&self, expr: &Expr) -> Option<String> {
187         match expr.node {
188             ExprKind::Binary(binop, ref lhs, ref rhs) => {
189                 if !implements_ord(self.cx, lhs) {
190                     return None;
191                 }
192
193                 match binop.node {
194                     BinOpKind::Eq => Some(" != "),
195                     BinOpKind::Ne => Some(" == "),
196                     BinOpKind::Lt => Some(" >= "),
197                     BinOpKind::Gt => Some(" <= "),
198                     BinOpKind::Le => Some(" > "),
199                     BinOpKind::Ge => Some(" < "),
200                     _ => None,
201                 }
202                 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
203             },
204             ExprKind::MethodCall(ref path, _, ref args) if args.len() == 1 => {
205                 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
206                 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
207                     && !match_type(self.cx, type_of_receiver, &paths::RESULT)
208                 {
209                     return None;
210                 }
211                 METHODS_WITH_NEGATION
212                     .iter()
213                     .cloned()
214                     .flat_map(|(a, b)| vec![(a, b), (b, a)])
215                     .find(|&(a, _)| a == path.ident.as_str())
216                     .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
217             },
218             _ => None,
219         }
220     }
221
222     fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
223         use quine_mc_cluskey::Bool::*;
224         match *suggestion {
225             True => {
226                 self.output.push_str("true");
227             },
228             False => {
229                 self.output.push_str("false");
230             },
231             Not(ref inner) => match **inner {
232                 And(_) | Or(_) => {
233                     self.output.push('!');
234                     self.output.push('(');
235                     self.recurse(inner);
236                     self.output.push(')');
237                 },
238                 Term(n) => {
239                     let terminal = self.terminals[n as usize];
240                     if let Some(str) = self.simplify_not(terminal) {
241                         self.simplified = true;
242                         self.output.push_str(&str)
243                     } else {
244                         self.output.push('!');
245                         let snip = self.snip(terminal)?;
246                         self.output.push_str(&snip);
247                     }
248                 },
249                 True | False | Not(_) => {
250                     self.output.push('!');
251                     self.recurse(inner)?;
252                 },
253             },
254             And(ref v) => {
255                 for (index, inner) in v.iter().enumerate() {
256                     if index > 0 {
257                         self.output.push_str(" && ");
258                     }
259                     if let Or(_) = *inner {
260                         self.output.push('(');
261                         self.recurse(inner);
262                         self.output.push(')');
263                     } else {
264                         self.recurse(inner);
265                     }
266                 }
267             },
268             Or(ref v) => {
269                 for (index, inner) in v.iter().enumerate() {
270                     if index > 0 {
271                         self.output.push_str(" || ");
272                     }
273                     self.recurse(inner);
274                 }
275             },
276             Term(n) => {
277                 let snip = self.snip(self.terminals[n as usize])?;
278                 self.output.push_str(&snip);
279             },
280         }
281         Some(())
282     }
283 }
284
285 // The boolean part of the return indicates whether some simplifications have been applied.
286 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
287     let mut suggest_context = SuggestContext {
288         terminals,
289         cx,
290         output: String::new(),
291         simplified: false,
292     };
293     suggest_context.recurse(suggestion);
294     (suggest_context.output, suggest_context.simplified)
295 }
296
297 fn simple_negate(b: Bool) -> Bool {
298     use quine_mc_cluskey::Bool::*;
299     match b {
300         True => False,
301         False => True,
302         t @ Term(_) => Not(Box::new(t)),
303         And(mut v) => {
304             for el in &mut v {
305                 *el = simple_negate(::std::mem::replace(el, True));
306             }
307             Or(v)
308         },
309         Or(mut v) => {
310             for el in &mut v {
311                 *el = simple_negate(::std::mem::replace(el, True));
312             }
313             And(v)
314         },
315         Not(inner) => *inner,
316     }
317 }
318
319 #[derive(Default)]
320 struct Stats {
321     terminals: [usize; 32],
322     negations: usize,
323     ops: usize,
324 }
325
326 fn terminal_stats(b: &Bool) -> Stats {
327     fn recurse(b: &Bool, stats: &mut Stats) {
328         match *b {
329             True | False => stats.ops += 1,
330             Not(ref inner) => {
331                 match **inner {
332                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
333                     _ => stats.negations += 1,
334                 }
335                 recurse(inner, stats);
336             },
337             And(ref v) | Or(ref v) => {
338                 stats.ops += v.len() - 1;
339                 for inner in v {
340                     recurse(inner, stats);
341                 }
342             },
343             Term(n) => stats.terminals[n as usize] += 1,
344         }
345     }
346     use quine_mc_cluskey::Bool::*;
347     let mut stats = Stats::default();
348     recurse(b, &mut stats);
349     stats
350 }
351
352 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
353     fn bool_expr(&self, e: &Expr) {
354         let mut h2q = Hir2Qmm {
355             terminals: Vec::new(),
356             cx: self.cx,
357         };
358         if let Ok(expr) = h2q.run(e) {
359             if h2q.terminals.len() > 8 {
360                 // QMC has exponentially slow behavior as the number of terminals increases
361                 // 8 is reasonable, it takes approximately 0.2 seconds.
362                 // See #825
363                 return;
364             }
365
366             let stats = terminal_stats(&expr);
367             let mut simplified = expr.simplify();
368             for simple in Bool::Not(Box::new(expr.clone())).simplify() {
369                 match simple {
370                     Bool::Not(_) | Bool::True | Bool::False => {},
371                     _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
372                 }
373                 let simple_negated = simple_negate(simple);
374                 if simplified.iter().any(|s| *s == simple_negated) {
375                     continue;
376                 }
377                 simplified.push(simple_negated);
378             }
379             let mut improvements = Vec::new();
380             'simplified: for suggestion in &simplified {
381                 let simplified_stats = terminal_stats(suggestion);
382                 let mut improvement = false;
383                 for i in 0..32 {
384                     // ignore any "simplifications" that end up requiring a terminal more often
385                     // than in the original expression
386                     if stats.terminals[i] < simplified_stats.terminals[i] {
387                         continue 'simplified;
388                     }
389                     if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
390                         span_lint_and_then(
391                             self.cx,
392                             LOGIC_BUG,
393                             e.span,
394                             "this boolean expression contains a logic bug",
395                             |db| {
396                                 db.span_help(
397                                     h2q.terminals[i].span,
398                                     "this expression can be optimized out by applying boolean operations to the \
399                                      outer expression",
400                                 );
401                                 db.span_suggestion_with_applicability(
402                                     e.span,
403                                     "it would look like the following",
404                                     suggest(self.cx, suggestion, &h2q.terminals).0,
405                                     // nonminimal_bool can produce minimal but
406                                     // not human readable expressions (#3141)
407                                     Applicability::Unspecified,
408                                 );
409                             },
410                         );
411                         // don't also lint `NONMINIMAL_BOOL`
412                         return;
413                     }
414                     // if the number of occurrences of a terminal decreases or any of the stats
415                     // decreases while none increases
416                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
417                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
418                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
419                 }
420                 if improvement {
421                     improvements.push(suggestion);
422                 }
423             }
424             let nonminimal_bool_lint = |suggestions: Vec<_>| {
425                 span_lint_and_then(
426                     self.cx,
427                     NONMINIMAL_BOOL,
428                     e.span,
429                     "this boolean expression can be simplified",
430                     |db| {
431                         db.span_suggestions_with_applicability(
432                             e.span,
433                             "try",
434                             suggestions.into_iter(),
435                             // nonminimal_bool can produce minimal but
436                             // not human readable expressions (#3141)
437                             Applicability::Unspecified,
438                         );
439                     },
440                 );
441             };
442             if improvements.is_empty() {
443                 let suggest = suggest(self.cx, &expr, &h2q.terminals);
444                 if suggest.1 {
445                     nonminimal_bool_lint(vec![suggest.0])
446                 }
447             } else {
448                 nonminimal_bool_lint(
449                     improvements
450                         .into_iter()
451                         .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
452                         .collect(),
453                 );
454             }
455         }
456     }
457 }
458
459 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
460     fn visit_expr(&mut self, e: &'tcx Expr) {
461         if in_macro(e.span) {
462             return;
463         }
464         match e.node {
465             ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
466                 self.bool_expr(e)
467             },
468             ExprKind::Unary(UnNot, ref inner) => {
469                 if self.cx.tables.node_types()[inner.hir_id].is_bool() {
470                     self.bool_expr(e);
471                 } else {
472                     walk_expr(self, e);
473                 }
474             },
475             _ => walk_expr(self, e),
476         }
477     }
478     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
479         NestedVisitorMap::None
480     }
481 }
482
483 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
484     let ty = cx.tables.expr_ty(expr);
485     get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[]))
486 }