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