From 942a1dd786aff5e678cf7d0d3648971d0190ea31 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Thu, 26 Feb 2026 11:22:40 +0300 Subject: [PATCH] parser: fix compiler does not infer field type and raise inappropriate error when initializing struct (fixes #14762) --- vlib/v/parser/struct.v | 10 ++++++++++ ..._init_array_field_with_curly_braces_err.out | 7 +++++++ ...t_init_array_field_with_curly_braces_err.vv | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.out create mode 100644 vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.vv diff --git a/vlib/v/parser/struct.v b/vlib/v/parser/struct.v index 0ae449fea..37737528d 100644 --- a/vlib/v/parser/struct.v +++ b/vlib/v/parser/struct.v @@ -649,6 +649,16 @@ fn (mut p Parser) struct_init(typ_str string, kind ast.StructInitKind, is_option } } p.check(.colon) + if p.tok.kind == .lcbr && typ != ast.void_type { + struct_sym := p.table.final_sym(p.table.unaliased_type(typ)) + if field := struct_sym.find_field(field_name) { + field_sym := p.table.final_sym(p.table.unaliased_type(field.typ)) + if field_sym.kind in [.array, .array_fixed] { + p.error_with_pos('cannot use `{}` for array field `${field_name}`; use `[]` instead', + p.tok.pos()) + } + } + } expr = p.expr(0) end_comments = p.eat_comments(same_line: true) last_field_pos := expr.pos() diff --git a/vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.out b/vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.out new file mode 100644 index 000000000..7e62a99d5 --- /dev/null +++ b/vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.vv:13:9: error: cannot use `{}` for array field `foos`; use `[]` instead + 11 | fn main() { + 12 | _ := Bar{ + 13 | foos: { + | ^ + 14 | new_foo() + 15 | new_foo() diff --git a/vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.vv b/vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.vv new file mode 100644 index 000000000..3e53df339 --- /dev/null +++ b/vlib/v/parser/tests/struct_init_array_field_with_curly_braces_err.vv @@ -0,0 +1,18 @@ +struct Foo {} + +fn new_foo() Foo { + return Foo{} +} + +struct Bar { + foos []Foo +} + +fn main() { + _ := Bar{ + foos: { + new_foo() + new_foo() + } + } +} -- 2.39.5