From d3b380b48b8b49bdf22a7750023af40f975c087e Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 10 Oct 2024 17:23:28 +0800 Subject: [PATCH] cgen: fix option if expr with noreturn fn call (fix #22467) (#22470) --- vlib/v/gen/c/cgen.v | 22 ++++++++++++++----- .../option_if_expr_with_panic_call_test.v | 10 +++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) create mode 100644 vlib/v/tests/options/option_if_expr_with_panic_call_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 08404d918572f0..e3b189ab6a9056 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1926,9 +1926,14 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool { g.fn_decl.return_type.clear_flag(.option) } styp = g.base_type(ret_typ) - g.write('_option_ok(&(${styp}[]) { ') - g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) - g.writeln(' }, (${option_name}*)(&${tmp_var}), sizeof(${styp}));') + if stmt.expr is ast.CallExpr && stmt.expr.is_noreturn { + g.expr(stmt.expr) + g.writeln(';') + } else { + g.write('_option_ok(&(${styp}[]) { ') + g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) + g.writeln(' }, (${option_name}*)(&${tmp_var}), sizeof(${styp}));') + } } } } @@ -1958,9 +1963,14 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool { } else { ret_typ := g.fn_decl.return_type.clear_flag(.result) styp = g.base_type(ret_typ) - g.write('_result_ok(&(${styp}[]) { ') - g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) - g.writeln(' }, (${result_name}*)(&${tmp_var}), sizeof(${styp}));') + if stmt.expr is ast.CallExpr && stmt.expr.is_noreturn { + g.expr(stmt.expr) + g.writeln(';') + } else { + g.write('_result_ok(&(${styp}[]) { ') + g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) + g.writeln(' }, (${result_name}*)(&${tmp_var}), sizeof(${styp}));') + } } } } diff --git a/vlib/v/tests/options/option_if_expr_with_panic_call_test.v b/vlib/v/tests/options/option_if_expr_with_panic_call_test.v new file mode 100644 index 00000000000000..9121a2401f8462 --- /dev/null +++ b/vlib/v/tests/options/option_if_expr_with_panic_call_test.v @@ -0,0 +1,10 @@ +fn test_option_if_expr_with_panic_call() { + mut x := ?string(none) + x = if true { + '' + } else { + panic('') + } + println(x) + assert true +}