ast, checker, cgen: fix array of sumtype initialisation with a default `init:` (#13178)
parent
7fe62a8b3e
commit
dfc23d939f
|
@ -1168,6 +1168,7 @@ pub:
|
|||
pub mut:
|
||||
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
|
||||
}
|
||||
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -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[]){')
|
||||
|
|
|
@ -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')]"
|
||||
}
|
Loading…
Reference in New Issue