]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bool_to_int_with_if.rs
Rollup merge of #101266 - LuisCardosoOliveira:translation-rustcsession-pt3, r=davidtwco
[rust.git] / src / tools / clippy / clippy_lints / src / bool_to_int_with_if.rs
1 use rustc_ast::{ExprPrecedence, 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, source::snippet_block_with_applicability};
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         && check_int_literal_equals_val(then_lit, 1)
59         && check_int_literal_equals_val(else_lit, 0)
60     {
61         let mut applicability = Applicability::MachineApplicable;
62         let snippet = snippet_block_with_applicability(ctx, check.span, "..", None, &mut applicability);
63         let snippet_with_braces = {
64             let need_parens = should_have_parentheses(check);
65             let (left_paren, right_paren) = if need_parens {("(", ")")} else {("", "")};
66             format!("{left_paren}{snippet}{right_paren}")
67         };
68
69         let ty = ctx.typeck_results().expr_ty(then_lit); // then and else must be of same type
70
71         let suggestion = {
72             let wrap_in_curly = is_else_clause(ctx.tcx, expr);
73             let (left_curly, right_curly) = if wrap_in_curly {("{", "}")} else {("", "")};
74             format!(
75                 "{left_curly}{ty}::from({snippet}){right_curly}"
76             )
77         }; // when used in else clause if statement should be wrapped in curly braces
78
79         span_lint_and_then(ctx,
80             BOOL_TO_INT_WITH_IF,
81             expr.span,
82             "boolean to int conversion using if",
83             |diag| {
84             diag.span_suggestion(
85                 expr.span,
86                 "replace with from",
87                 suggestion,
88                 applicability,
89             );
90             diag.note(format!("`{snippet_with_braces} as {ty}` or `{snippet_with_braces}.into()` can also be valid options"));
91         });
92     };
93 }
94
95 // If block contains only a int literal expression, return literal expression
96 fn int_literal<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>) -> Option<&'tcx rustc_hir::Expr<'tcx>> {
97     if let ExprKind::Block(block, _) = expr.kind
98         && let Block {
99             stmts: [],       // Shouldn't lint if statements with side effects
100             expr: Some(expr),
101             ..
102         } = block
103         && let ExprKind::Lit(lit) = &expr.kind
104         && let LitKind::Int(_, _) = lit.node
105     {
106         Some(expr)
107     } else {
108         None
109     }
110 }
111
112 fn check_int_literal_equals_val<'tcx>(expr: &'tcx rustc_hir::Expr<'tcx>, expected_value: u128) -> bool {
113     if let ExprKind::Lit(lit) = &expr.kind
114         && let LitKind::Int(val, _) = lit.node
115         && val == expected_value
116     {
117         true
118     } else {
119         false
120     }
121 }
122
123 fn should_have_parentheses<'tcx>(check: &'tcx rustc_hir::Expr<'tcx>) -> bool {
124     check.precedence().order() < ExprPrecedence::Cast.order()
125 }