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

cgen: fix for _,mut j in arr for fixed arrays (fix #8163) (#8167)

This commit is contained in:
yuyi 2021-01-18 13:05:38 +08:00 committed by GitHub
parent b4a542c51c
commit 6c87c25ef1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 41 additions and 17 deletions

View File

@ -1284,15 +1284,22 @@ fn (mut g Gen) for_in(it ast.ForInStmt) {
}
} else if it.kind == .array_fixed {
atmp := g.new_tmp_var()
atmp_type := g.typ(it.cond_type)
atmp_type := g.typ(it.cond_type).trim('*')
if !it.cond.is_lvalue() {
g.write('$atmp_type *$atmp = &(($atmp_type)')
g.write('$atmp_type *$atmp = ')
if !it.cond_type.is_ptr() {
g.write('&')
}
g.write('(($atmp_type)')
} else {
g.write('$atmp_type *$atmp = &(')
g.write('$atmp_type *$atmp = ')
if !it.cond_type.is_ptr() {
g.write('&')
}
g.write('(')
}
g.expr(it.cond)
g.writeln(')')
g.writeln(';')
g.writeln(');')
i := if it.key_var in ['', '_'] { g.new_tmp_var() } else { it.key_var }
cond_sym := g.table.get_type_symbol(it.cond_type)
info := cond_sym.info as table.ArrayFixed
@ -1306,7 +1313,11 @@ fn (mut g Gen) for_in(it ast.ForInStmt) {
styp := g.typ(it.val_type)
g.write('\t$styp ${c_name(it.val_var)}')
}
g.writeln(' = (*$atmp)[$i];')
if it.val_is_mut {
g.writeln(' = &(*$atmp)[$i];')
} else {
g.writeln(' = (*$atmp)[$i];')
}
}
} else if it.kind == .map {
// `for key, val in map {
@ -4181,7 +4192,13 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) {
g.expr(node.index)
g.write(')')
} else {
g.expr(node.left)
if sym.kind == .array_fixed && node.left_type.is_ptr() {
g.write('(*')
g.expr(node.left)
g.write(')')
} else {
g.expr(node.left)
}
g.write('[')
g.expr(node.index)
g.write(']')

View File

@ -241,13 +241,7 @@ fn (mut g Gen) fn_args(args []table.Param, is_variadic bool) ([]string, []string
g.definitions.write(')')
}
} else {
// TODO: combine two operations into one once ternary in expression is fixed
mut s := if arg_type_sym.kind == .array_fixed {
arg_type_name.trim('*')
} else {
arg_type_name
}
s += ' ' + caname
s := '$arg_type_name $caname'
g.write(s)
g.definitions.write(s)
fargs << caname

View File

@ -1,12 +1,25 @@
fn foo(mut arr []int) {
fn foo1(mut arr []int) {
for _, mut j in arr {
j *= 2
}
}
fn test_for_in_mut_val() {
fn test_for_in_mut_val_of_array() {
mut arr := [1, 2, 3]
foo(mut arr)
foo1(mut arr)
println(arr)
assert arr == [2, 4, 6]
}
fn foo2(mut arr [3]int) {
for _, mut j in arr {
j *= 2
}
}
fn test_for_in_mut_val_of_fixed_array() {
mut arr := [1,2,3]!
foo2(mut arr)
println(arr)
assert arr == [2, 4, 6]!
}