Skip to content

Commit

Permalink
cgen: fix struct init with embed field update (#13444)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Feb 12, 2022
1 parent 7178367 commit ae0e90f
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions vlib/v/ast/ast.v
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions vlib/v/gen/c/cgen.v
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
32 changes: 32 additions & 0 deletions vlib/v/tests/struct_init_with_embed_update_test.v
@@ -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}
}

0 comments on commit ae0e90f

Please sign in to comment.