Skip to content

Commit

Permalink
Add type checks for "in" operator
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Oct 4, 2018
1 parent 8a82eee commit 48a3857
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
42 changes: 42 additions & 0 deletions type.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ func (n binaryNode) Type(table typesTable) (Type, error) {
}
return nil, fmt.Errorf(`invalid operation: %v (mismatched types %v and %v)`, n, ltype, rtype)

case "in", "not in":
if (isStringType(ltype) || isInterfaceType(ltype)) && (isStructType(rtype) || isInterfaceType(rtype)) {
return boolType, nil
}
if isArrayType(rtype) || isMapType(rtype) || isInterfaceType(rtype) {
return boolType, nil
}
return nil, fmt.Errorf(`invalid operation: %v (mismatched types %v and %v)`, n, ltype, rtype)

case "<", ">", ">=", "<=":
if (isNumberType(ltype) || isInterfaceType(ltype)) && (isNumberType(rtype) || isInterfaceType(rtype)) {
return boolType, nil
Expand Down Expand Up @@ -325,6 +334,39 @@ func isStringType(t Type) bool {
return false
}

func isArrayType(t Type) bool {
t = dereference(t)
if t != nil {
switch t.Kind() {
case reflect.Slice, reflect.Array:
return true
}
}
return false
}

func isMapType(t Type) bool {
t = dereference(t)
if t != nil {
switch t.Kind() {
case reflect.Map:
return true
}
}
return false
}

func isStructType(t Type) bool {
t = dereference(t)
if t != nil {
switch t.Kind() {
case reflect.Struct:
return true
}
}
return false
}

func fieldType(ntype Type, name string) (Type, bool) {
ntype = dereference(ntype)
if ntype != nil {
Expand Down
12 changes: 12 additions & 0 deletions type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ var typeTests = []typeTest{
"nil == nil",
"nil == IntPtr",
"Foo2p.Bar.Baz",
"Str in Foo",
"Str in Arr",
"nil in Arr",
"Str not in Foo2p",
"Int | Num",
"Int ^ Num",
"Int & Num",
Expand Down Expand Up @@ -268,6 +272,14 @@ var typeErrorTests = []typeErrorTest{
"NilFn() and OkFn()",
"invalid operation: NilFn() and OkFn() (mismatched types <nil> and bool)",
},
{
"'str' in Str",
`invalid operation: "str" in Str (mismatched types string and string)`,
},
{
"1 in Foo",
"invalid operation: 1 in Foo (mismatched types float64 and *expr_test.foo)",
},
}

type abc interface {
Expand Down

0 comments on commit 48a3857

Please sign in to comment.