Skip to content

Commit c97a06d

Browse files
committed
Auto merge of #7850 - ThibsG:PossibleCastTruncation5395, r=camsteffen
Fix FP: no lint when cast is coming from `signum` method call for `cast_possible_truncation` lint Fixes a FP when cast is coming from `signum` method call fixes: #5395 changelog: [`cast_possible_truncation`] Fix FP when cast is coming from `signum` method call
2 parents 91496c2 + 566244a commit c97a06d

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

clippy_lints/src/casts/cast_possible_truncation.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
use clippy_utils::diagnostics::span_lint;
2+
use clippy_utils::expr_or_init;
23
use clippy_utils::ty::is_isize_or_usize;
3-
use rustc_hir::Expr;
4+
use rustc_hir::{Expr, ExprKind};
45
use rustc_lint::LateContext;
56
use rustc_middle::ty::{self, FloatTy, Ty};
67

78
use super::{utils, CAST_POSSIBLE_TRUNCATION};
89

9-
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
10+
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
11+
// do not lint if cast comes from a `signum` function
12+
if let ExprKind::MethodCall(path, ..) = expr_or_init(cx, cast_expr).kind {
13+
if path.ident.name.as_str() == "signum" {
14+
return;
15+
}
16+
}
17+
1018
let msg = match (cast_from.is_integral(), cast_to.is_integral()) {
1119
(true, true) => {
1220
let from_nbits = utils::int_ty_to_nbits(cast_from, cx.tcx);

clippy_lints/src/casts/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
427427
fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to);
428428
fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
429429
if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
430-
cast_possible_truncation::check(cx, expr, cast_from, cast_to);
430+
cast_possible_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
431431
cast_possible_wrap::check(cx, expr, cast_from, cast_to);
432432
cast_precision_loss::check(cx, expr, cast_from, cast_to);
433433
cast_lossless::check(cx, expr, cast_expr, cast_from, cast_to);

tests/ui/cast.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,12 @@ fn main() {
9292
(1i64).checked_rem_euclid(-1i64).unwrap() as u64;
9393
(1i64).checked_rem_euclid(-1i64).unwrap() as u128;
9494
(1isize).checked_rem_euclid(-1isize).unwrap() as usize;
95+
96+
// no lint for `cast_possible_truncation`
97+
// with `signum` method call (see issue #5395)
98+
let x: i64 = 5;
99+
let _ = x.signum() as i32;
100+
101+
let s = x.signum();
102+
let _ = s as i32;
95103
}

0 commit comments

Comments
 (0)