checker: fix error for array of sumtype init (#13501)

pull/13509/head
yuyi 2022-02-18 17:47:24 +08:00 committed by GitHub
parent 072480352c
commit 14073ac0fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 1 deletions

View File

@ -71,11 +71,15 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
if node.exprs.len > 0 && node.elem_type == ast.void_type { if node.exprs.len > 0 && node.elem_type == ast.void_type {
mut expected_value_type := ast.void_type mut expected_value_type := ast.void_type
mut expecting_interface_array := false mut expecting_interface_array := false
mut expecting_sumtype_array := false
if c.expected_type != 0 { if c.expected_type != 0 {
expected_value_type = c.table.value_type(c.expected_type) expected_value_type = c.table.value_type(c.expected_type)
if c.table.sym(expected_value_type).kind == .interface_ { expected_value_sym := c.table.sym(expected_value_type)
if expected_value_sym.kind == .interface_ {
// Array of interfaces? (`[dog, cat]`) Save the interface type (`Animal`) // Array of interfaces? (`[dog, cat]`) Save the interface type (`Animal`)
expecting_interface_array = true expecting_interface_array = true
} else if expected_value_sym.kind == .sum_type {
expecting_sumtype_array = true
} }
} }
// expecting_interface_array := c.expected_type != 0 && // expecting_interface_array := c.expected_type != 0 &&
@ -104,6 +108,11 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
} }
} }
continue continue
} else if expecting_sumtype_array {
if i == 0 {
elem_type = expected_value_type
}
continue
} }
// The first element's type // The first element's type
if i == 0 { if i == 0 {

View File

@ -0,0 +1,25 @@
pub type MenuItem = Action | Group | Separater
pub struct Group {
children []MenuItem
}
pub struct Separater {}
pub struct Action {}
fn test_array_of_sumtype_init() {
g := Group{
children: [
Action{},
Separater{},
Group{
children: [
Action{},
]
},
]
}
println(g)
assert g.children.len == 3
}