Skip to content

Commit 487e83b

Browse files
committed
Auto merge of #105650 - cassaundra:float-literal-suggestion, r=pnkfelix
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`. r? nnethercote
2 parents 001a77f + 80fcd7c commit 487e83b

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
@@ -1882,7 +1882,16 @@ impl<'a> Parser<'a> {
18821882
if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
18831883
next_token.kind
18841884
{
1885-
if self.token.span.hi() == next_token.span.lo() {
1885+
// If this integer looks like a float, then recover as such.
1886+
//
1887+
// We will never encounter the exponent part of a floating
1888+
// point literal here, since there's no use of the exponent
1889+
// syntax that also constitutes a valid integer, so we need
1890+
// not check for that.
1891+
if suffix.map_or(true, |s| s == sym::f32 || s == sym::f64)
1892+
&& symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
1893+
&& self.token.span.hi() == next_token.span.lo()
1894+
{
18861895
let s = String::from("0.") + symbol.as_str();
18871896
let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
18881897
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)