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