From fefb9643b2d2bfcdfd52d7027c9f137c4861900f Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 1 Jun 2022 14:18:59 +0800 Subject: [PATCH] checker, cgen: fix array index optional with if expr (#14575) --- vlib/v/checker/checker.v | 3 +++ vlib/v/gen/c/if.v | 2 +- vlib/v/tests/array_index_optional_with_if_expr_test.v | 7 +++++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/array_index_optional_with_if_expr_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 776f176e02..b78c2f69aa 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3403,6 +3403,9 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type { typ = value_type } } + if node.or_expr.stmts.len > 0 && node.or_expr.stmts.last() is ast.ExprStmt { + c.expected_or_type = typ + } c.stmts_ending_with_expression(node.or_expr.stmts) c.check_expr_opt_call(node, typ) return typ diff --git a/vlib/v/gen/c/if.v b/vlib/v/gen/c/if.v index 4c483ae96a..3e05821d88 100644 --- a/vlib/v/gen/c/if.v +++ b/vlib/v/gen/c/if.v @@ -85,7 +85,7 @@ fn (mut g Gen) if_expr(node ast.IfExpr) { g.stmts(branch.stmts) g.expected_cast_type = prev_expected_cast_type } - if node.branches.len == 1 { + if node.branches.len == 1 && !node.is_expr { g.write(': 0') } g.write(')') diff --git a/vlib/v/tests/array_index_optional_with_if_expr_test.v b/vlib/v/tests/array_index_optional_with_if_expr_test.v new file mode 100644 index 0000000000..19002ac0e6 --- /dev/null +++ b/vlib/v/tests/array_index_optional_with_if_expr_test.v @@ -0,0 +1,7 @@ +fn test_array_index_optional_with_if_expr() { + ret := []string{}[0] or { + if true { 'a' } else { 'b' } + } + println(ret) + assert ret == 'a' +}