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