From 68fb4e9fe56c977977de40ec89b29f3ff904b049 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 9 Dec 2022 17:56:38 +0800 Subject: [PATCH] cgen: fixevaluation order for match expressions inside boolean ones (fix #16554) (#16616) --- vlib/v/gen/c/match.v | 13 ++++++++ .../match_expr_skip_in_infix_expr_test.v | 33 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 vlib/v/tests/match_expr_skip_in_infix_expr_test.v diff --git a/vlib/v/gen/c/match.v b/vlib/v/gen/c/match.v index 4122972640..7ccf2a9c70 100644 --- a/vlib/v/gen/c/match.v +++ b/vlib/v/gen/c/match.v @@ -86,6 +86,11 @@ fn (mut g Gen) match_expr(node ast.MatchExpr) { cur_line = g.go_before_stmt(0).trim_left(' \t') tmp_var = g.new_tmp_var() g.writeln('${g.typ(node.return_type)} ${tmp_var} = ${g.type_default(node.return_type)};') + g.empty_line = true + if g.infix_left_var_name.len > 0 { + g.writeln('if (${g.infix_left_var_name}) {') + g.indent++ + } } if is_expr && !need_tmp_var { @@ -125,6 +130,14 @@ fn (mut g Gen) match_expr(node ast.MatchExpr) { } } g.set_current_pos_as_last_stmt_pos() + if need_tmp_var { + if g.infix_left_var_name.len > 0 { + g.writeln('') + g.indent-- + g.writeln('}') + g.set_current_pos_as_last_stmt_pos() + } + } g.write(cur_line) if need_tmp_var { g.write('${tmp_var}') diff --git a/vlib/v/tests/match_expr_skip_in_infix_expr_test.v b/vlib/v/tests/match_expr_skip_in_infix_expr_test.v new file mode 100644 index 0000000000..d9af14ad01 --- /dev/null +++ b/vlib/v/tests/match_expr_skip_in_infix_expr_test.v @@ -0,0 +1,33 @@ +fn test_match_expr_skip_in_infix_expr_1() { + mut a := false + b := a && match true { + true { + a = true + true + } + false { + false + } + } + println(a) + assert a == false + println(b) + assert b == false +} + +fn test_match_expr_skip_in_infix_expr_2() { + mut a := true + b := a || match true { + true { + a = false + true + } + false { + false + } + } + println(a) + assert a == true + println(b) + assert b == true +}