1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

parser, cgen: fix for i++; i<10; i++ { (fix #18445) (#19035)

This commit is contained in:
yuyi 2023-08-02 15:47:52 +08:00 committed by GitHub
parent 6b978a6b5a
commit 1d9835f0e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 0 deletions

View File

@ -17,6 +17,9 @@ fn (mut g Gen) for_c_stmt(node ast.ForCStmt) {
g.indent++
if node.has_init {
g.stmt(node.init)
if node.init is ast.ExprStmt {
g.write('; ')
}
}
g.writeln('bool _is_first = true;')
g.writeln('while (true) {')
@ -58,6 +61,9 @@ fn (mut g Gen) for_c_stmt(node ast.ForCStmt) {
g.write('; ')
} else {
g.stmt(node.init)
if node.init is ast.ExprStmt {
g.write('; ')
}
// Remove excess return and add space
if g.out.last_n(1) == '\n' {
g.go_back(1)

View File

@ -31,6 +31,7 @@ fn (mut p Parser) for_stmt() ast.Stmt {
p.close_scope()
return for_stmt
} else if p.peek_tok.kind in [.decl_assign, .assign, .semicolon]
|| (p.peek_tok.kind in [.inc, .dec] && p.peek_token(2).kind in [.semicolon, .comma])
|| p.peek_tok.kind.is_assign() || p.tok.kind == .semicolon
|| (p.peek_tok.kind == .comma && p.peek_token(2).kind != .key_mut
&& p.peek_token(3).kind != .key_in) {
@ -49,6 +50,9 @@ fn (mut p Parser) for_stmt() ast.Stmt {
if p.peek_tok.kind in [.assign, .decl_assign] || p.peek_tok.kind.is_assign() || is_multi {
init = p.assign_stmt()
has_init = true
} else if p.peek_tok.kind in [.inc, .dec] {
init = p.stmt(false)
has_init = true
}
comments << p.eat_comments()
// Allow `for ;; i++ {`

View File

@ -0,0 +1,9 @@
fn test_for_c_init_with_var_inc() {
mut results := []int{}
mut i := 0
for i++; i < 10; i++ {
println(i)
results << i
}
assert results == [1, 2, 3, 4, 5, 6, 7, 8, 9]
}