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