Skip to content

Commit

Permalink
autofree: fix argument freeing for json.encode and json.encode_pretty…
Browse files Browse the repository at this point in the history
… calls (#22781)
  • Loading branch information
felipensp authored Nov 7, 2024
1 parent aaeae8c commit 107167a
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
3 changes: 3 additions & 0 deletions vlib/v/checker/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,9 @@ fn (mut c Checker) call_expr(mut node ast.CallExpr) ast.Type {
// Only expressions like `str + 'b'` need to be freed.
continue
}
if arg.expr is ast.CallExpr && arg.expr.name in ['json.encode', 'json.encode_pretty'] {
continue
}
node.args[i].is_tmp_autofree = true
}
// TODO: copy pasta from above
Expand Down
12 changes: 11 additions & 1 deletion vlib/v/gen/c/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -2073,7 +2073,11 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
g.write('cJSON* ${json_obj} = ${encode_name}(')
g.call_args(node)
g.writeln(');')
tmp2 = g.new_tmp_var()
tmp2 = if g.is_autofree {
'_arg_expr_${node.name.replace('.', '_')}_${node.pos.pos}'
} else {
g.new_tmp_var()
}
if is_json_encode {
g.writeln('string ${tmp2} = json__json_print(${json_obj});')
} else {
Expand Down Expand Up @@ -2421,6 +2425,12 @@ fn (mut g Gen) autofree_call_pregen(node ast.CallExpr) {
args << node.args
for i, arg in args {
if !arg.is_tmp_autofree {
if arg.expr is ast.CallExpr && arg.expr.name in ['json.encode', 'json.encode_pretty'] {
t := '_arg_expr_${arg.expr.name.replace('.', '_')}_${arg.expr.pos.pos}'
defer {
g.writeln(';\n\tstring_free(&${t});')
}
}
continue
}
if arg.expr is ast.CallExpr {
Expand Down
5 changes: 5 additions & 0 deletions vlib/v/gen/c/testdata/autofree_json_encode.c.must_have
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
string _arg_expr_json_encode_pretty
string_free(&_arg_expr_json_encode_pretty_
string _arg_expr_json_encode_
string d = (_arg_expr_json_encode_
string_free(&d); // autofreed var main false
16 changes: 16 additions & 0 deletions vlib/v/gen/c/testdata/autofree_json_encode.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// vtest vflags: -autofree
import json

struct Foo {
foo int
}

fn main() {
mut a := {
'foo': 123
}
println(json.encode_pretty(a))
d := json.encode(a)
dump(d)
println(json.decode(Foo, d)!)
}

0 comments on commit 107167a

Please sign in to comment.