Skip to content

Commit 9cd1bce

Browse files
authored
cgen: fix array of sumtype initialization with var string (fix #23429) (#23432)
1 parent 7aca8b6 commit 9cd1bce

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

vlib/v/gen/c/array.v

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ fn (mut g Gen) array_init(node ast.ArrayInit, var_name string) {
2323
g.write('HEAP(${array_styp}, ')
2424
}
2525
len := node.exprs.len
26+
elem_sym := g.table.sym(g.unwrap_generic(node.elem_type))
2627
if array_type.unaliased_sym.kind == .array_fixed {
2728
g.fixed_array_init(node, array_type, var_name, is_amp)
2829
if is_amp {
@@ -44,12 +45,17 @@ fn (mut g Gen) array_init(node ast.ArrayInit, var_name string) {
4445
g.writeln('')
4546
g.write('\t\t')
4647
}
48+
is_sumtype := elem_sym.kind == .sum_type
4749
for i, expr in node.exprs {
4850
if node.expr_types[i] == ast.string_type
4951
&& expr !in [ast.IndexExpr, ast.CallExpr, ast.StringLiteral, ast.StringInterLiteral, ast.InfixExpr] {
50-
g.write('string_clone(')
51-
g.expr(expr)
52-
g.write(')')
52+
if is_sumtype {
53+
g.expr_with_cast(expr, node.expr_types[i], node.elem_type)
54+
} else {
55+
g.write('string_clone(')
56+
g.expr(expr)
57+
g.write(')')
58+
}
5359
} else {
5460
if node.elem_type.has_flag(.option) {
5561
g.expr_with_opt(expr, node.expr_types[i], node.elem_type)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
type SumFoo = int | string
2+
3+
struct Foo {
4+
bar []SumFoo
5+
}
6+
7+
struct Bar {
8+
foo []Foo
9+
}
10+
11+
fn test_main() {
12+
str := 'foobar'
13+
f := Bar{
14+
foo: [Foo{
15+
bar: [str]
16+
}]
17+
}
18+
assert f.foo.len == 1
19+
assert f.foo[0].bar.len == 1
20+
assert f.foo[0].bar[0] as string == str
21+
}

0 commit comments

Comments
 (0)