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};
6 use clippy_utils::{diagnostics::span_lint_and_then, is_else_clause, source::snippet_block_with_applicability};
7 use rustc_errors::Applicability;
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.
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.
18 /// See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E
22 /// # let condition = false;
31 /// # let condition = false;
32 /// i64::from(condition);
36 /// # let condition = false;
39 #[clippy::version = "1.65.0"]
40 pub BOOL_TO_INT_WITH_IF,
42 "using if to convert bool to int"
44 declare_lint_pass!(BoolToIntWithIf => [BOOL_TO_INT_WITH_IF]);
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);
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)
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}")
69 let ty = ctx.typeck_results().expr_ty(then_lit); // then and else must be of same type
72 let wrap_in_curly = is_else_clause(ctx.tcx, expr);
73 let (left_curly, right_curly) = if wrap_in_curly {("{", "}")} else {("", "")};
75 "{left_curly}{ty}::from({snippet}){right_curly}"
77 }; // when used in else clause if statement should be wrapped in curly braces
79 span_lint_and_then(ctx,
82 "boolean to int conversion using if",
90 diag.note(format!("`{snippet_with_braces} as {ty}` or `{snippet_with_braces}.into()` can also be valid options"));
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
99 stmts: [], // Shouldn't lint if statements with side effects
103 && let ExprKind::Lit(lit) = &expr.kind
104 && let LitKind::Int(_, _) = lit.node
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
123 fn should_have_parentheses<'tcx>(check: &'tcx rustc_hir::Expr<'tcx>) -> bool {
124 check.precedence().order() < ExprPrecedence::Cast.order()