Fix type checker for "in" operator

Fixes #426
This commit is contained in:
Anton Medvedev
2023-09-06 10:36:40 +02:00
parent 98b121681a
commit 454373abbe
4 changed files with 30 additions and 11 deletions
+2 -11
View File
@@ -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{}
}
@@ -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{}
+5
View File
@@ -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)
+15
View File
@@ -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
View File
@@ -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 {