Skip to content

Commit

Permalink
Fix type checker for "in" operator
Browse files Browse the repository at this point in the history
Fixes #426
  • Loading branch information
antonmedv committed Sep 6, 2023
1 parent 6001a17 commit 01c358d
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 11 deletions.
13 changes: 2 additions & 11 deletions checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,16 +242,7 @@ func (v *checker) BinaryNode(node *ast.BinaryNode) (reflect.Type, info) {

switch node.Operator {
case "==", "!=":
if isNumber(l) && isNumber(r) {
return boolType, info{}
}
if l == nil || r == nil { // It is possible to compare with nil.
return boolType, info{}
}
if l.Kind() == r.Kind() {
return boolType, info{}
}
if isAny(l) || isAny(r) {
if isComparable(l, r) {
return boolType, info{}
}

Expand Down Expand Up @@ -357,7 +348,7 @@ func (v *checker) BinaryNode(node *ast.BinaryNode) (reflect.Type, info) {
if l == nil { // It is possible to compare with nil.
return boolType, info{}
}
if !isAny(l) && !l.AssignableTo(r.Elem()) && !(isInteger(l) && isInteger(r.Elem())) {
if !isComparable(l, r.Elem()) {
return v.error(node, "cannot use %v as type %v in array", l, r.Elem())
}
return boolType, info{}
Expand Down
5 changes: 5 additions & 0 deletions checker/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,11 @@ cannot use float64 as type int in map key (1:5)
| 1/2 in MapIntAny
| ....^
0.5 in ArrayOfFoo
cannot use float64 as type *mock.Foo in array (1:5)
| 0.5 in ArrayOfFoo
| ....^
repeat("0", 1/0)
cannot use float64 as argument (type int) to call repeat (1:14)
| repeat("0", 1/0)
Expand Down
15 changes: 15 additions & 0 deletions checker/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,18 @@ func kind(t reflect.Type) reflect.Kind {
}
return t.Kind()
}

func isComparable(l, r reflect.Type) bool {
if l == nil || r == nil {
return true
}
switch {
case l.Kind() == r.Kind():
return true
case isNumber(l) && isNumber(r):
return true
case isAny(l) || isAny(r):
return true
}
return false
}
8 changes: 8 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,14 @@ func TestExpr(t *testing.T) {
`4/2 == 2`,
true,
},
{
`.5 in 0..1`,
false,
},
{
`.5 in ArrayOfInt`,
false,
},
}

for _, tt := range tests {
Expand Down

0 comments on commit 01c358d

Please sign in to comment.