Skip to content

Commit

Permalink
checker: fix nested if expr method call (vlang#21773)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored Jul 1, 2024
1 parent 387a01f commit 65ff74b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
13 changes: 13 additions & 0 deletions vlib/v/checker/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
33 changes: 33 additions & 0 deletions vlib/v/tests/nested_if_expr_method_call_test.v
Original file line number Diff line number Diff line change
@@ -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'
}

0 comments on commit 65ff74b

Please sign in to comment.