]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Merge pull request #2880 from mati865/rustup_hir
[rust.git] / clippy_lints / src / booleans.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::hir::*;
3 use rustc::hir::intravisit::*;
4 use syntax::ast::{LitKind, NodeId, DUMMY_NODE_ID};
5 use syntax::codemap::{dummy_spanned, Span, DUMMY_SP};
6 use syntax::util::ThinVec;
7 use crate::utils::{in_macro, paths, match_type, snippet_opt, span_lint_and_then, SpanlessEq, get_trait_def_id, implements_trait};
8
9 /// **What it does:** Checks for boolean expressions that can be written more
10 /// concisely.
11 ///
12 /// **Why is this bad?** Readability of boolean expressions suffers from
13 /// unnecessary duplication.
14 ///
15 /// **Known problems:** Ignores short circuiting behavior of `||` and
16 /// `&&`. Ignores `|`, `&` and `^`.
17 ///
18 /// **Example:**
19 /// ```rust
20 /// if a && true  // should be: if a
21 /// if !(a == b)  // should be: if a != b
22 /// ```
23 declare_clippy_lint! {
24     pub NONMINIMAL_BOOL,
25     complexity,
26     "boolean expressions that can be written more concisely"
27 }
28
29 /// **What it does:** Checks for boolean expressions that contain terminals that
30 /// can be eliminated.
31 ///
32 /// **Why is this bad?** This is most likely a logic bug.
33 ///
34 /// **Known problems:** Ignores short circuiting behavior.
35 ///
36 /// **Example:**
37 /// ```rust
38 /// if a && b || a { ... }
39 /// ```
40 /// The `b` is unnecessary, the expression is equivalent to `if a`.
41 declare_clippy_lint! {
42     pub LOGIC_BUG,
43     correctness,
44     "boolean expressions that contain terminals which can be eliminated"
45 }
46
47 // For each pairs, both orders are considered.
48 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [
49     ("is_some", "is_none"),
50     ("is_err", "is_ok"),
51 ];
52
53 #[derive(Copy, Clone)]
54 pub struct NonminimalBool;
55
56 impl LintPass for NonminimalBool {
57     fn get_lints(&self) -> LintArray {
58         lint_array!(NONMINIMAL_BOOL, LOGIC_BUG)
59     }
60 }
61
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonminimalBool {
63     fn check_fn(
64         &mut self,
65         cx: &LateContext<'a, 'tcx>,
66         _: intravisit::FnKind<'tcx>,
67         _: &'tcx FnDecl,
68         body: &'tcx Body,
69         _: Span,
70         _: NodeId,
71     ) {
72         NonminimalBoolVisitor { cx }.visit_body(body)
73     }
74 }
75
76 struct NonminimalBoolVisitor<'a, 'tcx: 'a> {
77     cx: &'a LateContext<'a, 'tcx>,
78 }
79
80 use quine_mc_cluskey::Bool;
81 struct Hir2Qmm<'a, 'tcx: 'a, 'v> {
82     terminals: Vec<&'v Expr>,
83     cx: &'a LateContext<'a, 'tcx>,
84 }
85
86 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
87     fn extract(&mut self, op: BinOp_, a: &[&'v Expr], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
88         for a in a {
89             if let ExprBinary(binop, ref lhs, ref rhs) = a.node {
90                 if binop.node == op {
91                     v = self.extract(op, &[lhs, rhs], v)?;
92                     continue;
93                 }
94             }
95             v.push(self.run(a)?);
96         }
97         Ok(v)
98     }
99
100     fn run(&mut self, e: &'v Expr) -> Result<Bool, String> {
101         // prevent folding of `cfg!` macros and the like
102         if !in_macro(e.span) {
103             match e.node {
104                 ExprUnary(UnNot, ref inner) => return Ok(Bool::Not(box self.run(inner)?)),
105                 ExprBinary(binop, ref lhs, ref rhs) => match binop.node {
106                     BiOr => return Ok(Bool::Or(self.extract(BiOr, &[lhs, rhs], Vec::new())?)),
107                     BiAnd => return Ok(Bool::And(self.extract(BiAnd, &[lhs, rhs], Vec::new())?)),
108                     _ => (),
109                 },
110                 ExprLit(ref lit) => match lit.node {
111                     LitKind::Bool(true) => return Ok(Bool::True),
112                     LitKind::Bool(false) => return Ok(Bool::False),
113                     _ => (),
114                 },
115                 _ => (),
116             }
117         }
118         for (n, expr) in self.terminals.iter().enumerate() {
119             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(e, expr) {
120                 #[allow(cast_possible_truncation)]
121                 return Ok(Bool::Term(n as u8));
122             }
123             let negated = match e.node {
124                 ExprBinary(binop, ref lhs, ref rhs) => {
125  
126                     if !implements_ord(self.cx, lhs) {
127                         continue;
128                     }
129
130                     let mk_expr = |op| {
131                         Expr {
132                             id: DUMMY_NODE_ID,
133                             hir_id: DUMMY_HIR_ID,
134                             span: DUMMY_SP,
135                             attrs: ThinVec::new(),
136                             node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
137                         }
138                     };
139                     match binop.node {
140                         BiEq => mk_expr(BiNe),
141                         BiNe => mk_expr(BiEq),
142                         BiGt => mk_expr(BiLe),
143                         BiGe => mk_expr(BiLt),
144                         BiLt => mk_expr(BiGe),
145                         BiLe => mk_expr(BiGt),
146                         _ => continue,
147                     }
148                 },
149                 _ => continue,
150             };
151             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
152                 #[allow(cast_possible_truncation)]
153                 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
154             }
155         }
156         let n = self.terminals.len();
157         self.terminals.push(e);
158         if n < 32 {
159             #[allow(cast_possible_truncation)]
160             Ok(Bool::Term(n as u8))
161         } else {
162             Err("too many literals".to_owned())
163         }
164     }
165 }
166
167 struct SuggestContext<'a, 'tcx: 'a, 'v> {
168     terminals: &'v [&'v Expr],
169     cx: &'a LateContext<'a, 'tcx>,
170     output: String,
171     simplified: bool,
172 }
173
174 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
175     fn snip(&self, e: &Expr) -> Option<String> {
176         snippet_opt(self.cx, e.span)
177     }
178
179     fn simplify_not(&self, expr: &Expr) -> Option<String> {
180         match expr.node {
181             ExprBinary(binop, ref lhs, ref rhs) => {
182
183                 if !implements_ord(self.cx, lhs) {
184                     return None;
185                 }
186
187                 match binop.node {
188                     BiEq => Some(" != "),
189                     BiNe => Some(" == "),
190                     BiLt => Some(" >= "),
191                     BiGt => Some(" <= "),
192                     BiLe => Some(" > "),
193                     BiGe => Some(" < "),
194                     _ => None,
195                 }.and_then(|op| Some(format!("{}{}{}", self.snip(lhs)?, op, self.snip(rhs)?)))
196             },
197             ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
198                 let type_of_receiver = self.cx.tables.expr_ty(&args[0]);
199                 if !match_type(self.cx, type_of_receiver, &paths::OPTION) &&
200                     !match_type(self.cx, type_of_receiver, &paths::RESULT) {
201                         return None;
202                 }
203                 METHODS_WITH_NEGATION
204                     .iter().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(ref 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(ref 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(ref 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(ref 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(ref v) | Or(ref 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(
393                                     e.span,
394                                     "it would look like the following",
395                                     suggest(self.cx, suggestion, &h2q.terminals).0,
396                                 );
397                             },
398                         );
399                         // don't also lint `NONMINIMAL_BOOL`
400                         return;
401                     }
402                     // if the number of occurrences of a terminal decreases or any of the stats
403                     // decreases while none increases
404                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
405                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
406                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
407                 }
408                 if improvement {
409                     improvements.push(suggestion);
410                 }
411             }
412             let nonminimal_bool_lint = |suggestions| {
413                 span_lint_and_then(
414                     self.cx,
415                     NONMINIMAL_BOOL,
416                     e.span,
417                     "this boolean expression can be simplified",
418                     |db| { db.span_suggestions(e.span, "try", suggestions); },
419                 );
420             };
421             if improvements.is_empty() {
422                 let suggest = suggest(self.cx, &expr, &h2q.terminals);
423                 if suggest.1 {
424                     nonminimal_bool_lint(vec![suggest.0])
425                 }
426             } else {
427                 nonminimal_bool_lint(
428                     improvements
429                         .into_iter()
430                         .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals).0)
431                         .collect()
432                 );
433             }
434         }
435     }
436 }
437
438 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
439     fn visit_expr(&mut self, e: &'tcx Expr) {
440         if in_macro(e.span) {
441             return;
442         }
443         match e.node {
444             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
445             ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
446                 self.bool_expr(e);
447             } else {
448                 walk_expr(self, e);
449             },
450             _ => walk_expr(self, e),
451         }
452     }
453     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
454         NestedVisitorMap::None
455     }
456 }
457
458
459 fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr) -> bool {
460     let ty = cx.tables.expr_ty(expr);
461     get_trait_def_id(cx, &paths::ORD)
462         .map_or(false, |id| implements_trait(cx, ty, id, &[]))
463 }