]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / booleans.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::{declare_lint, lint_array};
3 use rustc::hir::*;
4 use rustc::hir::intravisit::*;
5 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
6 use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
7 use syntax::util::ThinVec;
8 use crate::utils::{in_macro, paths, match_type, snippet_opt, span_lint_and_then, SpanlessEq, get_trait_def_id, implements_trait};
9
10 /// **What it does:** Checks for boolean expressions that can be written more
11 /// concisely.
12 ///
13 /// **Why is this bad?** Readability of boolean expressions suffers from
14 /// unnecessary duplication.
15 ///
16 /// **Known problems:** Ignores short circuiting behavior of `||` and
17 /// `&&`. Ignores `|`, `&` and `^`.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// if a && true  // should be: if a
22 /// if !(a == b)  // should be: if a != b
23 /// ```
24 declare_clippy_lint! {
25     pub NONMINIMAL_BOOL,
26     complexity,
27     "boolean expressions that can be written more concisely"
28 }
29
30 /// **What it does:** Checks for boolean expressions that contain terminals that
31 /// can be eliminated.
32 ///
33 /// **Why is this bad?** This is most likely a logic bug.
34 ///
35 /// **Known problems:** Ignores short circuiting behavior.
36 ///
37 /// **Example:**
38 /// ```rust
39 /// if a && b || a { ... }
40 /// ```
41 /// The `b` is unnecessary, the expression is equivalent to `if a`.
42 declare_clippy_lint! {
43     pub LOGIC_BUG,
44     correctness,
45     "boolean expressions that contain terminals which can be eliminated"
46 }
47
48 // For each pairs, both orders are considered.
49 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [
50     ("is_some", "is_none"),
51     ("is_err", "is_ok"),
52 ];
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, ref lhs, ref 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, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
106                 ExprKind::Binary(binop, ref lhs, ref 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(ref 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(cast_possible_truncation)]
122                 return Ok(Bool::Term(n as u8));
123             }
124             let negated = match e.node {
125                 ExprKind::Binary(binop, ref lhs, ref rhs) => {
126
127                     if !implements_ord(self.cx, lhs) {
128                         continue;
129                     }
130
131                     let mk_expr = |op| {
132                         Expr {
133                             id: DUMMY_NODE_ID,
134                             hir_id: DUMMY_HIR_ID,
135                             span: DUMMY_SP,
136                             attrs: ThinVec::new(),
137                             node: ExprKind::Binary(dummy_spanned(op), lhs.clone(), rhs.clone()),
138                         }
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(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(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, ref lhs, ref rhs) => {
183
184                 if !implements_ord(self.cx, lhs) {
185                     return None;
186                 }
187
188                 match binop.node {
189                     BinOpKind::Eq => Some(" != "),
190                     BinOpKind::Ne => Some(" == "),
191                     BinOpKind::Lt => Some(" >= "),
192                     BinOpKind::Gt => Some(" <= "),
193                     BinOpKind::Le => Some(" > "),
194                     BinOpKind::Ge => Some(" < "),
195                     _ => None,
196                 }.and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
197             },
198             ExprKind::MethodCall(ref path, _, ref 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                         return None;
203                 }
204                 METHODS_WITH_NEGATION
205                     .iter().cloned()
206                     .flat_map(|(a, b)| vec![(a, b), (b, a)])
207                     .find(|&(a, _)| a == path.ident.as_str())
208                     .and_then(|(_, neg_method)| Some(format!("{}.{}()", self.snip(&args[0])?, neg_method)))
209             },
210             _ => None,
211         }
212     }
213
214     fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
215         use quine_mc_cluskey::Bool::*;
216         match *suggestion {
217             True => {
218                 self.output.push_str("true");
219             },
220             False => {
221                 self.output.push_str("false");
222             },
223             Not(ref inner) => match **inner {
224                 And(_) | Or(_) => {
225                     self.output.push('!');
226                     self.output.push('(');
227                     self.recurse(inner);
228                     self.output.push(')');
229                 },
230                 Term(n) => {
231                     let terminal = self.terminals[n as usize];
232                     if let Some(str) = self.simplify_not(terminal) {
233                         self.simplified = true;
234                         self.output.push_str(&str)
235                     } else {
236                         self.output.push('!');
237                         let snip = self.snip(terminal)?;
238                         self.output.push_str(&snip);
239                     }
240                 },
241                 True | False | Not(_) => {
242                     self.output.push('!');
243                     self.recurse(inner)?;
244                 },
245             },
246             And(ref v) => {
247                 for (index, inner) in v.iter().enumerate() {
248                     if index > 0 {
249                         self.output.push_str(" && ");
250                     }
251                     if let Or(_) = *inner {
252                         self.output.push('(');
253                         self.recurse(inner);
254                         self.output.push(')');
255                     } else {
256                         self.recurse(inner);
257                     }
258                 }
259             },
260             Or(ref v) => {
261                 for (index, inner) in v.iter().enumerate() {
262                     if index > 0 {
263                         self.output.push_str(" || ");
264                     }
265                     self.recurse(inner);
266                 }
267             },
268             Term(n) => {
269                 let snip = self.snip(self.terminals[n as usize])?;
270                 self.output.push_str(&snip);
271             },
272         }
273         Some(())
274     }
275 }
276
277 // The boolean part of the return indicates whether some simplifications have been applied.
278 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> (String, bool) {
279     let mut suggest_context = SuggestContext {
280         terminals,
281         cx,
282         output: String::new(),
283         simplified: false,
284     };
285     suggest_context.recurse(suggestion);
286     (suggest_context.output, suggest_context.simplified)
287 }
288
289 fn simple_negate(b: Bool) -> Bool {
290     use quine_mc_cluskey::Bool::*;
291     match b {
292         True => False,
293         False => True,
294         t @ Term(_) => Not(Box::new(t)),
295         And(mut v) => {
296             for el in &mut v {
297                 *el = simple_negate(::std::mem::replace(el, True));
298             }
299             Or(v)
300         },
301         Or(mut v) => {
302             for el in &mut v {
303                 *el = simple_negate(::std::mem::replace(el, True));
304             }
305             And(v)
306         },
307         Not(inner) => *inner,
308     }
309 }
310
311 #[derive(Default)]
312 struct Stats {
313     terminals: [usize; 32],
314     negations: usize,
315     ops: usize,
316 }
317
318 fn terminal_stats(b: &Bool) -> Stats {
319     fn recurse(b: &Bool, stats: &mut Stats) {
320         match *b {
321             True | False => stats.ops += 1,
322             Not(ref inner) => {
323                 match **inner {
324                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
325                     _ => stats.negations += 1,
326                 }
327                 recurse(inner, stats);
328             },
329             And(ref v) | Or(ref v) => {
330                 stats.ops += v.len() - 1;
331                 for inner in v {
332                     recurse(inner, stats);
333                 }
334             },
335             Term(n) => stats.terminals[n as usize] += 1,
336         }
337     }
338     use quine_mc_cluskey::Bool::*;
339     let mut stats = Stats::default();
340     recurse(b, &mut stats);
341     stats
342 }
343
344 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
345     fn bool_expr(&self, e: &Expr) {
346         let mut h2q = Hir2Qmm {
347             terminals: Vec::new(),
348             cx: self.cx,
349         };
350         if let Ok(expr) = h2q.run(e) {
351             if h2q.terminals.len() > 8 {
352                 // QMC has exponentially slow behavior as the number of terminals increases
353                 // 8 is reasonable, it takes approximately 0.2 seconds.
354                 // See #825
355                 return;
356             }
357
358             let stats = terminal_stats(&expr);
359             let mut simplified = expr.simplify();
360             for simple in Bool::Not(Box::new(expr.clone())).simplify() {
361                 match simple {
362                     Bool::Not(_) | Bool::True | Bool::False => {},
363                     _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
364                 }
365                 let simple_negated = simple_negate(simple);
366                 if simplified.iter().any(|s| *s == simple_negated) {
367                     continue;
368                 }
369                 simplified.push(simple_negated);
370             }
371             let mut improvements = Vec::new();
372             'simplified: for suggestion in &simplified {
373                 let simplified_stats = terminal_stats(suggestion);
374                 let mut improvement = false;
375                 for i in 0..32 {
376                     // ignore any "simplifications" that end up requiring a terminal more often
377                     // than in the original expression
378                     if stats.terminals[i] < simplified_stats.terminals[i] {
379                         continue 'simplified;
380                     }
381                     if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
382                         span_lint_and_then(
383                             self.cx,
384                             LOGIC_BUG,
385                             e.span,
386                             "this boolean expression contains a logic bug",
387                             |db| {
388                                 db.span_help(
389                                     h2q.terminals[i].span,
390                                     "this expression can be optimized out by applying boolean operations to the \
391                                      outer expression",
392                                 );
393                                 db.span_suggestion(
394                                     e.span,
395                                     "it would look like the following",
396                                     suggest(self.cx, suggestion, &h2q.terminals).0,
397                                 );
398                             },
399                         );
400                         // don't also lint `NONMINIMAL_BOOL`
401                         return;
402                     }
403                     // if the number of occurrences of a terminal decreases or any of the stats
404                     // decreases while none increases
405                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
406                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
407                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
408                 }
409                 if improvement {
410                     improvements.push(suggestion);
411                 }
412             }
413             let nonminimal_bool_lint = |suggestions| {
414                 span_lint_and_then(
415                     self.cx,
416                     NONMINIMAL_BOOL,
417                     e.span,
418                     "this boolean expression can be simplified",
419                     |db| { db.span_suggestions(e.span, "try", suggestions); },
420                 );
421             };
422             if improvements.is_empty() {
423                 let suggest = suggest(self.cx, &expr, &h2q.terminals);
424                 if suggest.1 {
425                     nonminimal_bool_lint(vec![suggest.0])
426                 }
427             } else {
428                 nonminimal_bool_lint(
429                     improvements
430                         .into_iter()
431                         .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
432                         .collect()
433                 );
434             }
435         }
436     }
437 }
438
439 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
440     fn visit_expr(&mut self, e: &'tcx Expr) {
441         if in_macro(e.span) {
442             return;
443         }
444         match e.node {
445             ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => self.bool_expr(e),
446             ExprKind::Unary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
447                 self.bool_expr(e);
448             } else {
449                 walk_expr(self, e);
450             },
451             _ => walk_expr(self, e),
452         }
453     }
454     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
455         NestedVisitorMap::None
456     }
457 }
458
459
460 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
461     let ty = cx.tables.expr_ty(expr);
462     get_trait_def_id(cx, &paths::ORD)
463         .map_or(false, |id| implements_trait(cx, ty, id, &[]))
464 }