compiler: initialize struct fields explicitly

By default VM initializes every field of a new struct to a Boolean.
If field contains another struct, we need to initialize it to default
value explicitly. This commit sets default values for uninitialized
field.
This commit is contained in:
Evgenii Stratonikov 2020-05-20 11:32:52 +03:00
parent 051e3608ff
commit 5b0e73ddf0
3 changed files with 35 additions and 37 deletions

View file

@ -2,9 +2,7 @@ package compiler
import (
"errors"
"fmt"
"go/ast"
"go/constant"
"go/types"
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
@ -23,33 +21,6 @@ var (
}
)
// typeAndValueForField returns a zero initialized typeAndValue for the given type.Var.
func typeAndValueForField(fld *types.Var) (types.TypeAndValue, error) {
switch t := fld.Type().(type) {
case *types.Basic:
switch t.Kind() {
case types.Int:
return types.TypeAndValue{
Type: t,
Value: constant.MakeInt64(0),
}, nil
case types.String:
return types.TypeAndValue{
Type: t,
Value: constant.MakeString(""),
}, nil
case types.Bool, types.UntypedBool:
return types.TypeAndValue{
Type: t,
Value: constant.MakeBool(false),
}, nil
default:
return types.TypeAndValue{}, fmt.Errorf("could not initialize struct field %s to zero, type: %s", fld.Name(), t)
}
}
return types.TypeAndValue{}, nil
}
// newGlobal creates new global variable.
func (c *codegen) newGlobal(name string) {
c.globals[name] = len(c.globals)