Skip to content

Commit

Permalink
Normalize floats
Browse files Browse the repository at this point in the history
  • Loading branch information
fmeum committed Jan 6, 2025
1 parent 025cbb6 commit 59e2ab0
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
30 changes: 30 additions & 0 deletions build/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ var rewrites = []struct {
{"formatdocstrings", formatDocstrings, scopeBoth},
{"reorderarguments", reorderArguments, scopeBoth},
{"editoctal", editOctals, scopeBoth},
{"editfloat", editFloats, scopeBoth},
}

// leaveAlone reports whether any of the nodes on the stack are marked
Expand Down Expand Up @@ -1399,6 +1400,35 @@ func editOctals(f *File, _ *Rewriter) {
})
}

// editFloats inserts '0' before the decimal point in floats and normalizes the
// exponent part to lowercase, no plus sign, and no leading zero.
func editFloats(f *File, _ *Rewriter) {
Walk(f, func(expr Expr, stack []Expr) {
l, ok := expr.(*LiteralExpr)
if !ok {
return
}
if !strings.ContainsRune(l.Token, '.') {
return
}
if strings.HasPrefix(l.Token, ".") {
l.Token = "0" + l.Token
}
if !strings.ContainsAny(l.Token, "eE") {
return
}
parts := strings.SplitN(l.Token, "e", 2)
if len(parts) != 2 {
parts = strings.SplitN(l.Token, "E", 2)
}
if len(parts) != 2 {
// Invalid float, skip rewriting.
return
}
l.Token = parts[0] + "e" + strings.TrimLeft(parts[1], "0+")
})
}

// removeParens removes trivial parens
func removeParens(f *File, _ *Rewriter) {
var simplify func(expr Expr, stack []Expr) Expr
Expand Down
11 changes: 8 additions & 3 deletions build/testdata/003.golden
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ numbers = [
11,
123.456,
123.,
.456,
0.456,
1.23e45,
-1,
+1,
Expand All @@ -15,7 +15,12 @@ numbers = [
1e6,
-1e6,
-1.23e-45,
3.539537889086625e+24,
3.539537889086625E+24,
3.539537889086625e24,
3.539537889086625e24,
3.539537889086625e24000,
3.539537889086625e24000,
3539537889086624823140625,
0x123,
0xE45,
0xe45,
]
5 changes: 5 additions & 0 deletions build/testdata/003.in
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,10 @@ numbers = [
-1.23e-45,
3.539537889086625e+24,
3.539537889086625E+24,
3.539537889086625e00024000,
3.539537889086625e+00024000,
3539537889086624823140625,
0x123,
0xE45,
0xe45,
]

0 comments on commit 59e2ab0

Please sign in to comment.