From f9334c8340ff4b76b30a9362ced0038e97094256 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Tue, 19 Sep 2023 16:29:57 +0530 Subject: [PATCH] checker: disallow assigning pointer values to option struct fields (#19380) --- vlib/v/checker/struct.v | 4 ++++ .../struct_option_field_assign_ptr_err.out | 14 ++++++++++++++ .../tests/struct_option_field_assign_ptr_err.vv | 17 +++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 vlib/v/checker/tests/struct_option_field_assign_ptr_err.out create mode 100644 vlib/v/checker/tests/struct_option_field_assign_ptr_err.vv diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index dea608642..8c0185163 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -566,6 +566,10 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini init_field.pos) } } + if exp_type.has_flag(.option) && got_type.is_ptr() && !(exp_type.is_ptr() + && exp_type_sym.kind == .struct_) { + c.error('cannot assign a pointer to option struct field', init_field.pos) + } if exp_type_sym.kind == .voidptr && got_type_sym.kind == .struct_ && !got_type.is_ptr() { c.error('allocate on the heap for use in other functions', init_field.pos) diff --git a/vlib/v/checker/tests/struct_option_field_assign_ptr_err.out b/vlib/v/checker/tests/struct_option_field_assign_ptr_err.out new file mode 100644 index 000000000..c20705b62 --- /dev/null +++ b/vlib/v/checker/tests/struct_option_field_assign_ptr_err.out @@ -0,0 +1,14 @@ +vlib/v/checker/tests/struct_option_field_assign_ptr_err.vv:10:3: error: cannot assign a pointer to option struct field + 8 | name := 'Bilbo' + 9 | a := Abc{ + 10 | age: &age + | ~~~~~~ + 11 | } + 12 | b := Abc{ +vlib/v/checker/tests/struct_option_field_assign_ptr_err.vv:13:3: error: cannot assign a pointer to option struct field + 11 | } + 12 | b := Abc{ + 13 | name: &name + | ~~~~~~~ + 14 | } + 15 | dump(a) diff --git a/vlib/v/checker/tests/struct_option_field_assign_ptr_err.vv b/vlib/v/checker/tests/struct_option_field_assign_ptr_err.vv new file mode 100644 index 000000000..43a73c19d --- /dev/null +++ b/vlib/v/checker/tests/struct_option_field_assign_ptr_err.vv @@ -0,0 +1,17 @@ +struct Abc { + name ?string + age ?int +} + +fn main() { + age := 34 + name := 'Bilbo' + a := Abc{ + age: &age + } + b := Abc{ + name: &name + } + dump(a) + dump(b) +} -- 2.39.5