diff options
| author | spore <spore2050@gmail.com> | 2025-01-08 19:00:10 +0800 |
|---|---|---|
| committer | spore <spore2050@gmail.com> | 2025-01-08 19:00:10 +0800 |
| commit | 330be171440eb4efe479c5b1fcfd079153c5159d (patch) | |
| tree | faeee610441af7020fb519d7c16fc7c9401e81cb | |
| parent | be2369708a0fd53fc1ed80cbcca25f24e12a781d (diff) | |
| download | rust-330be171440eb4efe479c5b1fcfd079153c5159d.tar.gz rust-330be171440eb4efe479c5b1fcfd079153c5159d.zip | |
Detect overflow when the literal is negative
| -rw-r--r-- | compiler/rustc_lint/src/types/literal.rs | 8 |
1 files changed, 7 insertions, 1 deletions
diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index c3e558a3e20..13eca89fba6 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -204,7 +204,13 @@ fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static match t.kind() { ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize) => None, 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(_) if negative => { + if val > i128::MAX as u128 + 1 { + None + } else { + Some(Integer::fit_signed(val.wrapping_neg() as i128).int_ty_str()) + } + } ty::Int(int) => { let unsigned = Integer::fit_unsigned(val); Some(if let Ok(signed) = i128::try_from(val).map(Integer::fit_signed) { |
