From 447b45ca8c65eefe13b31ad274b00b9911018fda Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Fri, 12 May 2023 11:26:22 +0530 Subject: [PATCH] checker: disallow non-ptr elem in init ptr array (#18161) --- vlib/v/checker/containers.v | 9 +++++++++ .../tests/array_init_ptr_non_ptr_elem_err.out | 7 +++++++ .../tests/array_init_ptr_non_ptr_elem_err.vv | 17 +++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.out create mode 100644 vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.vv diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index 6add51676e..5c83b0bfe9 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -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_ { diff --git a/vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.out b/vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.out new file mode 100644 index 0000000000..5bc56dd112 --- /dev/null +++ b/vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.out @@ -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 | diff --git a/vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.vv b/vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.vv new file mode 100644 index 0000000000..45d1a7d942 --- /dev/null +++ b/vlib/v/checker/tests/array_init_ptr_non_ptr_elem_err.vv @@ -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) +}