Skip to content

Commit 42da37e

Browse files
committed
autofree: fix if expressions
1 parent a52314d commit 42da37e

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

vlib/v/gen/cgen.v

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@ mut:
7474
// inside_if_expr bool
7575
ternary_names map[string]string
7676
ternary_level_names map[string][]string
77-
stmt_path_pos []int
77+
stmt_path_pos []int // positions of each statement start, for inserting C statements before the current statement
78+
skip_stmt_pos bool // for handling if expressions + autofree (since both prepend C statements)
7879
right_is_opt bool
7980
autofree bool
8081
indent int
@@ -725,9 +726,12 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) {
725726
for i, stmt in stmts {
726727
if i == stmts.len - 1 && tmp_var != '' {
727728
// Handle if expressions, set the value of the last expression to the temp var.
729+
g.stmt_path_pos << g.out.len
730+
g.skip_stmt_pos = true
728731
g.writeln('$tmp_var = /* if expr set */')
729732
}
730733
g.stmt(stmt)
734+
g.skip_stmt_pos = false
731735
if g.inside_ternary > 0 && i < stmts.len - 1 {
732736
g.write(',')
733737
}
@@ -761,7 +765,9 @@ fn (mut g Gen) write_v_source_line_info(pos token.Position) {
761765
}
762766

763767
fn (mut g Gen) stmt(node ast.Stmt) {
764-
g.stmt_path_pos << g.out.len
768+
if !g.skip_stmt_pos {
769+
g.stmt_path_pos << g.out.len
770+
}
765771
defer {
766772
// If we have temporary string exprs to free after this statement, do it. e.g.:
767773
// `foo('a' + 'b')` => `tmp := 'a' + 'b'; foo(tmp); string_free(&tmp);`
@@ -1047,7 +1053,9 @@ fn (mut g Gen) stmt(node ast.Stmt) {
10471053
g.writeln('// TypeDecl')
10481054
}
10491055
}
1050-
g.stmt_path_pos.delete_last()
1056+
if !g.skip_stmt_pos { // && g.stmt_path_pos.len > 0 {
1057+
g.stmt_path_pos.delete_last()
1058+
}
10511059
}
10521060

10531061
fn (mut g Gen) write_defer_stmts() {

vlib/v/tests/valgrind/1.strings_and_arrays.v

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,18 +159,22 @@ fn tt() {
159159
}
160160

161161
fn get_string(s string) string {
162-
return s
162+
return s.clone() // TODO handle returning the argument without clone()
163+
}
164+
165+
fn if_expr() string {
166+
a := if true { get_string('a' + 'b') } else { get_string('c' + 'd') }
167+
return a
163168
}
164169

165-
/*
166170
fn return_if_expr() string {
167171
return if true {
168172
get_string('a' + 'b')
169173
} else {
170174
get_string('c' + 'd')
171175
}
172176
}
173-
*/
177+
174178
fn main() {
175179
println('start')
176180
simple()
@@ -186,7 +190,8 @@ fn main() {
186190
str_replace2()
187191
if_cond()
188192
addition_with_tmp_expr()
189-
// return_if_expr()
193+
if_expr()
194+
return_if_expr()
190195
println('end')
191196
}
192197

0 commit comments

Comments
 (0)