From b9a8a210943d663db0cb8f663640cc5303c70c07 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 28 Feb 2023 20:02:17 +0800 Subject: [PATCH] cgen: fix nested option struct init (fix #17415) (#17425) --- vlib/v/gen/c/struct.v | 23 +++++++++++++++---- vlib/v/tests/nested_option_struct_init_test.v | 16 +++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 vlib/v/tests/nested_option_struct_init_test.v diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 490d3f41fe..b488573d6d 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -306,13 +306,28 @@ fn (mut g Gen) struct_init(node ast.StructInit) { fn (mut g Gen) zero_struct_field(field ast.StructField) bool { sym := g.table.sym(field.typ) - if sym.kind == .struct_ { - info := sym.info as ast.Struct - if info.fields.len == 0 { + field_name := if sym.language == .v { c_name(field.name) } else { field.name } + if sym.info is ast.Struct { + if sym.info.fields.len == 0 { return false + } else if !field.has_default_expr { + mut has_option_field := false + for fd in sym.info.fields { + if fd.typ.has_flag(.option) { + has_option_field = true + break + } + } + if has_option_field { + default_init := ast.StructInit{ + typ: field.typ + } + g.write('.${field_name} = ') + g.struct_init(default_init) + return true + } } } - field_name := if sym.language == .v { c_name(field.name) } else { field.name } g.write('.${field_name} = ') if field.has_default_expr { if sym.kind in [.sum_type, .interface_] { diff --git a/vlib/v/tests/nested_option_struct_init_test.v b/vlib/v/tests/nested_option_struct_init_test.v new file mode 100644 index 0000000000..c975cc2e9b --- /dev/null +++ b/vlib/v/tests/nested_option_struct_init_test.v @@ -0,0 +1,16 @@ +struct Data { + a ?int + b ?int = 1 +} + +struct Data2 { + d Data +} + +fn test_nested_option_struct_init() { + d2 := Data2{} + println(d2) + assert d2.d.a == none + assert d2.d.b != none + assert d2.d.b? == 1 +}