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

checker: disallow non-ptr elem in init ptr array (#18161)

This commit is contained in:
Swastik Baranwal 2023-05-12 11:26:22 +05:30 committed by GitHub
parent d8cf65df1a
commit 447b45ca8c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 0 deletions

View File

@ -151,6 +151,7 @@ fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
mut expected_value_type := ast.void_type
mut expecting_interface_array := false
mut expecting_sumtype_array := false
mut is_first_elem_ptr := false
if c.expected_type != 0 {
expected_value_type = c.table.value_type(c.expected_type)
expected_value_sym := c.table.sym(expected_value_type)
@ -209,8 +210,16 @@ fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
} else {
elem_type = ast.mktyp(typ)
}
if typ.is_ptr() && c.in_for_count == 0 {
is_first_elem_ptr = true
}
c.expected_type = elem_type
continue
} else {
if !typ.is_real_pointer() && !typ.is_int() && is_first_elem_ptr {
c.error('cannot have non-pointer of type `${c.table.type_to_str(typ)}` in a pointer array of type `${c.table.type_to_str(elem_type)}`',
expr.pos())
}
}
if expr !is ast.TypeNode {
if c.table.type_kind(elem_type) == .interface_ {

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.vv:13:23: error: cannot have non-pointer of type `Chunk` in a pointer array of type `&Chunk`
11 | chunk1 := Chunk{1}
12 | w := World{
13 | chunks: [&Chunk{0}, chunk1]
| ~~~~~~
14 | }
15 |

View File

@ -0,0 +1,17 @@
struct World {
chunks []&Chunk
}
struct Chunk {
id int
// Big data here
}
fn main() {
chunk1 := Chunk{1}
w := World{
chunks: [&Chunk{0}, chunk1]
}
println(w)
}