Skip to content

Commit

Permalink
Handle negative literals in cast overflow warning
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnTitor committed Mar 6, 2021
1 parent 51748a8 commit 6e4dcea
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
27 changes: 21 additions & 6 deletions compiler/rustc_lint/src/types.rs
Expand Up @@ -217,7 +217,11 @@ fn report_bin_hex_error(
cx.struct_span_lint(OVERFLOWING_LITERALS, expr.span, |lint| {
let (t, actually) = match ty {
attr::IntType::SignedInt(t) => {
let actually = size.sign_extend(val) as i128;
let actually = if negative {
-(size.sign_extend(val) as i128)
} else {
size.sign_extend(val) as i128
};
(t.name_str(), actually.to_string())
}
attr::IntType::UnsignedInt(t) => {
Expand All @@ -226,11 +230,22 @@ fn report_bin_hex_error(
}
};
let mut err = lint.build(&format!("literal out of range for `{}`", t));
err.note(&format!(
"the literal `{}` (decimal `{}`) does not fit into \
the type `{}` and will become `{}{}`",
repr_str, val, t, actually, t
));
if negative {
// If the value is negative,
// emits a note about the value itself, apart from the literal.
err.note(&format!(
"the literal `{}` (decimal `{}`) does not fit into \
the type `{}`",
repr_str, val, t
));
err.note(&format!("and the value `-{}` will become `{}{}`", repr_str, actually, t));
} else {
err.note(&format!(
"the literal `{}` (decimal `{}`) does not fit into \
the type `{}` and will become `{}{}`",
repr_str, val, t, actually, t
));
}
if let Some(sugg_ty) =
get_type_suggestion(&cx.typeck_results().node_type(expr.hir_id), val, negative)
{
Expand Down
3 changes: 2 additions & 1 deletion src/test/ui/lint/type-overflow.stderr
Expand Up @@ -60,7 +60,8 @@ warning: literal out of range for `i8`
LL | let fail = -0b1111_1111i8;
| ^^^^^^^^^^^^^ help: consider using the type `i16` instead: `0b1111_1111i16`
|
= note: the literal `0b1111_1111i8` (decimal `255`) does not fit into the type `i8` and will become `-1i8`
= note: the literal `0b1111_1111i8` (decimal `255`) does not fit into the type `i8`
= note: and the value `-0b1111_1111i8` will become `1i8`

warning: 7 warnings emitted

0 comments on commit 6e4dcea

Please sign in to comment.