Skip to content

Commit

Permalink
Auto merge of #90297 - dtolnay:dotzero, r=petrochenkov
Browse files Browse the repository at this point in the history
Append .0 to unsuffixed float if it would otherwise become int token

Previously the unsuffixed f32/f64 constructors of `proc_macro::Literal` would create literal tokens that are definitely not a float:

```rust
Literal::f32_unsuffixed(10.0)  // 10
Literal::f32_suffixed(10.0)    // 10f32
Literal::f64_unsuffixed(10.0)  // 10
Literal::f64_suffixed(10.0)    // 10f64
```

Notice that the `10` are actually integer tokens if you were to reparse them, not float tokens.

This diff updates `Literal::f32_unsuffixed` and `Literal::f64_unsuffixed` to produce tokens that unambiguously parse as a float. This matches longstanding behavior of the proc-macro2 crate's implementation of these APIs dating back at least 3.5 years, so it's likely an unobjectionable behavior.

```rust
Literal::f32_unsuffixed(10.0)  // 10.0
Literal::f32_suffixed(10.0)    // 10f32
Literal::f64_unsuffixed(10.0)  // 10.0
Literal::f64_suffixed(10.0)    // 10f64
```

Fixes dtolnay/syn#1085.
  • Loading branch information
bors committed Nov 6, 2021
2 parents 9d39f6a + 1f98077 commit 7276a6a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
12 changes: 10 additions & 2 deletions library/proc_macro/src/lib.rs
Expand Up @@ -1074,7 +1074,11 @@ impl Literal {
if !n.is_finite() {
panic!("Invalid float literal {}", n);
}
Literal(bridge::client::Literal::float(&n.to_string()))
let mut repr = n.to_string();
if !repr.contains('.') {
repr.push_str(".0");
}
Literal(bridge::client::Literal::float(&repr))
}

/// Creates a new suffixed floating-point literal.
Expand Down Expand Up @@ -1115,7 +1119,11 @@ impl Literal {
if !n.is_finite() {
panic!("Invalid float literal {}", n);
}
Literal(bridge::client::Literal::float(&n.to_string()))
let mut repr = n.to_string();
if !repr.contains('.') {
repr.push_str(".0");
}
Literal(bridge::client::Literal::float(&repr))
}

/// Creates a new suffixed floating-point literal.
Expand Down
10 changes: 10 additions & 0 deletions src/test/ui/proc-macro/auxiliary/api/parse.rs
@@ -1,3 +1,5 @@
// ignore-tidy-linelength

use proc_macro::Literal;

pub fn test() {
Expand All @@ -8,6 +10,14 @@ pub fn test() {
fn test_display_literal() {
assert_eq!(Literal::isize_unsuffixed(-10).to_string(), "-10");
assert_eq!(Literal::isize_suffixed(-10).to_string(), "-10isize");
assert_eq!(Literal::f32_unsuffixed(-10.0).to_string(), "-10.0");
assert_eq!(Literal::f32_suffixed(-10.0).to_string(), "-10f32");
assert_eq!(Literal::f64_unsuffixed(-10.0).to_string(), "-10.0");
assert_eq!(Literal::f64_suffixed(-10.0).to_string(), "-10f64");
assert_eq!(
Literal::f64_unsuffixed(1e100).to_string(),
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0",
);
}

fn test_parse_literal() {
Expand Down

0 comments on commit 7276a6a

Please sign in to comment.