Skip to content

Add suggestion to cast_sign_loss and cast_possible_wrap using the cast_{un,}signed() methods #15384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion clippy_lints/src/casts/cast_possible_wrap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::sugg::Sugg;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::Ty;
Expand All @@ -16,7 +19,14 @@ enum EmitState {
LintOnPtrSize(u64),
}

pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
pub(super) fn check(
cx: &LateContext<'_>,
expr: &Expr<'_>,
cast_op: &Expr<'_>,
cast_from: Ty<'_>,
cast_to: Ty<'_>,
msrv: Msrv,
) {
let (Some(from_nbits), Some(to_nbits)) = (
utils::int_ty_to_nbits(cx.tcx, cast_from),
utils::int_ty_to_nbits(cx.tcx, cast_to),
Expand Down Expand Up @@ -85,5 +95,23 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, ca
.note("`usize` and `isize` may be as small as 16 bits on some platforms")
.note("for more information see https://doc.rust-lang.org/reference/types/numeric.html#machine-dependent-integer-types");
}

if msrv.meets(cx, msrvs::INTEGER_SIGN_CAST)
&& let Some(cast) = utils::is_signedness_cast(cast_from, cast_to)
{
let method = match cast {
utils::CastTo::Signed => "cast_signed()",
utils::CastTo::Unsigned => "cast_unsigned()",
};
let mut app = Applicability::MaybeIncorrect;
let sugg = Sugg::hir_with_context(cx, cast_op, expr.span.ctxt(), "..", &mut app);

diag.span_suggestion(
expr.span,
format!("if this is intentional, use `{method}` instead"),
format!("{}.{method}", sugg.maybe_paren()),
app,
);
}
});
}
29 changes: 26 additions & 3 deletions clippy_lints/src/casts/cast_sign_loss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ use std::convert::Infallible;
use std::ops::ControlFlow;

use clippy_utils::consts::{ConstEvalCtxt, Constant};
use clippy_utils::diagnostics::span_lint;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::sugg::Sugg;
use clippy_utils::visitors::{Descend, for_each_expr_without_closures};
use clippy_utils::{method_chain_args, sext, sym};
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use rustc_span::Symbol;

use super::CAST_SIGN_LOSS;
use super::{CAST_SIGN_LOSS, utils};

/// A list of methods that can never return a negative value.
/// Includes methods that panic rather than returning a negative value.
Expand Down Expand Up @@ -42,13 +45,33 @@ pub(super) fn check<'cx>(
cast_op: &Expr<'_>,
cast_from: Ty<'cx>,
cast_to: Ty<'_>,
msrv: Msrv,
) {
if should_lint(cx, cast_op, cast_from, cast_to) {
span_lint(
span_lint_and_then(
cx,
CAST_SIGN_LOSS,
expr.span,
format!("casting `{cast_from}` to `{cast_to}` may lose the sign of the value"),
|diag| {
if msrv.meets(cx, msrvs::INTEGER_SIGN_CAST)
&& let Some(cast) = utils::is_signedness_cast(cast_from, cast_to)
{
let method = match cast {
utils::CastTo::Signed => "cast_signed()",
utils::CastTo::Unsigned => "cast_unsigned()",
};
let mut app = Applicability::MaybeIncorrect;
let sugg = Sugg::hir_with_context(cx, cast_op, expr.span.ctxt(), "..", &mut app);

diag.span_suggestion(
expr.span,
format!("if this is intentional, use `{method}` instead"),
format!("{}.{method}", sugg.maybe_paren()),
app,
);
}
},
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/casts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -887,9 +887,9 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
if cast_to.is_numeric() {
cast_possible_truncation::check(cx, expr, cast_from_expr, cast_from, cast_to, cast_to_hir.span);
if cast_from.is_numeric() {
cast_possible_wrap::check(cx, expr, cast_from, cast_to);
cast_possible_wrap::check(cx, expr, cast_from_expr, cast_from, cast_to, self.msrv);
cast_precision_loss::check(cx, expr, cast_from, cast_to);
cast_sign_loss::check(cx, expr, cast_from_expr, cast_from, cast_to);
cast_sign_loss::check(cx, expr, cast_from_expr, cast_from, cast_to, self.msrv);
cast_abs_to_unsigned::check(cx, expr, cast_from_expr, cast_from, cast_to, self.msrv);
cast_nan_to_int::check(cx, expr, cast_from_expr, cast_from, cast_to);
}
Expand Down
15 changes: 15 additions & 0 deletions clippy_lints/src/casts/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,18 @@ pub(super) fn enum_ty_to_nbits(adt: AdtDef<'_>, tcx: TyCtxt<'_>) -> u64 {
neg_bits.max(pos_bits).into()
}
}

pub(super) enum CastTo {
Signed,
Unsigned,
}
/// Returns `Some` if the type cast is between 2 integral types that differ
/// only in signedness, otherwise `None`. The value of `Some` is which
/// signedness is casted to.
pub(super) fn is_signedness_cast(cast_from: Ty<'_>, cast_to: Ty<'_>) -> Option<CastTo> {
match (cast_from.kind(), cast_to.kind()) {
(ty::Int(from), ty::Uint(to)) if from.to_unsigned() == *to => Some(CastTo::Unsigned),
(ty::Uint(from), ty::Int(to)) if *from == to.to_unsigned() => Some(CastTo::Signed),
_ => None,
}
}
2 changes: 1 addition & 1 deletion clippy_utils/src/msrvs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ macro_rules! msrv_aliases {
// names may refer to stabilized feature flags or library items
msrv_aliases! {
1,88,0 { LET_CHAINS }
1,87,0 { OS_STR_DISPLAY, INT_MIDPOINT, CONST_CHAR_IS_DIGIT, UNSIGNED_IS_MULTIPLE_OF }
1,87,0 { OS_STR_DISPLAY, INT_MIDPOINT, CONST_CHAR_IS_DIGIT, UNSIGNED_IS_MULTIPLE_OF, INTEGER_SIGN_CAST }
1,85,0 { UINT_FLOAT_MIDPOINT, CONST_SIZE_OF_VAL }
1,84,0 { CONST_OPTION_AS_SLICE, MANUAL_DANGLING_PTR }
1,83,0 { CONST_EXTERN_FN, CONST_FLOAT_BITS_CONV, CONST_FLOAT_CLASSIFY, CONST_MUT_REFS, CONST_UNWRAP }
Expand Down
13 changes: 13 additions & 0 deletions tests/ui/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,3 +569,16 @@ fn issue12721() {
(255 % 999999u64) as u8;
//~^ cast_possible_truncation
}

mod issue14150 {
#[clippy::msrv = "1.87"]
fn msrv_supports_cast_signed() {
_ = 1u8 as i8;
//~^ cast_possible_wrap
}
#[clippy::msrv = "1.86"]
fn msrv_doesnt_supports_cast_signed() {
_ = 1u8 as i8;
//~^ cast_possible_wrap
}
}
Loading