]> Cypherpunks repositories - gostls13.git/commitdiff
go/constant: MakeFloat64(0) must return a value of Float kind
authorRobert Griesemer <gri@golang.org>
Wed, 25 Nov 2020 04:28:20 +0000 (20:28 -0800)
committerRobert Griesemer <gri@golang.org>
Wed, 25 Nov 2020 04:48:23 +0000 (04:48 +0000)
Fixes #42641.

Change-Id: I10fdc7c90054b37ab5b303999015262691c12927
Reviewed-on: https://go-review.googlesource.com/c/go/+/273126
Trust: Robert Griesemer <gri@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
src/go/constant/value.go
src/go/constant/value_test.go

index 4baae2eb327fdba9e5b6ce2bff1b95ae4011a4f6..46414423f2d122f0883e347bb3c84d1d1cf99801 100644 (file)
@@ -370,16 +370,13 @@ func MakeUint64(x uint64) Value {
 }
 
 // MakeFloat64 returns the Float value for x.
+// If x is -0.0, the result is 0.0.
 // If x is not finite, the result is an Unknown.
 func MakeFloat64(x float64) Value {
        if math.IsInf(x, 0) || math.IsNaN(x) {
                return unknownVal{}
        }
-       // convert -0 to 0
-       if x == 0 {
-               return int64Val(0)
-       }
-       return ratVal{newRat().SetFloat64(x)}
+       return ratVal{newRat().SetFloat64(x + 0)} // convert -0 to 0
 }
 
 // MakeFromLiteral returns the corresponding integer, floating-point,
index 5edc766fde85df201bf4b8c7f3894ed144f647a2..286677407d98d832a1fbf1effb5db019ae39410b 100644 (file)
@@ -7,6 +7,7 @@ package constant
 import (
        "fmt"
        "go/token"
+       "math"
        "math/big"
        "strings"
        "testing"
@@ -620,6 +621,42 @@ func TestUnknown(t *testing.T) {
        }
 }
 
+func TestMakeFloat64(t *testing.T) {
+       var zero float64
+       for _, arg := range []float64{
+               -math.MaxFloat32,
+               -10,
+               -0.5,
+               -zero,
+               zero,
+               1,
+               10,
+               123456789.87654321e-23,
+               1e10,
+               math.MaxFloat64,
+       } {
+               val := MakeFloat64(arg)
+               if val.Kind() != Float {
+                       t.Errorf("%v: got kind = %d; want %d", arg, val.Kind(), Float)
+               }
+
+               // -0.0 is mapped to 0.0
+               got, exact := Float64Val(val)
+               if !exact || math.Float64bits(got) != math.Float64bits(arg+0) {
+                       t.Errorf("%v: got %v (exact = %v)", arg, got, exact)
+               }
+       }
+
+       // infinity
+       for sign := range []int{-1, 1} {
+               arg := math.Inf(sign)
+               val := MakeFloat64(arg)
+               if val.Kind() != Unknown {
+                       t.Errorf("%v: got kind = %d; want %d", arg, val.Kind(), Unknown)
+               }
+       }
+}
+
 type makeTestCase struct {
        kind      Kind
        arg, want interface{}