From fde951652c7983d13036b59b8150e61ae00069e9 Mon Sep 17 00:00:00 2001 From: Jose Mendoza <56417208+StunxFS@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:06:45 -0400 Subject: [PATCH] checker: clarify error message about using empty map literal to initialize structs (fix #22498) (#22534) --- vlib/v/checker/containers.v | 19 ++++++++++++------- ...iteral_to_initialize_anon_struct_error.out | 7 +++++++ ...literal_to_initialize_anon_struct_error.vv | 11 +++++++++++ 3 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out create mode 100644 vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv diff --git a/vlib/v/checker/containers.v b/vlib/v/checker/containers.v index c5ae14777..8ff9283f9 100644 --- a/vlib/v/checker/containers.v +++ b/vlib/v/checker/containers.v @@ -432,16 +432,21 @@ fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type { node.key_type = info.key_type node.value_type = info.value_type return node.typ - } else { - if sym.kind == .struct { - c.error('`{}` can not be used for initialising empty structs any more. Use `${c.table.type_to_str(c.expected_type)}{}` instead.', - node.pos) + } else if sym.info is ast.Struct { + msg := if sym.info.is_anon { + '`{}` cannot be used to initialize anonymous structs. Use `struct{}` instead.' } else { - c.error('invalid empty map initialisation syntax, use e.g. map[string]int{} instead', - node.pos) + '`{}` can not be used for initialising empty structs any more. Use `${c.table.type_to_str(c.expected_type)}{}` instead.' } - return ast.void_type + c.error(msg, node.pos) + if sym.info.is_anon { + return c.expected_type + } + } else { + c.error('invalid empty map initialisation syntax, use e.g. map[string]int{} instead', + node.pos) } + return ast.void_type } // `x := map[string]string` - set in parser if node.typ != 0 { diff --git a/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out new file mode 100644 index 000000000..7f5410f08 --- /dev/null +++ b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv:9:22: error: `{}` cannot be used to initialize anonymous structs. Use `struct{}` instead. + 7 | + 8 | fn main() { + 9 | s := AStructName{5, {}} + | ~~ + 10 | println(s) + 11 | } diff --git a/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv new file mode 100644 index 000000000..81f99bd9b --- /dev/null +++ b/vlib/v/checker/tests/use_empty_map_literal_to_initialize_anon_struct_error.vv @@ -0,0 +1,11 @@ +struct AStructName { + foo int + anon struct { + bar int + } +} + +fn main() { + s := AStructName{5, {}} + println(s) +} -- 2.39.5