cgen: fix array_init has len but no init error

pull/4907/head
yuyi 2020-05-20 00:33:24 +08:00 committed by GitHub
parent b10df252dc
commit b3b86ea6d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 2 deletions

View File

@ -990,11 +990,13 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
ast.ArrayInit { ast.ArrayInit {
is_fixed_array_init = it.is_fixed is_fixed_array_init = it.is_fixed
has_val = it.has_val has_val = it.has_val
elem_type_str := g.typ(it.elem_type)
if it.has_default { if it.has_default {
elem_type_str := g.typ(it.elem_type)
g.write('$elem_type_str _val_$it.pos.pos = ') g.write('$elem_type_str _val_$it.pos.pos = ')
g.expr(it.default_expr) g.expr(it.default_expr)
g.writeln(';') g.writeln(';')
} else if it.has_len && it.elem_type == table.string_type {
g.writeln('$elem_type_str _val_$it.pos.pos = tos_lit("");')
} }
} }
else {} else {}
@ -3928,7 +3930,7 @@ fn (mut g Gen) array_init(it ast.ArrayInit) {
g.write('0, ') g.write('0, ')
} }
g.write('sizeof($elem_type_str), ') g.write('sizeof($elem_type_str), ')
if it.has_default { if it.has_default || (it.has_len && it.elem_type == table.string_type) {
g.write('&_val_$it.pos.pos)') g.write('&_val_$it.pos.pos)')
} else { } else {
g.write('0)') g.write('0)')

View File

@ -28,3 +28,14 @@ fn test_array_init_with_default() {
b2 := []string{len: 2, init: '111'} b2 := []string{len: 2, init: '111'}
assert '$b2' == "['111', '111']" assert '$b2' == "['111', '111']"
} }
fn test_array_init_with_len_no_default() {
a1 := []int{len: 4}
assert '$a1' == '[0, 0, 0, 0]'
a2 := []string{len: 4}
assert '$a2' == "['', '', '', '']"
a3 := []bool{len: 3}
assert '$a3' == '[false, false, false]'
}