Skip to content

Commit

Permalink
parser, checker, cgen: fix anon struct with default expr (#19257)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Sep 1, 2023
1 parent 13fd549 commit 5848610
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
4 changes: 4 additions & 0 deletions vlib/v/checker/struct.v
Expand Up @@ -93,6 +93,10 @@ fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
}
}
}
// check anon struct declaration
if field.anon_struct_decl.fields.len > 0 {
c.struct_decl(mut field.anon_struct_decl)
}
}
c.expected_type = old_expected_type
util.timing_measure_cumulative('Checker.struct setting default_expr_typ')
Expand Down
3 changes: 1 addition & 2 deletions vlib/v/gen/c/struct.v
Expand Up @@ -333,7 +333,7 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
break
}
}
if has_option_field {
if has_option_field || field.anon_struct_decl.fields.len > 0 {
default_init := ast.StructInit{
typ: field.typ
}
Expand Down Expand Up @@ -379,7 +379,6 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
tmp_var)
return true
}

g.expr(field.default_expr)
} else if field.typ.has_flag(.option) {
tmp_var := g.new_tmp_var()
Expand Down
3 changes: 2 additions & 1 deletion vlib/v/parser/struct.v
Expand Up @@ -314,7 +314,6 @@ fn (mut p Parser) struct_decl(is_anon bool) ast.StructDecl {
is_deprecated: is_field_deprecated
anon_struct_decl: p.anon_struct_decl
}
p.anon_struct_decl = ast.StructDecl{}
}
// save embeds as table fields too, it will be used in generation phase
fields << ast.StructField{
Expand All @@ -333,7 +332,9 @@ fn (mut p Parser) struct_decl(is_anon bool) ast.StructDecl {
is_global: is_field_global
is_volatile: is_field_volatile
is_deprecated: is_field_deprecated
anon_struct_decl: p.anon_struct_decl
}
p.anon_struct_decl = ast.StructDecl{}
p.attrs = prev_attrs
i++
}
Expand Down
15 changes: 15 additions & 0 deletions vlib/v/tests/anon_struct_with_default_expr_test.v
@@ -0,0 +1,15 @@
struct Bar {
anon struct {
foofoo Foo = Foo{'foofoo'}
}
}

struct Foo {
name string
}

fn test_anon_struct_with_default_expr() {
bar := Bar{}
println(bar.anon.foofoo.name)
assert bar.anon.foofoo.name == 'foofoo'
}

0 comments on commit 5848610

Please sign in to comment.