Skip to content

Commit

Permalink
Small transmute_float_to_int cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarcho committed Feb 6, 2022
1 parent 3403b3e commit 68993b1
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions clippy_lints/src/transmute/transmute_float_to_int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub(super) fn check<'tcx>(
e: &'tcx Expr<'_>,
from_ty: Ty<'tcx>,
to_ty: Ty<'tcx>,
arg: &'tcx Expr<'_>,
mut arg: &'tcx Expr<'_>,
const_context: bool,
) -> bool {
match (&from_ty.kind(), &to_ty.kind()) {
Expand All @@ -26,37 +26,36 @@ pub(super) fn check<'tcx>(
e.span,
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
|diag| {
let mut expr = arg;
let mut arg = sugg::Sugg::hir(cx, expr, "..");
let mut sugg = sugg::Sugg::hir(cx, arg, "..");

if let ExprKind::Unary(UnOp::Neg, inner_expr) = &expr.kind {
expr = inner_expr;
if let ExprKind::Unary(UnOp::Neg, inner_expr) = &arg.kind {
arg = inner_expr;
}

if_chain! {
// if the expression is a float literal and it is unsuffixed then
// add a suffix so the suggestion is valid and unambiguous
if let ExprKind::Lit(lit) = &expr.kind;
if let ExprKind::Lit(lit) = &arg.kind;
if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
then {
let op = format!("{}{}", arg, float_ty.name_str()).into();
match arg {
sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
_ => arg = sugg::Sugg::NonParen(op)
let op = format!("{}{}", sugg, float_ty.name_str()).into();
match sugg {
sugg::Sugg::MaybeParen(_) => sugg = sugg::Sugg::MaybeParen(op),
_ => sugg = sugg::Sugg::NonParen(op)
}
}
}

arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
sugg = sugg::Sugg::NonParen(format!("{}.to_bits()", sugg.maybe_par()).into());

// cast the result of `to_bits` if `to_ty` is signed
arg = if let ty::Int(int_ty) = to_ty.kind() {
arg.as_ty(int_ty.name_str().to_string())
sugg = if let ty::Int(int_ty) = to_ty.kind() {
sugg.as_ty(int_ty.name_str().to_string())
} else {
arg
sugg
};

diag.span_suggestion(e.span, "consider using", arg.to_string(), Applicability::Unspecified);
diag.span_suggestion(e.span, "consider using", sugg.to_string(), Applicability::Unspecified);
},
);
true
Expand Down

0 comments on commit 68993b1

Please sign in to comment.