Keep the exponent digit when formatting floats with a zero exponent (#1543) The float rewrite strips leading zeros and plus signs from the exponent, so a float whose exponent is zero loses it entirely: `x = 1.5e0`, `1.5e+0` and `1.0E00` are written back as `1.5e` and `1.0e`, which is no longer valid Starlark. I keep a single `0` when the exponent has digits but all of them are zeros. A float with no exponent digits at all (`1.5e`) was already invalid, and is now left as written instead of being rewritten. The new cases in `build/testdata/003` cover `1.5e0`, `1.5e+0`, `1.0E00` and `.5e+000`. I also compared the old and new output over a few hundred combinations of mantissa, `e`/`E`, sign and exponent: only zero exponents and the digitless ones changed.
diff --git a/build/rewrite.go b/build/rewrite.go index 7924801..5aa47bf 100644 --- a/build/rewrite.go +++ b/build/rewrite.go
@@ -1421,7 +1421,16 @@ // Invalid float, skip rewriting. return } - l.Token = parts[0] + "e" + strings.TrimLeft(parts[1], "0+") + exp := strings.TrimLeft(parts[1], "0+") + if exp == "" { + if !strings.Contains(parts[1], "0") { + // Invalid float without exponent digits, skip rewriting. + return + } + // An exponent of zero, such as in 1.5e0 or 1.5e+00, must keep its digit. + exp = "0" + } + l.Token = parts[0] + "e" + exp }) }
diff --git a/build/testdata/003.golden b/build/testdata/003.golden index 7a120c1..e0dc8ac 100644 --- a/build/testdata/003.golden +++ b/build/testdata/003.golden
@@ -19,6 +19,10 @@ 3.539537889086625e24, 3.539537889086625e24000, 3.539537889086625e24000, + 1.5e0, + 1.5e0, + 1.0e0, + 0.5e0, 3539537889086624823140625, 0x123, 0xE45,
diff --git a/build/testdata/003.in b/build/testdata/003.in index 19915c3..7ba6cc7 100644 --- a/build/testdata/003.in +++ b/build/testdata/003.in
@@ -19,6 +19,10 @@ 3.539537889086625E+24, 3.539537889086625e00024000, 3.539537889086625e+00024000, + 1.5e0, + 1.5e+0, + 1.0E00, + .5e+000, 3539537889086624823140625, 0x123, 0xE45,