]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/booleans.rs
Fix invalid float literal suggestions when recovering an integer
[rust.git] / src / tools / clippy / clippy_lints / src / booleans.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
2 use clippy_utils::eq_expr_value;
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::{walk_expr, FnKind, Visitor};
9 use rustc_hir::{BinOpKind, Body, Expr, ExprKind, FnDecl, HirId, UnOp};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Span;
13 use rustc_span::sym;
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for boolean expressions that can be written more
18     /// concisely.
19     ///
20     /// ### Why is this bad?
21     /// Readability of boolean expressions suffers from
22     /// unnecessary duplication.
23     ///
24     /// ### Known problems
25     /// Ignores short circuiting behavior of `||` and
26     /// `&&`. Ignores `|`, `&` and `^`.
27     ///
28     /// ### Example
29     /// ```ignore
30     /// if a && true {}
31     /// if !(a == b) {}
32     /// ```
33     ///
34     /// Use instead:
35     /// ```rust,ignore
36     /// if a {}
37     /// if a != b {}
38     /// ```
39     #[clippy::version = "pre 1.29.0"]
40     pub NONMINIMAL_BOOL,
41     complexity,
42     "boolean expressions that can be written more concisely"
43 }
44
45 declare_clippy_lint! {
46     /// ### What it does
47     /// Checks for boolean expressions that contain terminals that
48     /// can be eliminated.
49     ///
50     /// ### Why is this bad?
51     /// This is most likely a logic bug.
52     ///
53     /// ### Known problems
54     /// Ignores short circuiting behavior.
55     ///
56     /// ### Example
57     /// ```rust,ignore
58     /// // The `b` is unnecessary, the expression is equivalent to `if a`.
59     /// if a && b || a { ... }
60     /// ```
61     ///
62     /// Use instead:
63     /// ```rust,ignore
64     /// if a {}
65     /// ```
66     #[clippy::version = "pre 1.29.0"]
67     pub OVERLY_COMPLEX_BOOL_EXPR,
68     correctness,
69     "boolean expressions that contain terminals which can be eliminated"
70 }
71
72 // For each pairs, both orders are considered.
73 const METHODS_WITH_NEGATION: [(&str, &str); 2] = [("is_some", "is_none"), ("is_err", "is_ok")];
74
75 declare_lint_pass!(NonminimalBool => [NONMINIMAL_BOOL, OVERLY_COMPLEX_BOOL_EXPR]);
76
77 impl<'tcx> LateLintPass<'tcx> for NonminimalBool {
78     fn check_fn(
79         &mut self,
80         cx: &LateContext<'tcx>,
81         _: FnKind<'tcx>,
82         _: &'tcx FnDecl<'_>,
83         body: &'tcx Body<'_>,
84         _: Span,
85         _: HirId,
86     ) {
87         NonminimalBoolVisitor { cx }.visit_body(body);
88     }
89 }
90
91 struct NonminimalBoolVisitor<'a, 'tcx> {
92     cx: &'a LateContext<'tcx>,
93 }
94
95 use quine_mc_cluskey::Bool;
96 struct Hir2Qmm<'a, 'tcx, 'v> {
97     terminals: Vec<&'v Expr<'v>>,
98     cx: &'a LateContext<'tcx>,
99 }
100
101 impl<'a, 'tcx, 'v> Hir2Qmm<'a, 'tcx, 'v> {
102     fn extract(&mut self, op: BinOpKind, a: &[&'v Expr<'_>], mut v: Vec<Bool>) -> Result<Vec<Bool>, String> {
103         for a in a {
104             if let ExprKind::Binary(binop, lhs, rhs) = &a.kind {
105                 if binop.node == op {
106                     v = self.extract(op, &[lhs, rhs], v)?;
107                     continue;
108                 }
109             }
110             v.push(self.run(a)?);
111         }
112         Ok(v)
113     }
114
115     fn run(&mut self, e: &'v Expr<'_>) -> Result<Bool, String> {
116         fn negate(bin_op_kind: BinOpKind) -> Option<BinOpKind> {
117             match bin_op_kind {
118                 BinOpKind::Eq => Some(BinOpKind::Ne),
119                 BinOpKind::Ne => Some(BinOpKind::Eq),
120                 BinOpKind::Gt => Some(BinOpKind::Le),
121                 BinOpKind::Ge => Some(BinOpKind::Lt),
122                 BinOpKind::Lt => Some(BinOpKind::Ge),
123                 BinOpKind::Le => Some(BinOpKind::Gt),
124                 _ => None,
125             }
126         }
127
128         // prevent folding of `cfg!` macros and the like
129         if !e.span.from_expansion() {
130             match &e.kind {
131                 ExprKind::Unary(UnOp::Not, inner) => return Ok(Bool::Not(Box::new(self.run(inner)?))),
132                 ExprKind::Binary(binop, lhs, rhs) => match &binop.node {
133                     BinOpKind::Or => {
134                         return Ok(Bool::Or(self.extract(BinOpKind::Or, &[lhs, rhs], Vec::new())?));
135                     },
136                     BinOpKind::And => {
137                         return Ok(Bool::And(self.extract(BinOpKind::And, &[lhs, rhs], Vec::new())?));
138                     },
139                     _ => (),
140                 },
141                 ExprKind::Lit(lit) => match lit.node {
142                     LitKind::Bool(true) => return Ok(Bool::True),
143                     LitKind::Bool(false) => return Ok(Bool::False),
144                     _ => (),
145                 },
146                 _ => (),
147             }
148         }
149         for (n, expr) in self.terminals.iter().enumerate() {
150             if eq_expr_value(self.cx, e, expr) {
151                 #[expect(clippy::cast_possible_truncation)]
152                 return Ok(Bool::Term(n as u8));
153             }
154
155             if_chain! {
156                 if let ExprKind::Binary(e_binop, e_lhs, e_rhs) = &e.kind;
157                 if implements_ord(self.cx, e_lhs);
158                 if let ExprKind::Binary(expr_binop, expr_lhs, expr_rhs) = &expr.kind;
159                 if negate(e_binop.node) == Some(expr_binop.node);
160                 if eq_expr_value(self.cx, e_lhs, expr_lhs);
161                 if eq_expr_value(self.cx, e_rhs, expr_rhs);
162                 then {
163                     #[expect(clippy::cast_possible_truncation)]
164                     return Ok(Bool::Not(Box::new(Bool::Term(n as u8))));
165                 }
166             }
167         }
168         let n = self.terminals.len();
169         self.terminals.push(e);
170         if n < 32 {
171             #[expect(clippy::cast_possible_truncation)]
172             Ok(Bool::Term(n as u8))
173         } else {
174             Err("too many literals".to_owned())
175         }
176     }
177 }
178
179 struct SuggestContext<'a, 'tcx, 'v> {
180     terminals: &'v [&'v Expr<'v>],
181     cx: &'a LateContext<'tcx>,
182     output: String,
183 }
184
185 impl<'a, 'tcx, 'v> SuggestContext<'a, 'tcx, 'v> {
186     fn recurse(&mut self, suggestion: &Bool) -> Option<()> {
187         use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
188         match suggestion {
189             True => {
190                 self.output.push_str("true");
191             },
192             False => {
193                 self.output.push_str("false");
194             },
195             Not(inner) => match **inner {
196                 And(_) | Or(_) => {
197                     self.output.push('!');
198                     self.output.push('(');
199                     self.recurse(inner);
200                     self.output.push(')');
201                 },
202                 Term(n) => {
203                     let terminal = self.terminals[n as usize];
204                     if let Some(str) = simplify_not(self.cx, terminal) {
205                         self.output.push_str(&str);
206                     } else {
207                         self.output.push('!');
208                         let snip = snippet_opt(self.cx, terminal.span)?;
209                         self.output.push_str(&snip);
210                     }
211                 },
212                 True | False | Not(_) => {
213                     self.output.push('!');
214                     self.recurse(inner)?;
215                 },
216             },
217             And(v) => {
218                 for (index, inner) in v.iter().enumerate() {
219                     if index > 0 {
220                         self.output.push_str(" && ");
221                     }
222                     if let Or(_) = *inner {
223                         self.output.push('(');
224                         self.recurse(inner);
225                         self.output.push(')');
226                     } else {
227                         self.recurse(inner);
228                     }
229                 }
230             },
231             Or(v) => {
232                 for (index, inner) in v.iter().rev().enumerate() {
233                     if index > 0 {
234                         self.output.push_str(" || ");
235                     }
236                     self.recurse(inner);
237                 }
238             },
239             &Term(n) => {
240                 let snip = snippet_opt(self.cx, self.terminals[n as usize].span.source_callsite())?;
241                 self.output.push_str(&snip);
242             },
243         }
244         Some(())
245     }
246 }
247
248 fn simplify_not(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
249     match &expr.kind {
250         ExprKind::Binary(binop, lhs, rhs) => {
251             if !implements_ord(cx, lhs) {
252                 return None;
253             }
254
255             match binop.node {
256                 BinOpKind::Eq => Some(" != "),
257                 BinOpKind::Ne => Some(" == "),
258                 BinOpKind::Lt => Some(" >= "),
259                 BinOpKind::Gt => Some(" <= "),
260                 BinOpKind::Le => Some(" > "),
261                 BinOpKind::Ge => Some(" < "),
262                 _ => None,
263             }
264             .and_then(|op| {
265                 Some(format!(
266                     "{}{op}{}",
267                     snippet_opt(cx, lhs.span)?,
268                     snippet_opt(cx, rhs.span)?
269                 ))
270             })
271         },
272         ExprKind::MethodCall(path, receiver, [], _) => {
273             let type_of_receiver = cx.typeck_results().expr_ty(receiver);
274             if !is_type_diagnostic_item(cx, type_of_receiver, sym::Option)
275                 && !is_type_diagnostic_item(cx, type_of_receiver, sym::Result)
276             {
277                 return None;
278             }
279             METHODS_WITH_NEGATION
280                 .iter()
281                 .copied()
282                 .flat_map(|(a, b)| vec![(a, b), (b, a)])
283                 .find(|&(a, _)| {
284                     let path: &str = path.ident.name.as_str();
285                     a == path
286                 })
287                 .and_then(|(_, neg_method)| Some(format!("{}.{neg_method}()", snippet_opt(cx, receiver.span)?)))
288         },
289         _ => None,
290     }
291 }
292
293 fn suggest(cx: &LateContext<'_>, suggestion: &Bool, terminals: &[&Expr<'_>]) -> String {
294     let mut suggest_context = SuggestContext {
295         terminals,
296         cx,
297         output: String::new(),
298     };
299     suggest_context.recurse(suggestion);
300     suggest_context.output
301 }
302
303 fn simple_negate(b: Bool) -> Bool {
304     use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
305     match b {
306         True => False,
307         False => True,
308         t @ Term(_) => Not(Box::new(t)),
309         And(mut v) => {
310             for el in &mut v {
311                 *el = simple_negate(::std::mem::replace(el, True));
312             }
313             Or(v)
314         },
315         Or(mut v) => {
316             for el in &mut v {
317                 *el = simple_negate(::std::mem::replace(el, True));
318             }
319             And(v)
320         },
321         Not(inner) => *inner,
322     }
323 }
324
325 #[derive(Default)]
326 struct Stats {
327     terminals: [usize; 32],
328     negations: usize,
329     ops: usize,
330 }
331
332 fn terminal_stats(b: &Bool) -> Stats {
333     fn recurse(b: &Bool, stats: &mut Stats) {
334         match b {
335             True | False => stats.ops += 1,
336             Not(inner) => {
337                 match **inner {
338                     And(_) | Or(_) => stats.ops += 1, // brackets are also operations
339                     _ => stats.negations += 1,
340                 }
341                 recurse(inner, stats);
342             },
343             And(v) | Or(v) => {
344                 stats.ops += v.len() - 1;
345                 for inner in v {
346                     recurse(inner, stats);
347                 }
348             },
349             &Term(n) => stats.terminals[n as usize] += 1,
350         }
351     }
352     use quine_mc_cluskey::Bool::{And, False, Not, Or, Term, True};
353     let mut stats = Stats::default();
354     recurse(b, &mut stats);
355     stats
356 }
357
358 impl<'a, 'tcx> NonminimalBoolVisitor<'a, 'tcx> {
359     fn bool_expr(&self, e: &'tcx Expr<'_>) {
360         let mut h2q = Hir2Qmm {
361             terminals: Vec::new(),
362             cx: self.cx,
363         };
364         if let Ok(expr) = h2q.run(e) {
365             if h2q.terminals.len() > 8 {
366                 // QMC has exponentially slow behavior as the number of terminals increases
367                 // 8 is reasonable, it takes approximately 0.2 seconds.
368                 // See #825
369                 return;
370             }
371
372             let stats = terminal_stats(&expr);
373             let mut simplified = expr.simplify();
374             for simple in Bool::Not(Box::new(expr)).simplify() {
375                 match simple {
376                     Bool::Not(_) | Bool::True | Bool::False => {},
377                     _ => simplified.push(Bool::Not(Box::new(simple.clone()))),
378                 }
379                 let simple_negated = simple_negate(simple);
380                 if simplified.iter().any(|s| *s == simple_negated) {
381                     continue;
382                 }
383                 simplified.push(simple_negated);
384             }
385             let mut improvements = Vec::with_capacity(simplified.len());
386             'simplified: for suggestion in &simplified {
387                 let simplified_stats = terminal_stats(suggestion);
388                 let mut improvement = false;
389                 for i in 0..32 {
390                     // ignore any "simplifications" that end up requiring a terminal more often
391                     // than in the original expression
392                     if stats.terminals[i] < simplified_stats.terminals[i] {
393                         continue 'simplified;
394                     }
395                     if stats.terminals[i] != 0 && simplified_stats.terminals[i] == 0 {
396                         span_lint_hir_and_then(
397                             self.cx,
398                             OVERLY_COMPLEX_BOOL_EXPR,
399                             e.hir_id,
400                             e.span,
401                             "this boolean expression contains a logic bug",
402                             |diag| {
403                                 diag.span_help(
404                                     h2q.terminals[i].span,
405                                     "this expression can be optimized out by applying boolean operations to the \
406                                      outer expression",
407                                 );
408                                 diag.span_suggestion(
409                                     e.span,
410                                     "it would look like the following",
411                                     suggest(self.cx, suggestion, &h2q.terminals),
412                                     // nonminimal_bool can produce minimal but
413                                     // not human readable expressions (#3141)
414                                     Applicability::Unspecified,
415                                 );
416                             },
417                         );
418                         // don't also lint `NONMINIMAL_BOOL`
419                         return;
420                     }
421                     // if the number of occurrences of a terminal decreases or any of the stats
422                     // decreases while none increases
423                     improvement |= (stats.terminals[i] > simplified_stats.terminals[i])
424                         || (stats.negations > simplified_stats.negations && stats.ops == simplified_stats.ops)
425                         || (stats.ops > simplified_stats.ops && stats.negations == simplified_stats.negations);
426                 }
427                 if improvement {
428                     improvements.push(suggestion);
429                 }
430             }
431             let nonminimal_bool_lint = |suggestions: Vec<_>| {
432                 span_lint_hir_and_then(
433                     self.cx,
434                     NONMINIMAL_BOOL,
435                     e.hir_id,
436                     e.span,
437                     "this boolean expression can be simplified",
438                     |diag| {
439                         diag.span_suggestions(
440                             e.span,
441                             "try",
442                             suggestions.into_iter(),
443                             // nonminimal_bool can produce minimal but
444                             // not human readable expressions (#3141)
445                             Applicability::Unspecified,
446                         );
447                     },
448                 );
449             };
450             if improvements.is_empty() {
451                 let mut visitor = NotSimplificationVisitor { cx: self.cx };
452                 visitor.visit_expr(e);
453             } else {
454                 nonminimal_bool_lint(
455                     improvements
456                         .into_iter()
457                         .map(|suggestion| suggest(self.cx, suggestion, &h2q.terminals))
458                         .collect(),
459                 );
460             }
461         }
462     }
463 }
464
465 impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> {
466     fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
467         if !e.span.from_expansion() {
468             match &e.kind {
469                 ExprKind::Binary(binop, _, _) if binop.node == BinOpKind::Or || binop.node == BinOpKind::And => {
470                     self.bool_expr(e);
471                 },
472                 ExprKind::Unary(UnOp::Not, inner) => {
473                     if self.cx.typeck_results().node_types()[inner.hir_id].is_bool() {
474                         self.bool_expr(e);
475                     }
476                 },
477                 _ => {},
478             }
479         }
480         walk_expr(self, e);
481     }
482 }
483
484 fn implements_ord(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
485     let ty = cx.typeck_results().expr_ty(expr);
486     cx.tcx
487         .get_diagnostic_item(sym::Ord)
488         .map_or(false, |id| implements_trait(cx, ty, id, &[]))
489 }
490
491 struct NotSimplificationVisitor<'a, 'tcx> {
492     cx: &'a LateContext<'tcx>,
493 }
494
495 impl<'a, 'tcx> Visitor<'tcx> for NotSimplificationVisitor<'a, 'tcx> {
496     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
497         if let ExprKind::Unary(UnOp::Not, inner) = &expr.kind {
498             if let Some(suggestion) = simplify_not(self.cx, inner) {
499                 span_lint_and_sugg(
500                     self.cx,
501                     NONMINIMAL_BOOL,
502                     expr.span,
503                     "this boolean expression can be simplified",
504                     "try",
505                     suggestion,
506                     Applicability::MachineApplicable,
507                 );
508             }
509         }
510
511         walk_expr(self, expr);
512     }
513 }