From 172e4ff853d4dd9c043a292271da821b2d62f98c Mon Sep 17 00:00:00 2001 From: Enzo Baldisserri Date: Wed, 13 May 2020 18:38:00 +0200 Subject: [PATCH] cgen: simplify if guard else clause --- vlib/v/gen/cgen.v | 10 ++-------- vlib/v/tests/option_test.v | 13 +++++++++++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 5054675cec..d943c106bb 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -1810,18 +1810,16 @@ fn (mut g Gen) if_expr(node ast.IfExpr) { g.write(')') g.inside_ternary-- } else { - guard_ok := g.new_tmp_var() mut is_guard := false for i, branch in node.branches { if i == 0 { match branch.cond { ast.IfGuardExpr { is_guard = true - g.writeln('bool $guard_ok;') g.write('{ /* if guard */ ${g.typ(it.expr_type)} $it.var_name = ') g.expr(it.expr) g.writeln(';') - g.writeln('if (($guard_ok = ${it.var_name}.ok)) {') + g.writeln('if (${it.var_name}.ok) {') } else { g.write('if (') @@ -1834,11 +1832,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) { g.expr(branch.cond) g.writeln(') {') } else if i == node.branches.len - 1 && node.has_else { - if is_guard { - g.writeln('} if (!$guard_ok) { /* else */') - } else { - g.writeln('} else {') - } + g.writeln('} else {') } // Assign ret value // if i == node.stmts.len - 1 && type_sym.kind != .void {} diff --git a/vlib/v/tests/option_test.v b/vlib/v/tests/option_test.v index 585898c0d6..976aecc3d7 100644 --- a/vlib/v/tests/option_test.v +++ b/vlib/v/tests/option_test.v @@ -60,6 +60,19 @@ fn test_if_opt() { assert 1 == 1 } +fn test_if_else_opt() { + if val := err_call(true) { + assert val == 42 + } else { + assert false + } + if _ := err_call(false) { + assert false + } else { + assert true + } +} + fn for_opt_default() ?string { return error('awww') }