1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

autofree: handle array set/get

This commit is contained in:
Alexander Medvednikov 2020-11-22 20:48:10 +01:00
parent 67d5dfb315
commit a1827d7f98
2 changed files with 23 additions and 2 deletions

View File

@ -1536,6 +1536,7 @@ fn (mut g Gen) write_fn_ptr_decl(func &table.FnType, ptr_name string) {
g.write(')') g.write(')')
} }
// TODO this function is scary. Simplify/split up.
fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) { fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
if assign_stmt.is_static { if assign_stmt.is_static {
g.write('static ') g.write('static ')
@ -1683,7 +1684,14 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
if left.left_type.is_ptr() { if left.left_type.is_ptr() {
g.write('*') g.write('*')
} }
needs_clone := elem_typ == table.string_type && g.pref.autofree
if needs_clone {
g.write('/*1*/string_clone(')
}
g.expr(left.left) g.expr(left.left)
if needs_clone {
g.write(')')
}
g.write(', ') g.write(', ')
g.expr(left.index) g.expr(left.index)
g.writeln(');') g.writeln(');')
@ -3750,10 +3758,15 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) {
.function { 'voidptr*' } .function { 'voidptr*' }
else { '$elem_type_str*' } else { '$elem_type_str*' }
} }
needs_clone := info.elem_type == table.string_type_idx && g.pref.autofree &&
!g.is_assign_lhs
if needs_clone {
g.write('/*2*/string_clone(')
}
if is_direct_array_access { if is_direct_array_access {
g.write('(($array_ptr_type_str)') g.write('(($array_ptr_type_str)')
} else { } else {
g.write('(*($array_ptr_type_str)array_get(') g.write('(*($array_ptr_type_str)/*ee elem_typ */array_get(')
if left_is_ptr && !node.left_type.has_flag(.shared_f) { if left_is_ptr && !node.left_type.has_flag(.shared_f) {
g.write('*') g.write('*')
} }
@ -3781,6 +3794,9 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) {
g.expr(node.index) g.expr(node.index)
g.write('))') g.write('))')
} }
if needs_clone {
g.write(')')
}
} }
} else if sym.kind == .map { } else if sym.kind == .map {
info := sym.info as table.Map info := sym.info as table.Map
@ -3900,7 +3916,6 @@ fn (mut g Gen) return_statement(node ast.Return, af bool) {
if af { if af {
// free the tmp arg expr if we have one before the return // free the tmp arg expr if we have one before the return
g.autofree_call_postgen(node.pos.pos) g.autofree_call_postgen(node.pos.pos)
// g.strs_to_free = []
} }
styp := g.typ(g.fn_decl.return_type) styp := g.typ(g.fn_decl.return_type)
g.writeln('return *($styp*)&$tmp;') g.writeln('return *($styp*)&$tmp;')

View File

@ -256,6 +256,12 @@ fn get_user() User {
return user return user
} }
fn string_array_get() {
s := ['a', 'b', 'c']
x := s[0]
println(s)
}
fn main() { fn main() {
println('start') println('start')
simple() simple()