From 3d235169c81c0ab89b2552c410f5733e619ed63c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=8C=E3=82=82=E3=82=93?= Date: Sat, 23 Nov 2019 20:25:57 +0900 Subject: [PATCH] parser: fix if expression --- vlib/compiler/parser.v | 4 ++-- vlib/compiler/tests/if_expression_test.v | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 vlib/compiler/tests/if_expression_test.v diff --git a/vlib/compiler/parser.v b/vlib/compiler/parser.v index be6cbb0e3c..6e725f6a65 100644 --- a/vlib/compiler/parser.v +++ b/vlib/compiler/parser.v @@ -2499,7 +2499,7 @@ fn (p mut Parser) if_st(is_expr bool, elif_depth int) string { //println('IF EXPR') //} p.inside_if_expr = true - p.gen('(') + p.gen('((') } else { p.gen('if (') @@ -2594,7 +2594,7 @@ fn (p mut Parser) if_st(is_expr bool, elif_depth int) string { p.inside_if_expr = false if is_expr { p.check_types(first_typ, typ) - p.gen(strings.repeat(`)`, elif_depth + 1)) + p.gen(strings.repeat(`)`, 2 * (elif_depth + 1))) } else_returns := p.returns p.returns = if_returns && else_returns diff --git a/vlib/compiler/tests/if_expression_test.v b/vlib/compiler/tests/if_expression_test.v new file mode 100644 index 0000000000..e38f3f4766 --- /dev/null +++ b/vlib/compiler/tests/if_expression_test.v @@ -0,0 +1,14 @@ + +fn test_if_expression_precedence_false_condition(){ + b := 10 + c := 20 + res := 1 + if b > c { b } else { c } + 1 + assert res == c + 2 +} + +fn test_if_expression_precedence_true_condition(){ + b := 20 + c := 10 + res := 1 + if b > c { b } else { c } + 1 + assert res == b + 2 +}