From 65ff74b82a5ee06fee9bf556bb2fdd061d978fb1 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 1 Jul 2024 15:51:32 +0800 Subject: [PATCH] checker: fix nested if expr method call (#21773) --- vlib/v/checker/fn.v | 13 ++++++++ .../v/tests/nested_if_expr_method_call_test.v | 33 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 vlib/v/tests/nested_if_expr_method_call_test.v diff --git a/vlib/v/checker/fn.v b/vlib/v/checker/fn.v index 09268e8cc..60241a321 100644 --- a/vlib/v/checker/fn.v +++ b/vlib/v/checker/fn.v @@ -1819,6 +1819,19 @@ fn (mut c Checker) check_type_and_visibility(name string, type_idx int, expected } fn (mut c Checker) method_call(mut node ast.CallExpr) ast.Type { + // `(if true { 'foo.bar' } else { 'foo.bar.baz' }).all_after('foo.')` + mut left_expr := node.left + for mut left_expr is ast.ParExpr { + left_expr = left_expr.expr + } + if mut left_expr is ast.IfExpr { + if left_expr.branches.len > 0 && left_expr.has_else { + mut last_stmt := left_expr.branches[0].stmts.last() + if mut last_stmt is ast.ExprStmt { + c.expected_type = c.expr(mut last_stmt.expr) + } + } + } left_type := c.expr(mut node.left) if left_type == ast.void_type { c.error('cannot call a method using an invalid expression', node.pos) diff --git a/vlib/v/tests/nested_if_expr_method_call_test.v b/vlib/v/tests/nested_if_expr_method_call_test.v new file mode 100644 index 000000000..4aab4c0b8 --- /dev/null +++ b/vlib/v/tests/nested_if_expr_method_call_test.v @@ -0,0 +1,33 @@ +fn test_nested_if_expr_method_call() { + str_from_nested_exp1 := if true { + if true { 'foo.bar' } else { 'foo.bar.baz' }.all_after('foo.') + } else { + 'foo' + } + println(str_from_nested_exp1) + assert str_from_nested_exp1 == 'bar' + + str_from_nested_exp2 := if true { + (if true { 'foo.bar' } else { 'foo.bar.baz' }).all_after('foo.') + } else { + 'foo' + } + println(str_from_nested_exp2) + assert str_from_nested_exp2 == 'bar' + + str_from_nested_exp3 := if true { + 'foo' + } else { + if true { 'foo.bar' } else { 'foo.bar.baz' }.all_after('foo.') + } + println(str_from_nested_exp3) + assert str_from_nested_exp3 == 'foo' + + str_from_nested_exp4 := if true { + 'foo' + } else { + (if true { 'foo.bar' } else { 'foo.bar.baz' }).all_after('foo.') + } + println(str_from_nested_exp4) + assert str_from_nested_exp4 == 'foo' +} -- 2.39.5