From 30ac2e8763a1b21bab003e4d596333725d04d862 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Thu, 27 Apr 2023 20:24:26 +0530 Subject: [PATCH] checker: disallow assigning anon `struct` to typed `struct` (#18017) --- vlib/v/checker/struct.v | 8 ++++++++ .../assign_anon_struct_to_typed_struct_err.out | 7 +++++++ .../assign_anon_struct_to_typed_struct_err.vv | 16 ++++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.out create mode 100644 vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.vv diff --git a/vlib/v/checker/struct.v b/vlib/v/checker/struct.v index 337d76fa3..766fcc1ff 100644 --- a/vlib/v/checker/struct.v +++ b/vlib/v/checker/struct.v @@ -574,6 +574,14 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini } } } + + if field_type_sym.kind == .struct_ && !(field_type_sym.info as ast.Struct).is_anon + && mut field.expr is ast.StructInit { + if field.expr.is_anon { + c.error('cannot assign anonymous `struct` to a typed `struct`', + field.expr.pos) + } + } } // Check uninitialized refs/sum types // The variable `fields` contains two parts, the first part is the same as info.fields, diff --git a/vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.out b/vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.out new file mode 100644 index 000000000..9d2cf1528 --- /dev/null +++ b/vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.vv:11:18: error: cannot assign anonymous `struct` to a typed `struct` + 9 | + 10 | f := Fax{ + 11 | message: struct { + | ^ + 12 | a: 'A' + 13 | } diff --git a/vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.vv b/vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.vv new file mode 100644 index 000000000..f8daedd5b --- /dev/null +++ b/vlib/v/checker/tests/assign_anon_struct_to_typed_struct_err.vv @@ -0,0 +1,16 @@ +struct Message { + a string + b string +} + +struct Fax { + message Message +} + +f := Fax{ + message: struct { + a: 'A' + } +} + +dump(f) -- 2.39.5