cgen: fix a[0]+='str'

pull/5548/head
yuyi 2020-06-28 17:16:16 +08:00 committed by GitHub
parent 03829d9935
commit d9409006fa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 6 deletions

View File

@ -871,3 +871,9 @@ fn test_mutli_array_index() {
b[0][0] = 1
assert '$b' == '[[1, 0, 0], [0, 0, 0]]'
}
fn test_plus_assign_string() {
mut a := ['']
a[0] += 'abc'
assert a == ['abc']
}

View File

@ -1144,9 +1144,17 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
}
mut str_add := false
if var_type == table.string_type_idx && assign_stmt.op == .plus_assign {
// str += str2 => `str = string_add(str, str2)`
g.expr(left)
g.write(' = /*f*/string_add(')
if left is ast.IndexExpr {
// a[0] += str => `array_set(&a, 0, &(string[]) {string_add(...))})`
g.expr(left)
g.write('string_add(')
} else {
// str += str2 => `str = string_add(str, str2)`
g.expr(left)
g.write(' = /*f*/string_add(')
}
g.is_assign_lhs = false
g.is_assign_rhs = true
str_add = true
}
if right_sym.kind == .function && is_decl {
@ -1209,11 +1217,12 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
if unwrap_optional {
g.write('.data')
}
if str_add {
g.write(')')
}
if g.is_array_set {
g.write(' })')
g.is_array_set = false
} else if str_add {
g.write(')')
}
}
g.right_is_opt = false
@ -2196,7 +2205,8 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) {
g.write(', &')
}
// `x[0] *= y`
if g.assign_op != .assign && g.assign_op in token.assign_tokens {
if g.assign_op != .assign && g.assign_op in token.assign_tokens &&
info.elem_type != table.string_type {
// TODO move this
g.write('*($elem_type_str*)array_get(')
if left_is_ptr {