From 9e351516fea0f3865e4408f7acf93158fd22a38a Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sat, 13 Jun 2026 08:17:00 +0300 Subject: [PATCH] cgen: fix option sumtype if expr struct init (#27443) --- vlib/v/gen/c/cgen.v | 6 ++- ...option_sumtype_if_expr_struct_field_test.v | 47 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/options/option_sumtype_if_expr_struct_field_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index a3dcebf29..83d7b17ff 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -6576,11 +6576,13 @@ fn (mut g Gen) expr(node_ ast.Expr) { g.expr(g.table.resolve_init(node, g.unwrap_generic(node.typ))) } else { // `user := User{name: 'Bob'}` + old_inside_struct_init := g.inside_struct_init + old_cur_struct_init_typ := g.cur_struct_init_typ g.inside_struct_init = true g.cur_struct_init_typ = node.typ g.struct_init(node) - g.cur_struct_init_typ = 0 - g.inside_struct_init = false + g.cur_struct_init_typ = old_cur_struct_init_typ + g.inside_struct_init = old_inside_struct_init } } ast.TypeNode { diff --git a/vlib/v/tests/options/option_sumtype_if_expr_struct_field_test.v b/vlib/v/tests/options/option_sumtype_if_expr_struct_field_test.v new file mode 100644 index 000000000..78b1fd34f --- /dev/null +++ b/vlib/v/tests/options/option_sumtype_if_expr_struct_field_test.v @@ -0,0 +1,47 @@ +struct Circle27440 { + radius int +} + +struct Square27440 { + size int +} + +type Shape27440 = Circle27440 | Square27440 + +struct Box27440 { + shape ?Shape27440 +} + +fn new_box27440(use_circle bool, n int) Box27440 { + return Box27440{ + shape: if use_circle { + Shape27440(Circle27440{ + radius: n + }) + } else { + Shape27440(Square27440{ + size: n + }) + } + } +} + +fn test_option_sumtype_if_expr_struct_field() { + circle_box := new_box27440(true, 4) + circle_shape := circle_box.shape or { + assert false + return + } + + assert circle_shape is Circle27440 + assert circle_shape.radius == 4 + + square_box := new_box27440(false, 5) + square_shape := square_box.shape or { + assert false + return + } + + assert square_shape is Square27440 + assert square_shape.size == 5 +} -- 2.39.5