From 04936b00c51b16ffa67d39664f0180b5cb71c03a Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 18 Dec 2022 09:22:06 -0300 Subject: [PATCH] cgen: fix struct selector with or block (#16695) --- vlib/v/gen/c/cgen.v | 7 ++++++ vlib/v/tests/struct_selector_or_block_test.v | 26 ++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 vlib/v/tests/struct_selector_or_block_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index f90424ae54..835f47c06e 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -3591,13 +3591,20 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) { } if node.or_block.kind != .absent && !g.is_assign_lhs && g.table.sym(node.typ).kind != .chan { + is_ptr := g.table.sym(g.unwrap_generic(node.expr_type)).kind in [.interface_, .sum_type] stmt_str := g.go_before_stmt(0).trim_space() styp := g.typ(node.typ) g.empty_line = true tmp_var := g.new_tmp_var() g.write('${styp} ${tmp_var} = ') + if is_ptr { + g.write('*(') + } g.expr(node.expr) g.write('.${node.field_name}') + if is_ptr { + g.write(')') + } g.or_block(tmp_var, node.or_block, node.typ) g.write(stmt_str) g.write(' ') diff --git a/vlib/v/tests/struct_selector_or_block_test.v b/vlib/v/tests/struct_selector_or_block_test.v new file mode 100644 index 0000000000..18269937bb --- /dev/null +++ b/vlib/v/tests/struct_selector_or_block_test.v @@ -0,0 +1,26 @@ +module main + +interface Greeting { + tt ?string +} + +struct Hello { + tt ?string = none + value string +} + +struct Hi { + tt ?string = none +} + +fn greet(g Greeting) string { + // Problematic piece of code here + // If I leave it unchecked, the compiler complains (as expected) + t := g.tt or { 'UNKNOWN' } + return t +} + +fn test_main() { + assert greet(Hello{}) == 'UNKNOWN' + assert greet(Hello{'cool', ''}) == 'cool' +}