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

yuyi 2022-05-18 19:39:35 +08:00 committed by Jef Roosens
parent a1bd9acf82
commit 09886f78d3
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
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(`-`)]
}