checker: check for `x := []Interface{len: 9}` without `init:`

pull/10646/head
Delyan Angelov 2021-07-02 08:37:49 +03:00
parent d0a09579cc
commit a33a2ba095
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
3 changed files with 30 additions and 0 deletions

View File

@ -3840,6 +3840,13 @@ pub fn (mut c Checker) array_init(mut array_init ast.ArrayInit) ast.Type {
} }
} }
if array_init.has_len { if array_init.has_len {
if array_init.has_len && !array_init.has_default {
elem_type_sym := c.table.get_type_symbol(array_init.elem_type)
if elem_type_sym.kind == .interface_ {
c.error('cannot instantiate an array of interfaces without also giving a default `init:` value',
array_init.len_expr.position())
}
}
c.ensure_sumtype_array_has_default_value(array_init) c.ensure_sumtype_array_has_default_value(array_init)
} }
c.ensure_type_exists(array_init.elem_type, array_init.elem_type_pos) or {} c.ensure_type_exists(array_init.elem_type, array_init.elem_type_pos) or {}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/array_of_interfaces_with_len_without_init.vv:14:37: error: cannot instantiate an array of interfaces without also giving a default `init:` value
12 |
13 | fn main() {
14 | mut parsed_lines := []MObject{len: 9}
| ^
15 | println(parsed_lines)
16 | }

View File

@ -0,0 +1,16 @@
interface MObject {
give_string() string
}
struct LeStruct {
le_string string
}
fn (a LeStruct) give_string() string {
return 'V'
}
fn main() {
mut parsed_lines := []MObject{len: 9}
println(parsed_lines)
}