diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 800d86008f..8c7187c03f 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -815,15 +815,15 @@ pub: pub struct ArrayInit { pub: - pos token.Position - elem_type_pos token.Position + pos token.Position // `[]` in []Type{} position + elem_type_pos token.Position // `Type` in []Type{} position exprs []Expr // `[expr, expr]` or `[expr]Type{}` for fixed array ecmnts [][]Comment // optional iembed comments after each expr is_fixed bool has_val bool // fixed size literal `[expr, expr]!!` mod string - len_expr Expr - cap_expr Expr + len_expr Expr // len: expr + cap_expr Expr // cap: expr default_expr Expr // init: expr has_len bool has_cap bool @@ -832,8 +832,8 @@ pub mut: is_interface bool // array of interfaces e.g. `[]Animal` `[Dog{}, Cat{}]` interface_types []table.Type // [Dog, Cat] interface_type table.Type // Animal - elem_type table.Type - typ table.Type + elem_type table.Type // element type + typ table.Type // array type } pub struct ChanInit { diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 8ed39d7dfd..405ea7456a 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2246,6 +2246,11 @@ pub fn (mut c Checker) array_init(mut array_init ast.ArrayInit) table.Type { if array_init.has_default { c.expr(array_init.default_expr) } + if sym.kind in [.sum_type, .union_sum_type] { + if array_init.has_len && !array_init.has_default { + c.error('cannot initalize sum type array without default value', array_init.elem_type_pos) + } + } if sym.kind == .placeholder { c.error('unknown type `$sym.source_name`', array_init.elem_type_pos) } diff --git a/vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.out b/vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.out new file mode 100644 index 0000000000..5048e7efab --- /dev/null +++ b/vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.vv:4:9: error: cannot initalize sum type array without default value + 2 | + 3 | fn main() { + 4 | a := []Foo{len:10} + | ~~~ + 5 | println(a) + 6 | diff --git a/vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.vv b/vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.vv new file mode 100644 index 0000000000..935f5ba442 --- /dev/null +++ b/vlib/v/checker/tests/array_init_sum_type_without_init_value_and_len_err.vv @@ -0,0 +1,7 @@ +type Foo = string | int + +fn main() { + a := []Foo{len:10} + println(a) + +}