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