From f6dcc975f7207340ad11d9296c42e7730ecf1f9f Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Tue, 24 Nov 2020 17:26:22 -0800 Subject: [PATCH] go/constant: make constant.Make produce "smallest" const representation Fixes #42640. Change-Id: I22b8142b0a47a0f957d1bda28cdfdbb8388cffc4 Reviewed-on: https://go-review.googlesource.com/c/go/+/273086 Trust: Robert Griesemer Reviewed-by: Matthew Dempsky --- src/go/constant/value.go | 6 +++--- src/go/constant/value_test.go | 34 ++++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/go/constant/value.go b/src/go/constant/value.go index 116c7575d9..4baae2eb32 100644 --- a/src/go/constant/value.go +++ b/src/go/constant/value.go @@ -594,11 +594,11 @@ func Make(x interface{}) Value { case int64: return int64Val(x) case *big.Int: - return intVal{x} + return makeInt(x) case *big.Rat: - return ratVal{x} + return makeRat(x) case *big.Float: - return floatVal{x} + return makeFloat(x) default: return unknownVal{} } diff --git a/src/go/constant/value_test.go b/src/go/constant/value_test.go index 1a5025cbbd..5edc766fde 100644 --- a/src/go/constant/value_test.go +++ b/src/go/constant/value_test.go @@ -620,18 +620,32 @@ func TestUnknown(t *testing.T) { } } +type makeTestCase struct { + kind Kind + arg, want interface{} +} + +func dup(k Kind, x interface{}) makeTestCase { return makeTestCase{k, x, x} } + func TestMake(t *testing.T) { - for _, want := range []interface{}{ - false, - "hello", - int64(1), - big.NewInt(10), - big.NewFloat(2.0), - big.NewRat(1, 3), + for _, test := range []makeTestCase{ + {Bool, false, false}, + {String, "hello", "hello"}, + + {Int, int64(1), int64(1)}, + {Int, big.NewInt(10), int64(10)}, + {Int, new(big.Int).Lsh(big.NewInt(1), 62), int64(1 << 62)}, + dup(Int, new(big.Int).Lsh(big.NewInt(1), 63)), + + {Float, big.NewFloat(0), floatVal0.val}, + dup(Float, big.NewFloat(2.0)), + dup(Float, big.NewRat(1, 3)), } { - got := Val(Make(want)) - if got != want { - t.Errorf("got %v; want %v", got, want) + val := Make(test.arg) + got := Val(val) + if val.Kind() != test.kind || got != test.want { + t.Errorf("got %v (%T, kind = %d); want %v (%T, kind = %d)", + got, got, val.Kind(), test.want, test.want, test.kind) } } } -- 2.48.1