Skip to content

Commit 01c358d

Browse files
committed
Fix type checker for "in" operator
Fixes #426
1 parent 6001a17 commit 01c358d

File tree

4 files changed

+30
-11
lines changed

4 files changed

+30
-11
lines changed

checker/checker.go

+2-11
Original file line numberDiff line numberDiff line change
@@ -242,16 +242,7 @@ func (v *checker) BinaryNode(node *ast.BinaryNode) (reflect.Type, info) {
242242

243243
switch node.Operator {
244244
case "==", "!=":
245-
if isNumber(l) && isNumber(r) {
246-
return boolType, info{}
247-
}
248-
if l == nil || r == nil { // It is possible to compare with nil.
249-
return boolType, info{}
250-
}
251-
if l.Kind() == r.Kind() {
252-
return boolType, info{}
253-
}
254-
if isAny(l) || isAny(r) {
245+
if isComparable(l, r) {
255246
return boolType, info{}
256247
}
257248

@@ -357,7 +348,7 @@ func (v *checker) BinaryNode(node *ast.BinaryNode) (reflect.Type, info) {
357348
if l == nil { // It is possible to compare with nil.
358349
return boolType, info{}
359350
}
360-
if !isAny(l) && !l.AssignableTo(r.Elem()) && !(isInteger(l) && isInteger(r.Elem())) {
351+
if !isComparable(l, r.Elem()) {
361352
return v.error(node, "cannot use %v as type %v in array", l, r.Elem())
362353
}
363354
return boolType, info{}

checker/checker_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,11 @@ cannot use float64 as type int in map key (1:5)
513513
| 1/2 in MapIntAny
514514
| ....^
515515
516+
0.5 in ArrayOfFoo
517+
cannot use float64 as type *mock.Foo in array (1:5)
518+
| 0.5 in ArrayOfFoo
519+
| ....^
520+
516521
repeat("0", 1/0)
517522
cannot use float64 as argument (type int) to call repeat (1:14)
518523
| repeat("0", 1/0)

checker/types.go

+15
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,18 @@ func kind(t reflect.Type) reflect.Kind {
227227
}
228228
return t.Kind()
229229
}
230+
231+
func isComparable(l, r reflect.Type) bool {
232+
if l == nil || r == nil {
233+
return true
234+
}
235+
switch {
236+
case l.Kind() == r.Kind():
237+
return true
238+
case isNumber(l) && isNumber(r):
239+
return true
240+
case isAny(l) || isAny(r):
241+
return true
242+
}
243+
return false
244+
}

expr_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -1084,6 +1084,14 @@ func TestExpr(t *testing.T) {
10841084
`4/2 == 2`,
10851085
true,
10861086
},
1087+
{
1088+
`.5 in 0..1`,
1089+
false,
1090+
},
1091+
{
1092+
`.5 in ArrayOfInt`,
1093+
false,
1094+
},
10871095
}
10881096

10891097
for _, tt := range tests {

0 commit comments

Comments
 (0)