Skip to content

Commit

Permalink
jsgen: fix incorrect float32-literal behaviour (#824)
Browse files Browse the repository at this point in the history
## Summary

Narrow the value of 32-bit float-literal nodes prior to rendering them,
which fixes `float32` literals having an unexpected run-time value
when their value as-written is not fully representable with the
precision of a 32-bit float.

## Details

Instead of using `toStrMaxPrecision`, which would add an unwanted `f`
suffix, rendering the float value to text is done by directly calling
`addFloatRoundtrip`, which `toStrMaxPrecision` uses internally.
  • Loading branch information
zerbina authored Aug 2, 2023
1 parent b794757 commit 50c2ac0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
12 changes: 8 additions & 4 deletions compiler/backend/jsgen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ Check `mapType` for the details.
"""

import
system/[
formatfloat
],
std/[
sets,
math,
Expand Down Expand Up @@ -50,9 +53,6 @@ import
nversion,
ropes
],
compiler/sem/[
rodutils,
],
compiler/backend/[
ccgutils,
]
Expand Down Expand Up @@ -2449,7 +2449,11 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) =
r.res = rope"Infinity"
of fcNegInf:
r.res = rope"-Infinity"
else: r.res = rope(f.toStrMaxPrecision)
else:
if n.typ.skipTypes(abstractRange).kind == tyFloat32:
r.res.addFloatRoundtrip(f.float32)
else:
r.res.addFloatRoundtrip(f)
r.kind = resExpr
of nkCall:
if isEmptyType(n.typ):
Expand Down
8 changes: 2 additions & 6 deletions tests/lang_types/float/tfloats.nim
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,8 @@ template main =
doAssert $x2 == "1.32"
block:
var x = 1.23456789012345'f32
when nimvm:
discard # xxx, refs #12884
else:
when not defined(js):
doAssert x == 1.2345679'f32
doAssert $x == "1.2345679"
doAssert x == 1.2345679'f32
doAssert $x == "1.2345679"

static: main()
main()

0 comments on commit 50c2ac0

Please sign in to comment.