From 73b28ae96ce58bd52605bef2fa2c1b3cf5bba278 Mon Sep 17 00:00:00 2001 From: Lee ByeongJun Date: Thu, 9 Nov 2023 21:29:59 +0900 Subject: [PATCH] handle undefined/nil type conversion --- gnovm/pkg/gnolang/gno_test.go | 96 +++++++++++++++++++++++++ gnovm/pkg/gnolang/values_conversions.go | 6 +- 2 files changed, 100 insertions(+), 2 deletions(-) diff --git a/gnovm/pkg/gnolang/gno_test.go b/gnovm/pkg/gnolang/gno_test.go index 5ed5971c836..4dd424b311a 100644 --- a/gnovm/pkg/gnolang/gno_test.go +++ b/gnovm/pkg/gnolang/gno_test.go @@ -107,6 +107,102 @@ func main() { }`, `aaa,bbb`) } +func TestVarDeclTypeConversion(t *testing.T) { + m := NewMachine("test", nil) + c := `package test +func main() { + var x float64 = 10.5 + println(int(x)) +}` + n := MustParseFile("main.go", c) + m.RunFiles(n) + m.RunMain() +} + +func TestShortenVarDeclTypeConversion(t *testing.T) { + m := NewMachine("test", nil) + c := `package test +func main() { + x := 10.5 // default type is float64 + println(int(x)) +}` + n := MustParseFile("main.go", c) + m.RunFiles(n) + m.RunMain() +} + + +func TestInvalidTypeConversion(t *testing.T) { + m := NewMachine("test", nil) + testCases := []struct { + name string + code string + }{ + { + name: "UndefinedIntType", + code: `package test + func main(){ + println(int(10.5)) + }`, + }, + { + name: "NilToInt", + code: `package test + func main(){ + println(int(nil)) + }`, + }, + { + name: "NilToFloat", + code: `package test + func main(){ + println(float64(nil)) + }`, + }, + { + name: "NilToBool", + code: `package test + func main(){ + println(bool(nil)) + }`, + }, + { + name: "BoolToInt", + code: `package test + func main(){ + println(int(true)) + }`, + }, + { + name: "IntToBool", + code: `package test + func main(){ + x := 1 + println(bool(x)) + }`, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + n := MustParseFile("main.go", tc.code) + defer func() { + if r := recover(); r != nil { + t.Logf("Recovered from panic as expected: %v", r) + } else { + t.Errorf("Expected a panic for invalid type conversion") + } + }() + m.RunFiles(n) + m.RunMain() + + if err := m.CheckEmpty(); err != nil { + t.Fatal(err) + } + }) + } +} + // ---------------------------------------- // Benchmarks diff --git a/gnovm/pkg/gnolang/values_conversions.go b/gnovm/pkg/gnolang/values_conversions.go index cc7c0de9f09..418ef279723 100644 --- a/gnovm/pkg/gnolang/values_conversions.go +++ b/gnovm/pkg/gnolang/values_conversions.go @@ -77,8 +77,10 @@ GNO_CASE: } // special case for undefined/nil source if tv.IsUndefined() { - tv.T = t - return + panic(fmt.Sprintf( + "cannot convert %s (untyped %s constant) to type %s", + tv.String(), tv.T.String(), t.String()), + ) } // general case tvk := tv.T.Kind()