]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Auto merge of #4100 - phansch:add_stderr_length_check, r=flip1995
[rust.git] / clippy_lints / src / booleans.rs
1 use crate::utils::{
2     get_trait_def_id, implements_trait, in_macro, in_macro_or_desugar, match_type, paths, snippet_opt,
3     span_lint_and_then, SpanlessEq,
4 };
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_data_structures::thin_vec::ThinVec;
10 use rustc_errors::Applicability;
11 use syntax::ast::LitKind;
12 use syntax::source_map::{dummy_spanned, Span, DUMMY_SP};
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for boolean expressions that can be written more
16     /// concisely.
17     ///
18     /// **Why is this bad?** Readability of boolean expressions suffers from
19     /// unnecessary duplication.
20     ///
21     /// **Known problems:** Ignores short circuiting behavior of `||` and
22     /// `&&`. Ignores `|`, `&` and `^`.
23     ///
24     /// **Example:**
25     /// ```ignore
26     /// if a && true  // should be: if a
27     /// if !(a == b)  // should be: if a != b
28     /// ```
29     pub NONMINIMAL_BOOL,
30     complexity,
31     "boolean expressions that can be written more concisely"
32 }
33
34 declare_clippy_lint! {
35     /// **What it does:** Checks for boolean expressions that contain terminals that
36     /// can be eliminated.
37     ///
38     /// **Why is this bad?** This is most likely a logic bug.
39     ///
40     /// **Known problems:** Ignores short circuiting behavior.
41     ///
42     /// **Example:**
43     /// ```ignore
44     /// if a && b || a { ... }
45     /// ```
46     /// The `b` is unnecessary, the expression is equivalent to `if a`.
47     pub LOGIC_BUG,
48     correctness,
49     "boolean expressions that contain terminals which can be eliminated"
50 }
51
52 // For each pairs, both orders are considered.
53 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
54
55 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, LOGIC_BUG]);
56
57 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
58     fn check_fn(
59         &mut self,
60         cx: &LateContext<'a, 'tcx>,
61         _: intravisit::FnKind<'tcx>,
62         _: &'tcx FnDecl,
63         body: &'tcx Body,
64         _: Span,
65         _: HirId,
66     ) {
67         NonminimalBoolVisitor { cx }.visit_body(body)
68     }
69 }
70
71 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
72     cx: &'a LateContext<'a, 'tcx>,
73 }
74
75 use quine_mc_cluskey::Bool;
76 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
77     terminals: Vec<&'v Expr>,
78     cx: &'a LateContext<'a, 'tcx>,
79 }
80
81 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
82     fn extract(&mut self, op: BinOpKind, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
83         for a in a {
84             if let ExprKind::Binary(binop, lhs, rhs) = &a.node {
85                 if binop.node == op {
86                     v = self.extract(op, &[lhs, rhs], v)?;
87                     continue;
88                 }
89             }
90             v.push(self.run(a)?);
91         }
92         Ok(v)
93     }
94
95     fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
96         // prevent folding of `cfg!` macros and the like
97         if !in_macro_or_desugar(e.span) {
98             match &e.node {
99                 ExprKind::Unary(UnNot, inner) => return Ok(Bool::Not(box self.run(inner)?)),
100                 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
101                     BinOpKind::Or => return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?)),
102                     BinOpKind::And => return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?)),
103                     _ => (),
104                 },
105                 ExprKind::Lit(lit) => match lit.node {
106                     LitKind::Bool(true) => return Ok(Bool::True),
107                     LitKind::Bool(false) => return Ok(Bool::False),
108                     _ => (),
109                 },
110                 _ => (),
111             }
112         }
113         for (n, expr) in self.terminals.iter().enumerate() {
114             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
115                 #[allow(clippy::cast_possible_truncation)]
116                 return Ok(Bool::Term(n as u8));
117             }
118             let negated = match &e.node {
119                 ExprKind::Binary(binop, lhs, rhs) => {
120                     if !implements_ord(self.cx, lhs) {
121                         continue;
122                     }
123
124                     let mk_expr = |op| Expr {
125                         hir_id: DUMMY_HIR_ID,
126                         span: DUMMY_SP,
127                         attrs: ThinVec::new(),
128                         node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
129                     };
130                     match binop.node {
131                         BinOpKind::Eq => mk_expr(BinOpKind::Ne),
132                         BinOpKind::Ne => mk_expr(BinOpKind::Eq),
133                         BinOpKind::Gt => mk_expr(BinOpKind::Le),
134                         BinOpKind::Ge => mk_expr(BinOpKind::Lt),
135                         BinOpKind::Lt => mk_expr(BinOpKind::Ge),
136                         BinOpKind::Le => mk_expr(BinOpKind::Gt),
137                         _ => continue,
138                     }
139                 },
140                 _ => continue,
141             };
142             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
143                 #[allow(clippy::cast_possible_truncation)]
144                 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
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: 'a, 'v> {
159     terminals: &'v [&'v Expr],
160     cx: &'a LateContext<'a, 'tcx>,
161     output: String,
162     simplified: bool,
163 }
164
165 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
166     fn snip(&self, e: &Expr) -> Option<String> {
167         snippet_opt(self.cx, e.span)
168     }
169
170     fn simplify_not(&self, expr: &Expr) -> Option<String> {
171         match &expr.node {
172             ExprKind::Binary(binop, lhs, rhs) => {
173                 if !implements_ord(self.cx, lhs) {
174                     return None;
175                 }
176
177                 match binop.node {
178                     BinOpKind::Eq => Some(" != "),
179                     BinOpKind::Ne => Some(" == "),
180                     BinOpKind::Lt => Some(" >= "),
181                     BinOpKind::Gt => Some(" <= "),
182                     BinOpKind::Le => Some(" > "),
183                     BinOpKind::Ge => Some(" < "),
184                     _ => None,
185                 }
186                 .and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
187             },
188             ExprKind::MethodCall(path, _, args) if args.len() == 1 => {
189                 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
190                 if !match_type(self.cx, type_of_receiver, &paths::OPTION)
191                     && !match_type(self.cx, type_of_receiver, &paths::RESULT)
192                 {
193                     return None;
194                 }
195                 METHODS_WITH_NEGATION
196                     .iter()
197                     .cloned()
198                     .flat_map(|(a, b)| vec![(a, b), (b, a)])
199                     .find(|&(a, _)| a == path.ident.name.as_str())
200                     .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
201             },
202             _ => None,
203         }
204     }
205
206     fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
207         use quine_mc_cluskey::Bool::*;
208         match suggestion {
209             True => {
210                 self.output.push_str("true");
211             },
212             False => {
213                 self.output.push_str("false");
214             },
215             Not(inner) => match **inner {
216                 And(_) | Or(_) => {
217                     self.output.push('!');
218                     self.output.push('(');
219                     self.recurse(inner);
220                     self.output.push(')');
221                 },
222                 Term(n) => {
223                     let terminal = self.terminals[n as usize];
224                     if let Some(str) = self.simplify_not(terminal) {
225                         self.simplified = true;
226                         self.output.push_str(&str)
227                     } else {
228                         self.output.push('!');
229                         let snip = self.snip(terminal)?;
230                         self.output.push_str(&snip);
231                     }
232                 },
233                 True | False | Not(_) => {
234                     self.output.push('!');
235                     self.recurse(inner)?;
236                 },
237             },
238             And(v) => {
239                 for (index, inner) in v.iter().enumerate() {
240                     if index > 0 {
241                         self.output.push_str(" && ");
242                     }
243                     if let Or(_) = *inner {
244                         self.output.push('(');
245                         self.recurse(inner);
246                         self.output.push(')');
247                     } else {
248                         self.recurse(inner);
249                     }
250                 }
251             },
252             Or(v) => {
253                 for (index, inner) in v.iter().enumerate() {
254                     if index > 0 {
255                         self.output.push_str(" || ");
256                     }
257                     self.recurse(inner);
258                 }
259             },
260             &Term(n) => {
261                 let snip = self.snip(self.terminals[n as usize])?;
262                 self.output.push_str(&snip);
263             },
264         }
265         Some(())
266     }
267 }
268
269 // The boolean part of the return indicates whether some simplifications have been applied.
270 fn suggest(cx: &LateContext<'_, '_>, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
271     let mut suggest_context = SuggestContext {
272         terminals,
273         cx,
274         output: String::new(),
275         simplified: false,
276     };
277     suggest_context.recurse(suggestion);
278     (suggest_context.output, suggest_context.simplified)
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: &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.clone())).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).0,
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 suggest = suggest(self.cx, &expr, &h2q.terminals);
428                 if suggest.1 {
429                     nonminimal_bool_lint(vec![suggest.0])
430                 }
431             } else {
432                 nonminimal_bool_lint(
433                     improvements
434                         .into_iter()
435                         .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
436                         .collect(),
437                 );
438             }
439         }
440     }
441 }
442
443 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
444     fn visit_expr(&mut self, e: &'tcx Expr) {
445         if in_macro(e.span) {
446             return;
447         }
448         match &e.node {
449             ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
450                 self.bool_expr(e)
451             },
452             ExprKind::Unary(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<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
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 }