From 968e3107931552e324d6e143a000f4c6577a5562 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sat, 7 Mar 2020 00:47:49 +0100 Subject: [PATCH] cgen: fix match --- vlib/v/gen/cgen.v | 27 ++++++++++++++++++--------- vlib/v/gen/tests/1.c | 6 ++++-- vlib/v/gen/tests/1.vv | 1 + 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 2f5f26119d..b779cfda63 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -513,16 +513,25 @@ fn (g mut Gen) expr(node ast.Expr) { g.write('$type_sym.name $tmp = ') g.expr(it.cond) g.writeln(';') // $it.blocks.len') - for branch in it.branches { - g.write('if ') - for i, expr in branch.exprs { - g.write('$tmp == ') - g.expr(expr) - if i < branch.exprs.len - 1 { - g.write(' || ') - } + for j, branch in it.branches { + if j == it.branches.len - 1 { + // last block is an `else{}` + g.writeln('else {') + } + else { + if j > 0 { + g.write('else ') + } + g.write('if (') + for i, expr in branch.exprs { + g.write('$tmp == ') + g.expr(expr) + if i < branch.exprs.len - 1 { + g.write(' || ') + } + } + g.writeln(') {') } - g.writeln('{') g.stmts(branch.stmts) g.writeln('}') } diff --git a/vlib/v/gen/tests/1.c b/vlib/v/gen/tests/1.c index 850b3cc2db..4bff212d48 100644 --- a/vlib/v/gen/tests/1.c +++ b/vlib/v/gen/tests/1.c @@ -148,13 +148,15 @@ void println(string s) { void matches() { int a = 100; int tmp1 = a; - if tmp1 == 10{ + if (tmp1 == 10) { println(tos3("10")); } - if tmp1 == 20{ + else if (tmp1 == 20) { int k = a + 1; + } + else { } ; } diff --git a/vlib/v/gen/tests/1.vv b/vlib/v/gen/tests/1.vv index 52e59279a9..f6b4d3d069 100644 --- a/vlib/v/gen/tests/1.vv +++ b/vlib/v/gen/tests/1.vv @@ -147,6 +147,7 @@ fn matches() { 20 { k := a + 1 } + else{} } /* n := match a {