cgen: simplify for in range

pull/4898/head
Enzo Baldisserri 2020-05-14 22:22:32 +02:00 committed by GitHub
parent 0f251e9ede
commit d60233b618
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 12 deletions

View File

@ -715,15 +715,12 @@ fn (mut g Gen) write_defer_stmts() {
fn (mut g Gen) for_in(it ast.ForInStmt) {
if it.is_range {
// `for x in 1..10 {`
i := g.new_tmp_var()
i := if it.val_var == '_' { g.new_tmp_var() } else { c_name(it.val_var) }
g.write('for (int $i = ')
g.expr(it.cond)
g.write('; $i < ')
g.expr(it.high)
g.writeln('; $i++) {')
if it.val_var != '_' {
g.writeln('\tint ${c_name(it.val_var)} = $i;')
}
g.stmts(it.stmts)
g.writeln('}')
} else if it.kind == .array {

View File

@ -18,6 +18,14 @@ fn test_for_char_in_range() {
assert sum == 6
}
fn test_for_blank_in_range() {
mut sum := 0
for _ in 1 .. 3 {
sum++
}
assert sum == 2
}
fn test_for_char_complex() {
mut sum := 0
for char := 0; char < nums.len; char++ {