From 89aa695fba1781943b2250110529337a8af523eb Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Fri, 13 Jan 2023 20:35:18 +0530 Subject: [PATCH] checker: disallow non ptr struct values to voidptr fields (#16958) --- vlib/v/checker/struct.v | 4 ++++ ...struct_voidptr_field_no_ptr_struct_value_err.out | 7 +++++++ .../struct_voidptr_field_no_ptr_struct_value_err.vv | 13 +++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.out create mode 100644 vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.vv diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index 6111b8ed1..fba2e02e2 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -467,6 +467,10 @@ fn (mut c Checker) struct_init(mut node ast.StructInit) ast.Type { expr_type = c.check_expr_opt_call(field.expr, expr_type) } expr_type_sym := c.table.sym(expr_type) + if field_type_sym.kind == .voidptr && expr_type_sym.kind == .struct_ + && !expr_type.is_ptr() { + c.error('allocate on the heap for use in other functions', field.pos) + } if field_type_sym.kind == .interface_ { if c.type_implements(expr_type, field_info.typ, field.pos) { if !c.inside_unsafe && expr_type_sym.kind != .interface_ diff --git a/vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.out b/vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.out new file mode 100644 index 000000000..0756fbe4f --- /dev/null +++ b/vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.vv:11:3: error: allocate on the heap for use in other functions + 9 | fn main() { + 10 | _ := Foo2{ + 11 | a: Foo{} + | ~~~~~~~~ + 12 | } + 13 | } diff --git a/vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.vv b/vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.vv new file mode 100644 index 000000000..214fb1332 --- /dev/null +++ b/vlib/v/checker/tests/struct_voidptr_field_no_ptr_struct_value_err.vv @@ -0,0 +1,13 @@ +struct Foo { + num int +} + +struct Foo2 { + a voidptr +} + +fn main() { + _ := Foo2{ + a: Foo{} + } +} -- 2.39.5