Skip to content

Commit 80fcd7c

Browse files
committed
Fix invalid float literal suggestions when recovering an integer
Only suggest adding a zero to integers with a preceding dot when the change will result in a valid floating point literal. For example, `.0x0` should not be turned into `0.0x0`.
1 parent 4817259 commit 80fcd7c

File tree

3 files changed

+60
-1
lines changed

3 files changed

+60
-1
lines changed

compiler/rustc_parse/src/parser/expr.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -1854,7 +1854,16 @@ impl<'a> Parser<'a> {
18541854
if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
18551855
next_token.kind
18561856
{
1857-
if self.token.span.hi() == next_token.span.lo() {
1857+
// If this integer looks like a float, then recover as such.
1858+
//
1859+
// We will never encounter the exponent part of a floating
1860+
// point literal here, since there's no use of the exponent
1861+
// syntax that also constitutes a valid integer, so we need
1862+
// not check for that.
1863+
if suffix.map_or(true, |s| s == sym::f32 || s == sym::f64)
1864+
&& symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
1865+
&& self.token.span.hi() == next_token.span.lo()
1866+
{
18581867
let s = String::from("0.") + symbol.as_str();
18591868
let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
18601869
return Some(Token::new(kind, self.token.span.to(next_token.span)));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Check that suggestions to add a zero to integers with a preceding dot only appear when the change
2+
// will result in a valid floating point literal.
3+
4+
fn main() {}
5+
6+
fn a() {
7+
_ = .3u32;
8+
//~^ ERROR expected expression, found `.`
9+
}
10+
11+
fn b() {
12+
_ = .0b0;
13+
//~^ ERROR expected expression, found `.`
14+
}
15+
16+
fn c() {
17+
_ = .0o07;
18+
//~^ ERROR expected expression, found `.`
19+
}
20+
21+
fn d() {
22+
_ = .0x0ABC;
23+
//~^ ERROR expected expression, found `.`
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
error: expected expression, found `.`
2+
--> $DIR/recover-invalid-float-invalid.rs:7:9
3+
|
4+
LL | _ = .3u32;
5+
| ^ expected expression
6+
7+
error: expected expression, found `.`
8+
--> $DIR/recover-invalid-float-invalid.rs:12:9
9+
|
10+
LL | _ = .0b0;
11+
| ^ expected expression
12+
13+
error: expected expression, found `.`
14+
--> $DIR/recover-invalid-float-invalid.rs:17:9
15+
|
16+
LL | _ = .0o07;
17+
| ^ expected expression
18+
19+
error: expected expression, found `.`
20+
--> $DIR/recover-invalid-float-invalid.rs:22:9
21+
|
22+
LL | _ = .0x0ABC;
23+
| ^ expected expression
24+
25+
error: aborting due to 4 previous errors
26+

0 commit comments

Comments
 (0)