cgen: execute defer stmts in LIFO order (#9528)

pull/9531/head
zakuro 2021-03-30 16:35:19 +09:00 committed by GitHub
parent b319068151
commit a3455b8433
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -1243,7 +1243,8 @@ fn (mut g Gen) stmt(node ast.Stmt) {
}
fn (mut g Gen) write_defer_stmts() {
for defer_stmt in g.defer_stmts {
for i := g.defer_stmts.len - 1; i >= 0; i-- {
defer_stmt := g.defer_stmts[i]
g.writeln('// Defer begin')
g.writeln('if (${g.defer_flag_var(defer_stmt)} == true) {')
g.indent++

View File

@ -101,3 +101,19 @@ fn test_defer_with_if() {
set_num_if(mut n, 20, false)
assert n.val == 10
}
fn test_defer_order() {
mut i := 0
defer {
i++
assert i == 3
}
defer {
i++
assert i == 2
}
defer {
i++
assert i == 1
}
}