Skip to content

Commit ec29f43

Browse files
authored
cgen: fix alias to sumtype cast initialization (fix #25086) (#25091)
1 parent 9391b7c commit ec29f43

2 files changed

Lines changed: 47 additions & 17 deletions

File tree

‎vlib/v/gen/c/cgen.v‎

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5587,28 +5587,39 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) {
55875587
} else if sym.info is ast.Alias && sym.info.parent_type.has_flag(.option) {
55885588
g.expr_with_opt(node.expr, expr_type, sym.info.parent_type)
55895589
} else {
5590-
g.write('(${cast_label}(')
5591-
if node.expr is ast.Ident {
5592-
if !node.typ.is_ptr() && node.expr_type.is_ptr() && node.expr.obj is ast.Var
5593-
&& node.expr.obj.smartcasts.len > 0 {
5594-
g.write('*'.repeat(node.expr_type.nr_muls()))
5590+
g.write('(${cast_label}')
5591+
expr_typ := ast.mktyp(node.expr_type)
5592+
alias_to_sumtype := sym.info is ast.Alias
5593+
&& g.table.sumtype_has_variant(sym.info.parent_type, expr_typ, false)
5594+
if alias_to_sumtype {
5595+
expr_styp := g.styp(expr_typ)
5596+
g.write('{._${g.table.sym(expr_typ).cname}=memdup(ADDR(${expr_styp}, ')
5597+
g.expr(node.expr)
5598+
g.write('), sizeof(${expr_styp})),._typ=${int(expr_typ)}})')
5599+
} else {
5600+
g.write('(')
5601+
if node.expr is ast.Ident {
5602+
if !node.typ.is_ptr() && node.expr_type.is_ptr() && node.expr.obj is ast.Var
5603+
&& node.expr.obj.smartcasts.len > 0 {
5604+
g.write('*'.repeat(node.expr_type.nr_muls()))
5605+
}
55955606
}
5596-
}
5597-
if sym.kind == .alias && g.table.final_sym(node.typ).kind == .string {
5598-
ptr_cnt := node.typ.nr_muls() - expr_type.nr_muls()
5599-
if ptr_cnt > 0 {
5600-
g.write('&'.repeat(ptr_cnt))
5607+
if sym.kind == .alias && g.table.final_sym(node.typ).kind == .string {
5608+
ptr_cnt := node.typ.nr_muls() - expr_type.nr_muls()
5609+
if ptr_cnt > 0 {
5610+
g.write('&'.repeat(ptr_cnt))
5611+
}
56015612
}
5602-
}
5603-
g.expr(node.expr)
5604-
if node.expr is ast.IntegerLiteral {
5605-
if node_typ in [ast.u64_type, ast.u32_type, ast.u16_type] {
5606-
if !node.expr.val.starts_with('-') {
5607-
g.write('U')
5613+
g.expr(node.expr)
5614+
if node.expr is ast.IntegerLiteral {
5615+
if node_typ in [ast.u64_type, ast.u32_type, ast.u16_type] {
5616+
if !node.expr.val.starts_with('-') {
5617+
g.write('U')
5618+
}
56085619
}
56095620
}
5621+
g.write('))')
56105622
}
5611-
g.write('))')
56125623
}
56135624
}
56145625
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
struct Foo {}
2+
3+
type Sum = int | string | Foo
4+
type SumAlias = Sum
5+
6+
fn test_struct() {
7+
a := SumAlias(Foo{})
8+
assert '${a}' == 'SumAlias(Sum(Foo{}))'
9+
}
10+
11+
fn test_int() {
12+
a := SumAlias(0)
13+
assert '${a}' == 'SumAlias(Sum(0))'
14+
}
15+
16+
fn test_string() {
17+
a := SumAlias('foo')
18+
assert '${a}' == "SumAlias(Sum('foo'))"
19+
}

0 commit comments

Comments
 (0)