cgen: fix array_init of struct error

pull/5016/head
yuyi 2020-05-25 10:45:16 +08:00 committed by GitHub
parent 4189190bb8
commit ec7863d174
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 16 deletions

View File

@ -967,9 +967,7 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
if is_call { if is_call {
g.expr(val) g.expr(val)
} else { } else {
if val is ast.ArrayInit { g.gen_default_init_value(val)
g.gen_default_init_value(val as ast.ArrayInit)
}
g.write('{$styp _ = ') g.write('{$styp _ = ')
g.expr(val) g.expr(val)
g.writeln(';}') g.writeln(';}')
@ -978,9 +976,7 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
right_sym := g.table.get_type_symbol(assign_stmt.right_types[i]) right_sym := g.table.get_type_symbol(assign_stmt.right_types[i])
mut is_fixed_array_init := false mut is_fixed_array_init := false
mut has_val := false mut has_val := false
if val is ast.ArrayInit { is_fixed_array_init, has_val = g.gen_default_init_value(val)
is_fixed_array_init, has_val = g.gen_default_init_value(val as ast.ArrayInit)
}
is_inside_ternary := g.inside_ternary != 0 is_inside_ternary := g.inside_ternary != 0
cur_line := if is_inside_ternary { cur_line := if is_inside_ternary {
g.register_ternary_name(ident.name) g.register_ternary_name(ident.name)
@ -1045,16 +1041,28 @@ fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
} }
} }
fn (mut g Gen) gen_default_init_value(val ast.ArrayInit) (bool, bool) { fn (mut g Gen) gen_default_init_value(val ast.Expr) (bool, bool) {
is_fixed_array_init := val.is_fixed mut is_fixed_array_init := false
has_val := val.has_val mut has_val := false
elem_type_str := g.typ(val.elem_type) match val {
if val.has_default { ast.ArrayInit {
g.write('$elem_type_str _val_$val.pos.pos = ') is_fixed_array_init = it.is_fixed
g.expr(val.default_expr) has_val = it.has_val
g.writeln(';') elem_type_str := g.typ(it.elem_type)
} else if val.has_len && val.elem_type == table.string_type { if it.has_default {
g.writeln('$elem_type_str _val_$val.pos.pos = tos_lit("");') g.write('$elem_type_str _val_$it.pos.pos = ')
g.expr(it.default_expr)
g.writeln(';')
} else if it.has_len && it.elem_type == table.string_type {
g.writeln('$elem_type_str _val_$it.pos.pos = tos_lit("");')
}
}
ast.StructInit {
for field in it.fields {
g.gen_default_init_value(field.expr)
}
}
else {}
} }
return is_fixed_array_init, has_val return is_fixed_array_init, has_val
} }

View File

@ -127,3 +127,16 @@ fn test_array_string_full_options() {
assert c.cap >= c.len assert c.cap >= c.len
assert c.str() == "['a', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', '11', '12', '13', '14', '15', '16']" assert c.str() == "['a', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', '11', '12', '13', '14', '15', '16']"
} }
struct MyStruct {
pub mut:
ar []f32
}
fn test_array_init_in_struct_field() {
m := MyStruct {
ar: []f32{len: 4, init:1.2}
}
println(m)
assert m.ar.str() == '[1.2, 1.2, 1.2, 1.2]'
}