From 3e02cfd5280311c8c81e924f77b9fb740b19972b Mon Sep 17 00:00:00 2001 From: 05st <60903484+05st@users.noreply.github.com> Date: Mon, 11 Oct 2021 06:17:04 -0500 Subject: [PATCH] cgen: fix `in` op usage on array of sumtypes without cast (#12141) --- vlib/v/gen/c/infix_expr.v | 16 ++++++++++++++++ vlib/v/tests/in_expression_test.v | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/vlib/v/gen/c/infix_expr.v b/vlib/v/gen/c/infix_expr.v index bb52d57c29..82900e4e30 100644 --- a/vlib/v/gen/c/infix_expr.v +++ b/vlib/v/gen/c/infix_expr.v @@ -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(') diff --git a/vlib/v/tests/in_expression_test.v b/vlib/v/tests/in_expression_test.v index 63a3730a63..ec631b834b 100644 --- a/vlib/v/tests/in_expression_test.v +++ b/vlib/v/tests/in_expression_test.v @@ -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 }