ast, checker, cgen: fix array of sumtype initialisation with a default `init:` (#13178)

pull/13180/head
yuyi 2022-01-15 15:59:38 +08:00 committed by GitHub
parent 7fe62a8b3e
commit dfc23d939f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 17 additions and 4 deletions

View File

@ -1166,9 +1166,10 @@ pub:
has_default bool
has_it bool // true if temp variable it is used
pub mut:
expr_types []Type // [Dog, Cat] // also used for interface_types
elem_type Type // element type
typ Type // array type
expr_types []Type // [Dog, Cat] // also used for interface_types
elem_type Type // element type
default_type Type // default value type
typ Type // array type
}
pub struct ArrayDecompose {

View File

@ -20,6 +20,7 @@ pub fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
if node.has_default {
default_expr := node.default_expr
default_typ := c.check_expr_opt_call(default_expr, c.expr(default_expr))
node.default_type = default_typ
c.check_expected(default_typ, node.elem_type) or {
c.error(err.msg, default_expr.position())
}

View File

@ -213,7 +213,7 @@ fn (mut g Gen) array_init(node ast.ArrayInit) {
g.write('}[0])')
} else if node.has_default {
g.write('&($elem_styp[]){')
g.expr(node.default_expr)
g.expr_with_cast(node.default_expr, node.default_type, node.elem_type)
g.write('})')
} else if node.has_len && node.elem_type == ast.string_type {
g.write('&($elem_styp[]){')

View File

@ -0,0 +1,11 @@
type Abc = int | string
fn test_array_of_sumtype_with_default() {
a1 := []Abc{len: 1, init: 22}
println(a1)
assert '$a1' == '[Abc(22)]'
a2 := []Abc{len: 1, init: 'hello'}
println(a2)
assert '$a2' == "[Abc('hello')]"
}