cgen: fix alias to sumtype cast initialization (fix #25086) (#25091)

This commit is contained in:
Felipe Pena 2025-08-12 04:18:56 -03:00 committed by GitHub
parent 9391b7c234
commit ec29f43a4d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 49 additions and 19 deletions

View file

@ -5587,7 +5587,17 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) {
} else if sym.info is ast.Alias && sym.info.parent_type.has_flag(.option) {
g.expr_with_opt(node.expr, expr_type, sym.info.parent_type)
} else {
g.write('(${cast_label}(')
g.write('(${cast_label}')
expr_typ := ast.mktyp(node.expr_type)
alias_to_sumtype := sym.info is ast.Alias
&& g.table.sumtype_has_variant(sym.info.parent_type, expr_typ, false)
if alias_to_sumtype {
expr_styp := g.styp(expr_typ)
g.write('{._${g.table.sym(expr_typ).cname}=memdup(ADDR(${expr_styp}, ')
g.expr(node.expr)
g.write('), sizeof(${expr_styp})),._typ=${int(expr_typ)}})')
} else {
g.write('(')
if node.expr is ast.Ident {
if !node.typ.is_ptr() && node.expr_type.is_ptr() && node.expr.obj is ast.Var
&& node.expr.obj.smartcasts.len > 0 {
@ -5611,6 +5621,7 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) {
g.write('))')
}
}
}
}
fn (mut g Gen) concat_expr(node ast.ConcatExpr) {

View file

@ -0,0 +1,19 @@
struct Foo {}
type Sum = int | string | Foo
type SumAlias = Sum
fn test_struct() {
a := SumAlias(Foo{})
assert '${a}' == 'SumAlias(Sum(Foo{}))'
}
fn test_int() {
a := SumAlias(0)
assert '${a}' == 'SumAlias(Sum(0))'
}
fn test_string() {
a := SumAlias('foo')
assert '${a}' == "SumAlias(Sum('foo'))"
}