Skip to content

Commit 74e2e8b

Browse files
committed
Suggest the smallest fitting type instead
Changes the behavior of the `overflowing_literals` suggestion so that it always suggest the smallest type regardless of the original type size.
1 parent f52724c commit 74e2e8b

File tree

3 files changed

+4
-4
lines changed

3 files changed

+4
-4
lines changed

compiler/rustc_lint/src/types/literal.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -204,14 +204,14 @@ fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static
204204
match t.kind() {
205205
ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize) => None,
206206
ty::Uint(_) => Some(Integer::fit_unsigned(val).uint_ty_str()),
207-
ty::Int(int) => {
207+
ty::Int(_) => {
208208
let signed = literal_to_i128(val, negative).map(Integer::fit_signed);
209209
if negative {
210210
signed.map(Integer::int_ty_str)
211211
} else {
212212
let unsigned = Integer::fit_unsigned(val);
213213
Some(if let Some(signed) = signed {
214-
if Some(unsigned.size().bits()) == int.bit_width() {
214+
if unsigned.size() < signed.size() {
215215
unsigned.uint_ty_str()
216216
} else {
217217
signed.int_ty_str()

tests/ui/lint/type-overflow.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ fn main() {
4040
//~| HELP consider using the type `u128` instead
4141

4242
let fail = 0x8FFF_FFFF_FFFF_FFFE; //~WARNING literal out of range for `i32`
43-
//~| HELP consider using the type `i128` instead
43+
//~| HELP consider using the type `u64` instead
4444
//~| HELP
4545

4646
let fail = -0b1111_1111i8; //~WARNING literal out of range for `i8`

tests/ui/lint/type-overflow.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ LL | let fail = 0x8FFF_FFFF_FFFF_FFFE;
109109
| ^^^^^^^^^^^^^^^^^^^^^
110110
|
111111
= note: the literal `0x8FFF_FFFF_FFFF_FFFE` (decimal `10376293541461622782`) does not fit into the type `i32` and will become `-2i32`
112-
= help: consider using the type `i128` instead
112+
= help: consider using the type `u64` instead
113113
help: to use as a negative number (decimal `-2`), consider using the type `u32` for the literal and cast it to `i32`
114114
|
115115
LL | let fail = 0x8FFF_FFFF_FFFF_FFFEu32 as i32;

0 commit comments

Comments
 (0)