1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix another error for 'in array of sumtype' (#14448)

This commit is contained in:
yuyi 2022-05-18 19:39:35 +08:00 committed by GitHub
parent f2447a4bd8
commit 4cbfa884c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 4 deletions

View File

@ -402,11 +402,25 @@ fn (mut g Gen) infix_expr_in_op(node ast.InfixExpr) {
}
}
if node.right is ast.ArrayInit {
elem_type := node.right.elem_type
elem_sym := g.table.sym(elem_type)
if node.right.exprs.len > 0 {
// `a in [1,2,3]` optimization => `a == 1 || a == 2 || a == 3`
// avoids an allocation
g.write('(')
g.infix_expr_in_optimization(node.left, node.right)
if elem_sym.kind == .sum_type && left.sym.kind != .sum_type {
if node.left_type in elem_sym.sumtype_info().variants {
new_node_left := ast.CastExpr{
arg: ast.EmptyExpr{}
typ: elem_type
expr: node.left
expr_type: node.left_type
}
g.infix_expr_in_optimization(new_node_left, node.right)
}
} else {
g.infix_expr_in_optimization(node.left, node.right)
}
g.write(')')
return
}

View File

@ -312,7 +312,10 @@ fn test_in_alias_array() {
type TokenValue = rune | u64
fn test_in_array_of_sumtype() {
val := TokenValue(`+`)
assert val in [TokenValue(`+`), TokenValue(`-`)]
fn test_in_array_literal_of_sumtype() {
val1 := TokenValue(`+`)
assert val1 in [TokenValue(`+`), TokenValue(`-`)]
val2 := `+`
assert val2 in [TokenValue(`+`), TokenValue(`-`)]
}