]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/booleans.rs
Move 'handle_method_call_in_not' code into 'suggest'
[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 utils::{in_macro, snippet_opt, span_lint_and_then, SpanlessEq};
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_lint! {
24     pub NONMINIMAL_BOOL,
25     Allow,
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_lint! {
42     pub LOGIC_BUG,
43     Warn,
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: 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                     let mk_expr = |op| {
126                         Expr {
127                             id: DUMMY_NODE_ID,
128                             hir_id: DUMMY_HIR_ID,
129                             span: DUMMY_SP,
130                             attrs: ThinVec::new(),
131                             node: ExprBinary(dummy_spanned(op), lhs.clone(), rhs.clone()),
132                         }
133                     };
134                     match binop.node {
135                         BiEq => mk_expr(BiNe),
136                         BiNe => mk_expr(BiEq),
137                         BiGt => mk_expr(BiLe),
138                         BiGe => mk_expr(BiLt),
139                         BiLt => mk_expr(BiGe),
140                         BiLe => mk_expr(BiGt),
141                         _ => continue,
142                     }
143                 },
144                 _ => continue,
145             };
146             if SpanlessEq::new(self.cx).ignore_fn().eq_expr(&negated, expr) {
147                 #[allow(cast_possible_truncation)]
148                 return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
149             }
150         }
151         let n = self.terminals.len();
152         self.terminals.push(e);
153         if n < 32 {
154             #[allow(cast_possible_truncation)]
155             Ok(Bool::Term(n as u8))
156         } else {
157             Err("too many literals".to_owned())
158         }
159     }
160 }
161
162 fn suggest(cx: &LateContext, suggestion: &Bool, terminals: &[&Expr]) -> String {
163     fn recurse(brackets: bool, cx: &LateContext, suggestion: &Bool, terminals: &[&Expr], mut s: String) -> String {
164         use quine_mc_cluskey::Bool::*;
165         let snip = |e: &Expr| snippet_opt(cx, e.span).expect("don't try to improve booleans created by macros");
166         match *suggestion {
167             True => {
168                 s.push_str("true");
169                 s
170             },
171             False => {
172                 s.push_str("false");
173                 s
174             },
175             Not(ref inner) => match **inner {
176                 And(_) | Or(_) => {
177                     s.push('!');
178                     recurse(true, cx, inner, terminals, s)
179                 },
180                 Term(n) => match terminals[n as usize].node {
181                     ExprBinary(binop, ref lhs, ref rhs) => {
182                         let op = match binop.node {
183                             BiEq => " != ",
184                             BiNe => " == ",
185                             BiLt => " >= ",
186                             BiGt => " <= ",
187                             BiLe => " > ",
188                             BiGe => " < ",
189                             _ => {
190                                 s.push('!');
191                                 return recurse(true, cx, inner, terminals, s);
192                             },
193                         };
194                         s.push_str(&snip(lhs));
195                         s.push_str(op);
196                         s.push_str(&snip(rhs));
197                         s
198                     },
199                     ExprMethodCall(ref path, _, ref args) if args.len() == 1 => {
200                         let negation = METHODS_WITH_NEGATION
201                             .iter().cloned()
202                             .flat_map(|(a, b)| vec![(a, b), (b, a)])
203                             .find(|&(a, _)| a == path.name.as_str());
204                         if let Some((_, negation_method)) = negation {
205                             s.push_str(&snip(&args[0]));
206                             s.push('.');
207                             s.push_str(negation_method);
208                             s.push_str("()");
209                             s
210                         } else {
211                             s.push('!');
212                             recurse(false, cx, inner, terminals, s)
213                         }
214                     },
215                     _ => {
216                         s.push('!');
217                         recurse(false, cx, inner, terminals, s)
218                     },
219                 },
220                 _ => {
221                     s.push('!');
222                     recurse(false, cx, inner, terminals, s)
223                 },
224             },
225             And(ref v) => {
226                 if brackets {
227                     s.push('(');
228                 }
229                 if let Or(_) = v[0] {
230                     s = recurse(true, cx, &v[0], terminals, s);
231                 } else {
232                     s = recurse(false, cx, &v[0], terminals, s);
233                 }
234                 for inner in &v[1..] {
235                     s.push_str(" && ");
236                     if let Or(_) = *inner {
237                         s = recurse(true, cx, inner, terminals, s);
238                     } else {
239                         s = recurse(false, cx, inner, terminals, s);
240                     }
241                 }
242                 if brackets {
243                     s.push(')');
244                 }
245                 s
246             },
247             Or(ref v) => {
248                 if brackets {
249                     s.push('(');
250                 }
251                 s = recurse(false, cx, &v[0], terminals, s);
252                 for inner in &v[1..] {
253                     s.push_str(" || ");
254                     s = recurse(false, cx, inner, terminals, s);
255                 }
256                 if brackets {
257                     s.push(')');
258                 }
259                 s
260             },
261             Term(n) => {
262                 if brackets {
263                     if let ExprBinary(..) = terminals[n as usize].node {
264                         s.push('(');
265                     }
266                 }
267                 s.push_str(&snip(terminals[n as usize]));
268                 if brackets {
269                     if let ExprBinary(..) = terminals[n as usize].node {
270                         s.push(')');
271                     }
272                 }
273                 s
274             },
275         }
276     }
277     recurse(false, cx, suggestion, terminals, String::new())
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(ref 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(ref v) | Or(ref 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),
388                                 );
389                             },
390                         );
391                         // don't also lint `NONMINIMAL_BOOL`
392                         return;
393                     }
394                     // if the number of occurrences of a terminal decreases or any of the stats
395                     // decreases while none increases
396                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
397                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
398                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
399                 }
400                 if improvement {
401                     improvements.push(suggestion);
402                 }
403             }
404             if !improvements.is_empty() {
405                 span_lint_and_then(
406                     self.cx,
407                     NONMINIMAL_BOOL,
408                     e.span,
409                     "this boolean expression can be simplified",
410                     |db| {
411                         db.span_suggestions(
412                             e.span,
413                             "try",
414                             improvements
415                                 .into_iter()
416                                 .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
417                                 .collect(),
418                         );
419                     },
420                 );
421             }
422         }
423     }
424 }
425
426 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
427     fn visit_expr(&mut self, e: &'tcx Expr) {
428         if in_macro(e.span) {
429             return;
430         }
431         match e.node {
432             ExprBinary(binop, _, _) if binop.node == BiOr || binop.node == BiAnd => self.bool_expr(e),
433             ExprUnary(UnNot, ref inner) => if self.cx.tables.node_types()[inner.hir_id].is_bool() {
434                 self.bool_expr(e);
435             } else {
436                 walk_expr(self, e);
437             },
438             _ => walk_expr(self, e),
439         }
440     }
441     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
442         NestedVisitorMap::None
443     }
444 }