Rollup merge of #138484 - xizheyin:issue-138392, r=compiler-errors

Use lit span when suggesting suffix lit cast

Fixes #138392
This commit is contained in:
许杰友 Jieyou Xu (Joe)
2025-03-16 09:40:10 +08:00
committed by GitHub
4 changed files with 47 additions and 3 deletions
@@ -2983,7 +2983,8 @@ pub(crate) fn suggest_cast(
return false;
}
let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) else {
let span = if let hir::ExprKind::Lit(lit) = &expr.kind { lit.span } else { expr.span };
let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) else {
return false;
};
@@ -3078,10 +3079,10 @@ pub(crate) fn suggest_cast(
// Remove fractional part from literal, for example `42.0f32` into `42`
let src = src.trim_end_matches(&checked_ty.to_string());
let len = src.split('.').next().unwrap().len();
expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
span.with_lo(span.lo() + BytePos(len as u32))
} else {
let len = src.trim_end_matches(&checked_ty.to_string()).len();
expr.span.with_lo(expr.span.lo() + BytePos(len as u32))
span.with_lo(span.lo() + BytePos(len as u32))
},
if expr.precedence() < ExprPrecedence::Unambiguous {
// Readd `)`
@@ -0,0 +1,6 @@
//@ run-rustfix
#![allow(unused_parens)]
fn main() {
let _x: u8 = (4u8); //~ ERROR: mismatched types
let _y: u8 = (4u8); //~ ERROR: mismatched types
}
@@ -0,0 +1,6 @@
//@ run-rustfix
#![allow(unused_parens)]
fn main() {
let _x: u8 = (4i32); //~ ERROR: mismatched types
let _y: u8 = (4.0f32); //~ ERROR: mismatched types
}
@@ -0,0 +1,31 @@
error[E0308]: mismatched types
--> $DIR/cast_lit_suffix-issue-138392.rs:4:18
|
LL | let _x: u8 = (4i32);
| -- ^^^^^^ expected `u8`, found `i32`
| |
| expected due to this
|
help: change the type of the numeric literal from `i32` to `u8`
|
LL - let _x: u8 = (4i32);
LL + let _x: u8 = (4u8);
|
error[E0308]: mismatched types
--> $DIR/cast_lit_suffix-issue-138392.rs:5:18
|
LL | let _y: u8 = (4.0f32);
| -- ^^^^^^^^ expected `u8`, found `f32`
| |
| expected due to this
|
help: change the type of the numeric literal from `f32` to `u8`
|
LL - let _y: u8 = (4.0f32);
LL + let _y: u8 = (4u8);
|
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0308`.