From 2b86243e12fe45d75d84ba113944baa68cd6f789 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sun, 1 Feb 2026 23:03:16 +0200 Subject: [PATCH] cgen: fix generation of struct initialisers for structs with option fields, inside ternaries (fix #26476) (#26493) --- vlib/v/gen/c/cgen.v | 6 ++- vlib/v/gen/c/struct.v | 4 +- ...it_inside_ternary_with_option_field_test.v | 46 +++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/structs/struct_init_inside_ternary_with_option_field_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 715ba0bec..96a1f7719 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2374,7 +2374,11 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T g.assign_op = assign_op } g.assign_op = .unknown - stmt_str := g.go_before_last_stmt().trim_space() + stmt_str := if g.inside_ternary > 0 { + g.go_before_ternary().trim_space() + } else { + g.go_before_last_stmt().trim_space() + } mut styp := g.base_type(ret_typ) g.empty_line = true final_expr_sym := g.table.final_sym(expr_typ) diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 6252b0581..1b4c9bb7e 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -14,7 +14,7 @@ fn (mut g Gen) struct_init(node ast.StructInit) { is_update_tmp_var = true tmp_update_var = g.new_tmp_var() - s := g.go_before_last_stmt() + s := if g.inside_ternary > 0 { g.go_before_ternary() } else { g.go_before_last_stmt() } g.empty_line = true styp := g.styp(node.update_expr_type) @@ -121,7 +121,7 @@ fn (mut g Gen) struct_init(node ast.StructInit) { } } else if node.typ.has_flag(.option) { tmp_var := g.new_tmp_var() - s := g.go_before_last_stmt() + s := if g.inside_ternary > 0 { g.go_before_ternary() } else { g.go_before_last_stmt() } g.empty_line = true base_styp := g.styp(node.typ.clear_option_and_result()) diff --git a/vlib/v/tests/structs/struct_init_inside_ternary_with_option_field_test.v b/vlib/v/tests/structs/struct_init_inside_ternary_with_option_field_test.v new file mode 100644 index 000000000..79991c3a2 --- /dev/null +++ b/vlib/v/tests/structs/struct_init_inside_ternary_with_option_field_test.v @@ -0,0 +1,46 @@ +pub struct Color { +pub mut: + r u8 + g u8 + b u8 + a u8 = 255 +} + +pub const color_transparent = Color{0, 0, 0, 0} + +pub struct MarkdownStyle { +pub: + table_row_alt ?Color +} + +pub struct MarkdownCfg { +pub: + id string + style MarkdownStyle +} + +struct AResult { + x int +} + +struct App { + mode bool +} + +fn (app App) method(params MarkdownCfg) AResult { + return AResult{123} +} + +fn another_fn() AResult { + return AResult{456} +} + +fn test_main() { + app := App{} + x := if app.mode { + [app.method(id: 'abc')] + } else { + [another_fn()] + } + assert x == [AResult{456}] +} -- 2.39.5