From e6a4f76f82d097548cfdf2962aeb1127c9857c29 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 29 Jan 2023 10:59:13 -0300 Subject: [PATCH] cgen: fix returing comptime if expressions within functions with an option result (#17154) --- vlib/v/gen/c/comptime.v | 25 ++++++++++++++++--- vlib/v/tests/ifexpr_with_option_result_test.v | 11 ++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 vlib/v/tests/ifexpr_with_option_result_test.v diff --git a/vlib/v/gen/c/comptime.v b/vlib/v/gen/c/comptime.v index 6051bc4ebc..371a419bd0 100644 --- a/vlib/v/gen/c/comptime.v +++ b/vlib/v/gen/c/comptime.v @@ -285,6 +285,7 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) { } } tmp_var := g.new_tmp_var() + is_opt_or_result := node.typ.has_flag(.option) || node.typ.has_flag(.result) line := if node.is_expr { stmt_str := g.go_before_stmt(0) g.write(util.tabs(g.indent)) @@ -339,8 +340,16 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) { g.set_current_pos_as_last_stmt_pos() prev_skip_stmt_pos := g.skip_stmt_pos g.skip_stmt_pos = true - g.write('\t${tmp_var} = ') - g.stmt(last) + if is_opt_or_result { + tmp_var2 := g.new_tmp_var() + g.write('{ ${g.base_type(node.typ)} ${tmp_var2} = ') + g.stmt(last) + g.writeln('_result_ok(&(${g.base_type(node.typ)}[]) { ${tmp_var2} }, (_result*)(&${tmp_var}), sizeof(${g.base_type(node.typ)}));') + g.writeln('}') + } else { + g.write('\t${tmp_var} = ') + g.stmt(last) + } g.skip_stmt_pos = prev_skip_stmt_pos g.writeln(';') g.writeln('}') @@ -350,8 +359,16 @@ fn (mut g Gen) comptime_if(node ast.IfExpr) { g.set_current_pos_as_last_stmt_pos() prev_skip_stmt_pos := g.skip_stmt_pos g.skip_stmt_pos = true - g.write('${tmp_var} = ') - g.stmt(last) + if is_opt_or_result { + tmp_var2 := g.new_tmp_var() + g.write('{ ${g.base_type(node.typ)} ${tmp_var2} = ') + g.stmt(last) + g.writeln('_result_ok(&(${g.base_type(node.typ)}[]) { ${tmp_var2} }, (_result*)(&${tmp_var}), sizeof(${g.base_type(node.typ)}));') + g.writeln('}') + } else { + g.write('${tmp_var} = ') + g.stmt(last) + } g.skip_stmt_pos = prev_skip_stmt_pos g.writeln(';') g.indent-- diff --git a/vlib/v/tests/ifexpr_with_option_result_test.v b/vlib/v/tests/ifexpr_with_option_result_test.v new file mode 100644 index 0000000000..b88f671109 --- /dev/null +++ b/vlib/v/tests/ifexpr_with_option_result_test.v @@ -0,0 +1,11 @@ +fn comptime_ret_result() !string { + return $if debug { + 'debug' + } $else { + 'not debug' + } +} + +fn test_main() { + assert comptime_ret_result()? == 'not debug' +}