From bd21ec396cd5e2ff334118267d328f45545c8054 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 8 May 2022 01:20:00 +0800 Subject: [PATCH] cgen: fix error for if cond with optional expr (#14334) --- vlib/v/gen/c/cgen.v | 4 +-- vlib/v/tests/if_cond_with_optional_test.v | 43 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/if_cond_with_optional_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 9c155f027f..603aa77855 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -5133,9 +5133,7 @@ fn (mut g Gen) or_block(var_name string, or_block ast.OrExpr, return_type ast.Ty g.inside_opt_data = true g.expr_with_cast(expr_stmt.expr, expr_stmt.typ, return_type.clear_flag(.optional)) g.inside_opt_data = old_inside_opt_data - if g.inside_ternary == 0 { - g.writeln(';') - } + g.writeln(';') g.stmt_path_pos.delete_last() } else { g.stmt(stmt) diff --git a/vlib/v/tests/if_cond_with_optional_test.v b/vlib/v/tests/if_cond_with_optional_test.v new file mode 100644 index 0000000000..860478abce --- /dev/null +++ b/vlib/v/tests/if_cond_with_optional_test.v @@ -0,0 +1,43 @@ +module main + +import rand + +interface Sample { +mut: + get_next() int +} + +struct SampleA { +mut: + state int +} + +fn (mut sample SampleA) get_next() int { + sample.state++ + return sample.state +} + +struct SampleB { +mut: + state int = 1 +} + +fn (mut sample SampleB) get_next() int { + sample.state += 2 + return sample.state +} + +fn create_sampler() Sample { + return if rand.intn(1) or { 0 } == 0 { Sample(SampleA{}) } else { Sample(SampleB{}) } +} + +fn test_if_cond_with_optional() { + mut sample := create_sampler() + mut ret := sample.get_next() + println(ret) + assert ret == 1 + + ret = sample.get_next() + println(ret) + assert ret == 2 +}