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