Fix undefined value compatibility

This commit is contained in:
Daniel Kang 2019-01-15 17:21:58 -08:00
parent d1f7baf054
commit 40ad7aa1bb
4 changed files with 20 additions and 9 deletions

View file

@ -6,33 +6,33 @@ import "github.com/d5/tengo/compiler/token"
type Undefined struct{}
// TypeName returns the name of the type.
func (o Undefined) TypeName() string {
func (o *Undefined) TypeName() string {
return "undefined"
}
func (o Undefined) String() string {
func (o *Undefined) String() string {
return "<undefined>"
}
// BinaryOp returns another object that is the result of
// a given binary operator and a right-hand side object.
func (o Undefined) BinaryOp(op token.Token, rhs Object) (Object, error) {
func (o *Undefined) BinaryOp(op token.Token, rhs Object) (Object, error) {
return nil, ErrInvalidOperator
}
// Copy returns a copy of the type.
func (o Undefined) Copy() Object {
return Undefined{}
func (o *Undefined) Copy() Object {
return &Undefined{}
}
// IsFalsy returns true if the value of the type is falsy.
func (o Undefined) IsFalsy() bool {
func (o *Undefined) IsFalsy() bool {
return true
}
// Equals returns true if the value of the type
// is equal to the value of another object.
func (o Undefined) Equals(x Object) bool {
func (o *Undefined) Equals(x Object) bool {
_, ok := x.(*Undefined)
return ok

View file

@ -65,6 +65,8 @@ func objectToInterface(o objects.Object) interface{} {
func interfaceToObject(v interface{}) (objects.Object, error) {
switch v := v.(type) {
case nil:
return undefined, nil
case string:
return &objects.String{Value: v}, nil
case int64:

View file

@ -156,7 +156,7 @@ func (v *Variable) Object() objects.Object {
// IsUndefined returns true if the underlying value is undefined.
func (v *Variable) IsUndefined() bool {
_, isUndefined := (*v.value).(objects.Undefined)
_, isUndefined := (*v.value).(*objects.Undefined)
return isUndefined
}

View file

@ -19,6 +19,7 @@ type VariableTest struct {
BoolValue bool
StringValue string
Object objects.Object
IsUndefined bool
}
func TestVariable(t *testing.T) {
@ -52,6 +53,14 @@ func TestVariable(t *testing.T) {
StringValue: "true",
Object: &objects.Bool{Value: true},
},
{
Name: "d",
Value: nil,
ValueType: "undefined",
StringValue: "<undefined>",
Object: objects.UndefinedValue,
IsUndefined: true,
},
}
for _, tc := range vars {
@ -66,6 +75,6 @@ func TestVariable(t *testing.T) {
assert.Equal(t, tc.BoolValue, v.Bool())
assert.Equal(t, tc.StringValue, v.String())
assert.Equal(t, tc.Object, v.Object())
assert.Equal(t, tc.IsUndefined, v.IsUndefined())
}
}