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,28 +5587,39 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) {
} else if sym.info is ast.Alias && sym.info.parent_type.has_flag(.option) { } 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) g.expr_with_opt(node.expr, expr_type, sym.info.parent_type)
} else { } else {
g.write('(${cast_label}(') g.write('(${cast_label}')
if node.expr is ast.Ident { expr_typ := ast.mktyp(node.expr_type)
if !node.typ.is_ptr() && node.expr_type.is_ptr() && node.expr.obj is ast.Var alias_to_sumtype := sym.info is ast.Alias
&& node.expr.obj.smartcasts.len > 0 { && g.table.sumtype_has_variant(sym.info.parent_type, expr_typ, false)
g.write('*'.repeat(node.expr_type.nr_muls())) if alias_to_sumtype {
} expr_styp := g.styp(expr_typ)
} g.write('{._${g.table.sym(expr_typ).cname}=memdup(ADDR(${expr_styp}, ')
if sym.kind == .alias && g.table.final_sym(node.typ).kind == .string { g.expr(node.expr)
ptr_cnt := node.typ.nr_muls() - expr_type.nr_muls() g.write('), sizeof(${expr_styp})),._typ=${int(expr_typ)}})')
if ptr_cnt > 0 { } else {
g.write('&'.repeat(ptr_cnt)) g.write('(')
} if node.expr is ast.Ident {
} if !node.typ.is_ptr() && node.expr_type.is_ptr() && node.expr.obj is ast.Var
g.expr(node.expr) && node.expr.obj.smartcasts.len > 0 {
if node.expr is ast.IntegerLiteral { g.write('*'.repeat(node.expr_type.nr_muls()))
if node_typ in [ast.u64_type, ast.u32_type, ast.u16_type] {
if !node.expr.val.starts_with('-') {
g.write('U')
} }
} }
if sym.kind == .alias && g.table.final_sym(node.typ).kind == .string {
ptr_cnt := node.typ.nr_muls() - expr_type.nr_muls()
if ptr_cnt > 0 {
g.write('&'.repeat(ptr_cnt))
}
}
g.expr(node.expr)
if node.expr is ast.IntegerLiteral {
if node_typ in [ast.u64_type, ast.u32_type, ast.u16_type] {
if !node.expr.val.starts_with('-') {
g.write('U')
}
}
}
g.write('))')
} }
g.write('))')
} }
} }
} }

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'))"
}