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) { fn (mut g Gen) for_in(it ast.ForInStmt) {
if it.is_range { if it.is_range {
// `for x in 1..10 {` // `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.write('for (int $i = ')
g.expr(it.cond) g.expr(it.cond)
g.write('; $i < ') g.write('; $i < ')
g.expr(it.high) g.expr(it.high)
g.writeln('; $i++) {') g.writeln('; $i++) {')
if it.val_var != '_' {
g.writeln('\tint ${c_name(it.val_var)} = $i;')
}
g.stmts(it.stmts) g.stmts(it.stmts)
g.writeln('}') g.writeln('}')
} else if it.kind == .array { } else if it.kind == .array {
@ -1303,14 +1300,14 @@ fn (mut g Gen) expr(node ast.Expr) {
mut styp := it.type_name mut styp := it.type_name
if it.type_name == '' { if it.type_name == '' {
styp = g.typ(it.typ) styp = g.typ(it.typ)
} else { } else {
sym := g.table.get_type_symbol(it.typ) sym := g.table.get_type_symbol(it.typ)
if sym.kind == .struct_ { if sym.kind == .struct_ {
info := sym.info as table.Struct info := sym.info as table.Struct
if !info.is_typedef { if !info.is_typedef {
styp = 'struct ' + styp styp = 'struct ' + styp
} }
} }
} }
/* /*
if styp.starts_with('C__') { if styp.starts_with('C__') {

View File

@ -18,6 +18,14 @@ fn test_for_char_in_range() {
assert sum == 6 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() { fn test_for_char_complex() {
mut sum := 0 mut sum := 0
for char := 0; char < nums.len; char++ { for char := 0; char < nums.len; char++ {