cgen: fix struct init with embed field update (#13444)

pull/13450/head
yuyi 2022-02-12 13:16:51 +08:00 committed by GitHub
parent 7178367de0
commit ae0e90f5d8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 0 deletions

View File

@ -409,6 +409,7 @@ pub mut:
update_expr Expr
update_expr_type Type
update_expr_comments []Comment
is_update_embed bool
has_update_expr bool
fields []StructInitField
embeds []StructInitEmbed

View File

@ -5456,6 +5456,7 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
default_init := ast.StructInit{
...node
typ: embed
is_update_embed: true
fields: init_fields_to_embed
}
inside_cast_in_heap := g.inside_cast_in_heap
@ -5557,6 +5558,16 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
} else {
g.write('.')
}
if node.is_update_embed {
embed_sym := g.table.sym(node.typ)
embed_name := embed_sym.embed_name()
g.write(embed_name)
if node.typ.is_ptr() {
g.write('->')
} else {
g.write('.')
}
}
g.write(field.name)
} else {
if !g.zero_struct_field(field) {

View File

@ -0,0 +1,32 @@
struct Button {
width int
height int
}
enum Color {
red
blue
yellow
}
struct ColoredButton {
Button
color Color
}
fn change_color(cb ColoredButton, color Color) ColoredButton {
return ColoredButton{
...cb
color: color
}
}
fn test_struct_update_with_embed_field() {
red_button := ColoredButton{Button{100, 100}, .red}
blue_button := change_color(red_button, .blue)
println(red_button)
println(blue_button)
assert blue_button == ColoredButton{Button{100, 100}, .blue}
}