From be2369708a0fd53fc1ed80cbcca25f24e12a781d Mon Sep 17 00:00:00 2001 From: spore Date: Wed, 8 Jan 2025 18:31:29 +0800 Subject: [PATCH] Detect overflow when the literal is larger than i128::MAX --- compiler/rustc_lint/src/types/literal.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index 83942918e3b58..c3e558a3e20a9 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -206,12 +206,15 @@ fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static ty::Uint(_) => Some(Integer::fit_unsigned(val).uint_ty_str()), ty::Int(_) if negative => Some(Integer::fit_signed(-(val as i128)).int_ty_str()), ty::Int(int) => { - let signed = Integer::fit_signed(val as i128); let unsigned = Integer::fit_unsigned(val); - Some(if Some(unsigned.size().bits()) == int.bit_width() { - unsigned.uint_ty_str() + Some(if let Ok(signed) = i128::try_from(val).map(Integer::fit_signed) { + if Some(unsigned.size().bits()) == int.bit_width() { + unsigned.uint_ty_str() + } else { + signed.int_ty_str() + } } else { - signed.int_ty_str() + unsigned.uint_ty_str() }) } _ => None,