autofree: free strings on re-assignments

pull/6345/head
Alexander Medvednikov 2020-09-11 13:55:20 +02:00
parent 4aaeaa4331
commit e0d20eadff
3 changed files with 17 additions and 1 deletions

View File

@ -1325,6 +1325,13 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
ast.MatchExpr { return_type = it.return_type }
else {}
}
// Free the old value assigned to this string var (only if it's `str = [new value]`)
if g.pref.autofree && assign_stmt.op == .assign && assign_stmt.left_types.len == 1 &&
assign_stmt.left_types[0] == table.string_type && assign_stmt.left[0] is ast.Ident {
g.write('string_free(&')
g.expr(assign_stmt.left[0])
g.writeln('); // free str on re-assignment')
}
// json_test failed w/o this check
if return_type != table.void_type && return_type != 0 {
sym := g.table.get_type_symbol(return_type)

View File

@ -308,6 +308,7 @@ fn (mut g Gen) call_expr(node ast.CallExpr) {
g.or_block(tmp_opt, node.or_block, node.return_type)
if is_gen_or_and_assign_rhs {
g.write('\n$cur_line$tmp_opt')
// g.insert_before_stmt('\n /* VVV */ $tmp_opt')
}
}
}
@ -544,10 +545,12 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
t := '_tt${g.tmp_count2}_arg_expr_${fn_name}_$i'
g.called_fn_name = name
str_expr := g.write_expr_to_string(arg.expr)
// g.insert_before_stmt('string $t = $str_expr; // new. to free $i ')
g.insert_before_stmt('string $t = $str_expr; // new3. to free $i ')
/*
cur_line = g.go_before_stmt(0)
// println('cur line ="$cur_line"')
g.writeln('string $t = $str_expr; // new. to free $i ')
*/
}
}
// Handle `print(x)`

View File

@ -49,6 +49,11 @@ fn str_replace() {
println(r)
}
fn reassign_str() {
mut s := 'a' + 'b'
s = 'x' + 'y' // 'a' + 'b' must be freed before the re-assignment
}
fn match_expr() string {
x := 2
res := match x {
@ -76,6 +81,7 @@ fn main() {
str_tmp_expr()
str_inter()
match_expr()
reassign_str()
// str_replace()
println('end')
}