]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bool_to_int_with_if.rs
Rollup merge of #102846 - zertosh:update-syn, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / bool_to_int_with_if.rs
1 use rustc_ast::LitKind;
2 use rustc_hir::{Block, ExprKind};
3 use rustc_lint::{LateContext, LateLintPass};
4 use rustc_session::{declare_lint_pass, declare_tool_lint};
5
6 use clippy_utils::{diagnostics::span_lint_and_then, is_else_clause, is_integer_literal, sugg::Sugg};
7 use rustc_errors::Applicability;
8
9 declare_clippy_lint! {
10     /// ### What it does
11     /// Instead of using an if statement to convert a bool to an int,
12     /// this lint suggests using a `from()` function or an `as` coercion.
13     ///
14     /// ### Why is this bad?
15     /// Coercion or `from()` is idiomatic way to convert bool to a number.
16     /// Both methods are guaranteed to return 1 for true, and 0 for false.
17     ///
18     /// See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E
19     ///
20     /// ### Example
21     /// ```rust
22     /// # let condition = false;
23     /// if condition {
24     ///     1_i64
25     /// } else {
26     ///     0
27     /// };
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// # let condition = false;
32     /// i64::from(condition);
33     /// ```
34     /// or
35     /// ```rust
36     /// # let condition = false;
37     /// condition as i64;
38     /// ```
39     #[clippy::version = "1.65.0"]
40     pub BOOL_TO_INT_WITH_IF,
41     style,
42     "using if to convert bool to int"
43 }
44 declare_lint_pass!(BoolToIntWithIf => [BOOL_TO_INT_WITH_IF]);
45
46 impl<'tcx> LateLintPass<'tcx> for BoolToIntWithIf {
47     fn check_expr(&mut self, ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) {
48         if !expr.span.from_expansion() {
49             check_if_else(ctx, expr);
50         }
51     }
52 }
53
54 fn check_if_else<'tcx>(ctx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) {
55     if let ExprKind::If(check, then, Some(else_)) = expr.kind
56         && let Some(then_lit) = int_literal(then)
57         && let Some(else_lit) = int_literal(else_)
58     {
59         let inverted = if is_integer_literal(then_lit, 1) && is_integer_literal(else_lit, 0) {
60             false
61         } else if is_integer_literal(then_lit, 0) && is_integer_literal(else_lit, 1) {
62             true
63         } else {
64             // Expression isn't boolean, exit
65             return;
66         };
67         let mut applicability = Applicability::MachineApplicable;
68         let snippet = {
69             let mut sugg = Sugg::hir_with_applicability(ctx, check, "..", &mut applicability);
70             if inverted {
71                 sugg = !sugg;
72             }
73             sugg
74         };
75
76         let ty = ctx.typeck_results().expr_ty(then_lit); // then and else must be of same type
77
78         let suggestion = {
79             let wrap_in_curly = is_else_clause(ctx.tcx, expr);
80             let mut s = Sugg::NonParen(format!("{ty}::from({snippet})").into());
81             if wrap_in_curly {
82                 s = s.blockify();
83             }
84             s
85         }; // when used in else clause if statement should be wrapped in curly braces
86
87         let into_snippet = snippet.clone().maybe_par();
88         let as_snippet = snippet.as_ty(ty);
89
90         span_lint_and_then(ctx,
91             BOOL_TO_INT_WITH_IF,
92             expr.span,
93             "boolean to int conversion using if",
94             |diag| {
95             diag.span_suggestion(
96                 expr.span,
97                 "replace with from",
98                 suggestion,
99                 applicability,
100             );
101             diag.note(format!("`{as_snippet}` or `{into_snippet}.into()` can also be valid options"));
102         });
103     };
104 }
105
106 // If block contains only a int literal expression, return literal expression
107 fn int_literal<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>) -> Option<&'tcx rustc_hir::Expr<'tcx>> {
108     if let ExprKind::Block(block, _) = expr.kind
109         && let Block {
110             stmts: [],       // Shouldn't lint if statements with side effects
111             expr: Some(expr),
112             ..
113         } = block
114         && let ExprKind::Lit(lit) = &expr.kind
115         && let LitKind::Int(_, _) = lit.node
116     {
117         Some(expr)
118     } else {
119         None
120     }
121 }