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

cgen: fix default init value for an array of option (#17538)

This commit is contained in:
Felipe Pena 2023-03-07 15:04:16 -03:00 committed by GitHub
parent 792b822091
commit b85f71d00f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 73 additions and 2 deletions

View File

@ -343,10 +343,18 @@ fn (mut g Gen) array_init_with_fields(node ast.ArrayInit, elem_type Type, is_amp
g.writeln('; ${ind}++) {')
g.write('\t${tmp}[${ind}] = ')
if node.has_default {
if node.elem_type.has_flag(.option) {
g.expr_with_opt(node.default_expr, node.default_type, node.elem_type)
} else {
g.expr_with_cast(node.default_expr, node.default_type, node.elem_type)
}
} else {
if node.elem_type.has_flag(.option) {
g.expr_with_opt(ast.None{}, ast.none_type, node.elem_type)
} else {
g.write(g.type_default(node.elem_type))
}
}
g.writeln(';')
g.writeln('}')
g.write(line)
@ -355,6 +363,10 @@ fn (mut g Gen) array_init_with_fields(node ast.ArrayInit, elem_type Type, is_amp
g.write('&(${elem_styp}[]){')
g.expr_with_cast(node.default_expr, node.default_type, node.elem_type)
g.write('})')
} else if node.has_len && node.elem_type.has_flag(.option) {
g.write('&')
g.expr_with_opt(ast.None{}, ast.none_type, node.elem_type)
g.write(')')
} else if node.has_len && node.elem_type == ast.string_type {
g.write('&(${elem_styp}[]){')
g.write('_SLIT("")')

View File

@ -0,0 +1,59 @@
fn check_init_value_for_arrays_of_option[T]() {
a := []?T{len: 2}
assert a.len == 2
for value in a {
assert value == none
println(value)
}
}
enum MyEnum {
zero
one
two
}
enum MyEnum32 as u32 {
zero
one
two
}
struct MyStruct {
x int = 123
name string = 'abc'
}
fn test_primitives() {
check_init_value_for_arrays_of_option[i8]()
check_init_value_for_arrays_of_option[i16]()
check_init_value_for_arrays_of_option[i32]()
check_init_value_for_arrays_of_option[int]()
check_init_value_for_arrays_of_option[i64]()
check_init_value_for_arrays_of_option[u8]()
check_init_value_for_arrays_of_option[byte]()
check_init_value_for_arrays_of_option[u16]()
check_init_value_for_arrays_of_option[u32]()
check_init_value_for_arrays_of_option[u64]()
check_init_value_for_arrays_of_option[f32]()
check_init_value_for_arrays_of_option[f64]()
check_init_value_for_arrays_of_option[string]()
check_init_value_for_arrays_of_option[rune]()
}
fn test_arrays() {
check_init_value_for_arrays_of_option[[]int]()
check_init_value_for_arrays_of_option[[]f32]()
}
fn test_enums() {
check_init_value_for_arrays_of_option[MyEnum]()
check_init_value_for_arrays_of_option[MyEnum32]()
}
fn test_structs() {
check_init_value_for_arrays_of_option[MyStruct]()
}