From 3e33f4a11d3d30cc92080eb9bfcea6a9f15ac3b5 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Thu, 13 Oct 2022 13:06:59 +0530 Subject: [PATCH] checker: disallow nil assignment on non pointer struct fields (#16056) --- vlib/v/checker/struct.v | 6 ++++++ .../tests/struct_non_ptr_field_nil_default_value_err.out | 7 +++++++ .../tests/struct_non_ptr_field_nil_default_value_err.vv | 9 +++++++++ 3 files changed, 22 insertions(+) create mode 100644 vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.out create mode 100644 vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.vv diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index 3231603977..e16686e297 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -116,6 +116,12 @@ pub fn (mut c Checker) struct_decl(mut node ast.StructDecl) { } continue } + if field.default_expr is ast.UnsafeExpr { + if field.default_expr.expr is ast.Nil && !field.typ.is_ptr() + && c.table.sym(field.typ).kind != .function && !field.typ.is_pointer() { + c.error('cannot assign `nil` to a non-pointer field', field.type_pos) + } + } if field.default_expr is ast.IntegerLiteral { if field.default_expr.val == '0' { c.warn('unnecessary default value of `0`: struct fields are zeroed by default', diff --git a/vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.out b/vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.out new file mode 100644 index 0000000000..0e942cf0a4 --- /dev/null +++ b/vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.vv:4:7: error: cannot assign `nil` to a non-pointer field + 2 | + 3 | struct Foo { + 4 | bar SomeInterface = unsafe{ nil } + | ~~~~~~~~~~~~~ + 5 | } + 6 | fn main() { diff --git a/vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.vv b/vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.vv new file mode 100644 index 0000000000..a166df9436 --- /dev/null +++ b/vlib/v/checker/tests/struct_non_ptr_field_nil_default_value_err.vv @@ -0,0 +1,9 @@ +interface SomeInterface{} + +struct Foo { + bar SomeInterface = unsafe{ nil } +} +fn main() { + foo := Foo{} + dump(foo) +}