From ac136c08e64d7e58fa5b7324cda93dd1380c8f3a Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 27 Jul 2024 19:30:19 -0300 Subject: [PATCH] cgen: fix struct ref field with no ref structinit (#21932) --- vlib/net/http/download_progress.v | 2 +- vlib/v/checker/struct.v | 5 +++++ vlib/v/checker/tests/struct_ref_field_no_ptr_err.out | 6 ++++++ vlib/v/checker/tests/struct_ref_field_no_ptr_err.vv | 7 +++++++ 4 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/struct_ref_field_no_ptr_err.out create mode 100644 vlib/v/checker/tests/struct_ref_field_no_ptr_err.vv diff --git a/vlib/net/http/download_progress.v b/vlib/net/http/download_progress.v index 9811f3e70f..f8c9d87e6d 100644 --- a/vlib/net/http/download_progress.v +++ b/vlib/net/http/download_progress.v @@ -23,7 +23,7 @@ mut: pub struct DownloaderParams { FetchConfig pub mut: - downloader &Downloader = TerminalStreamingDownloader{} + downloader &Downloader = &TerminalStreamingDownloader{} } // download_file_with_progress will save the URL `url` to the filepath `path` . diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index 78e5d99ada..83eb8b6ab4 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -111,6 +111,11 @@ fn (mut c Checker) struct_decl(mut node ast.StructDecl) { if field.has_default_expr { c.expected_type = field.typ field.default_expr_typ = c.expr(mut field.default_expr) + if field.typ.is_ptr() && !field.default_expr_typ.is_ptr() + && field.default_expr is ast.StructInit { + c.error('reference field must be initialized with reference', field.default_expr.pos()) + } + // disallow map `mut a = b` field_sym := c.table.sym(field.typ) expr_sym := c.table.sym(field.default_expr_typ) diff --git a/vlib/v/checker/tests/struct_ref_field_no_ptr_err.out b/vlib/v/checker/tests/struct_ref_field_no_ptr_err.out new file mode 100644 index 0000000000..3d6231d2ea --- /dev/null +++ b/vlib/v/checker/tests/struct_ref_field_no_ptr_err.out @@ -0,0 +1,6 @@ +vlib/v/checker/tests/struct_ref_field_no_ptr_err.vv:2:13: error: reference field must be initialized with reference + 1 | struct Foo { + 2 | bar &Bar = Bar{} + | ~~~~~ + 3 | } + 4 | diff --git a/vlib/v/checker/tests/struct_ref_field_no_ptr_err.vv b/vlib/v/checker/tests/struct_ref_field_no_ptr_err.vv new file mode 100644 index 0000000000..668441a253 --- /dev/null +++ b/vlib/v/checker/tests/struct_ref_field_no_ptr_err.vv @@ -0,0 +1,7 @@ +struct Foo { + bar &Bar = Bar{} +} + +struct Bar { + field int +}