Skip to content

Commit

Permalink
checker, cgen: fix if/match expr with continue or break in a bran…
Browse files Browse the repository at this point in the history
…ch (#18466)
  • Loading branch information
yuyi98 committed Jun 16, 2023
1 parent d17f6f6 commit ac32d2a
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 3 deletions.
2 changes: 1 addition & 1 deletion vlib/v/checker/if.v
Expand Up @@ -414,7 +414,7 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
node.pos)
}
}
} else if !node.is_comptime && stmt !is ast.Return {
} else if !node.is_comptime && stmt !in [ast.Return, ast.BranchStmt] {
c.error('`${if_kind}` expression requires an expression as the last statement of every branch',
branch.pos)
}
Expand Down
2 changes: 1 addition & 1 deletion vlib/v/checker/match.v
Expand Up @@ -90,7 +90,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
c.check_match_branch_last_stmt(stmt, ret_type, expr_type)
}
}
} else if stmt !is ast.Return {
} else if stmt !in [ast.Return, ast.BranchStmt] {
if node.is_expr && ret_type != ast.void_type {
c.error('`match` expression requires an expression as the last statement of every branch',
stmt.pos)
Expand Down
2 changes: 1 addition & 1 deletion vlib/v/gen/c/cgen.v
Expand Up @@ -1802,7 +1802,7 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool {
g.set_current_pos_as_last_stmt_pos()
g.skip_stmt_pos = true
mut is_noreturn := false
if stmt is ast.Return {
if stmt in [ast.Return, ast.BranchStmt] {
is_noreturn = true
} else if stmt is ast.ExprStmt {
is_noreturn = is_noreturn_callexpr(stmt.expr)
Expand Down
2 changes: 2 additions & 0 deletions vlib/v/gen/c/if.v
Expand Up @@ -25,6 +25,8 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool {
}
} else if branch.stmts[0] is ast.Return {
return true
} else if branch.stmts[0] is ast.BranchStmt {
return true
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions vlib/v/gen/c/match.v
Expand Up @@ -29,6 +29,8 @@ fn (mut g Gen) need_tmp_var_in_match(node ast.MatchExpr) bool {
}
} else if branch.stmts[0] is ast.Return {
return true
} else if branch.stmts[0] is ast.BranchStmt {
return true
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions vlib/v/tests/if_expr_with_continue_in_branch_test.v
@@ -0,0 +1,17 @@
fn test_if_expr_with_continue_in_branch() {
mut result := []int{}
for i in 0 .. 10 {
s := if i < 2 {
100 + i
} else {
continue
}

println(s)
result << s
}
println(result)
assert result.len == 2
assert result[0] == 100
assert result[1] == 101
}

0 comments on commit ac32d2a

Please sign in to comment.