autofree: fix a bug with $if and add a test

pull/7076/head
Alexander Medvednikov 2020-12-01 18:58:16 +01:00
parent 3612bd58ef
commit 0ff541375d
3 changed files with 31 additions and 4 deletions

View File

@ -782,9 +782,25 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) {
// go back 1 position is important so we dont get the
// internal scope of for loops and possibly other nodes
// g.autofree_scope_vars(stmt.position().pos - 1)
stmt_pos := stmt.position()
g.writeln('// af scope_vars')
g.autofree_scope_vars(stmt_pos.pos - 1, stmt_pos.line_nr, false)
mut stmt_pos := stmt.position()
if stmt_pos.pos == 0 {
// Do not autofree if the position is 0, since the correct scope won't be found.
// Report a bug, since position shouldn't be 0 for most nodes.
if stmt is ast.Module {
return
}
if stmt is ast.ExprStmt {
// For some reason ExprStmt.pos is 0 when ExprStmt.expr is comp if expr
// Extract the pos. TODO figure out why and fix.
stmt_pos = stmt.expr.position()
}
if stmt_pos.pos == 0 {
print('autofree: first stmt pos = 0. ')
println(typeof(stmt))
return
}
}
g.autofree_scope_vars(stmt_pos.pos, stmt_pos.line_nr, false)
}
}
}

View File

@ -18,7 +18,8 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
pos := if is_comptime {
p.inside_ct_if_expr = true
p.next() // `$`
p.prev_tok.position().extend(p.tok.position())
// p.prev_tok.position().extend(p.tok.position())
p.tok.position()
} else {
p.tok.position()
}

View File

@ -278,6 +278,15 @@ fn string_array_get() {
println(s)
}
fn comp_if() {
// compif pos used to be 0, if it was the first statement in a block, vars wouldn't be freed
$if macos {
println('macos')
}
s := 'a' + 'b'
println(s)
}
fn main() {
println('start')
simple()
@ -297,6 +306,7 @@ fn main() {
q := if_expr()
s := return_if_expr()
free_inside_opt_block()
comp_if()
// free_before_return()
// free_before_return_bool()
// free_before_break()