cgen: fix `in` op usage on array of sumtypes without cast (#12141)

pull/12153/head
05st 2021-10-11 06:17:04 -05:00 committed by GitHub
parent ceb24bc32e
commit 3e02cfd528
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -394,6 +394,22 @@ fn (mut g Gen) infix_expr_in_op(node ast.InfixExpr) {
return
}
}
if right.sym.info is ast.Array {
elem_type := right.sym.info.elem_type
elem_type_ := g.unwrap(elem_type)
if elem_type_.sym.kind == .sum_type {
if node.left_type in elem_type_.sym.sumtype_info().variants {
new_node_left := ast.CastExpr{
arg: ast.EmptyExpr{}
typ: elem_type
expr: node.left
expr_type: node.left_type
}
g.gen_array_contains(node.right_type, node.right, new_node_left)
return
}
}
}
g.gen_array_contains(node.right_type, node.right, node.left)
} else if right.unaliased_sym.kind == .map {
g.write('_IN_MAP(')

View File

@ -280,4 +280,10 @@ fn test_in_sumtype_array() {
println(foo)
assert true
}
// without sumtype cast
mut foos := []Foo{}
foos << Foo1{}
assert Foo1{} in foos
assert Foo2{} !in foos
}