From 74d55eff945851f941ce98b8c5ded99a28101c44 Mon Sep 17 00:00:00 2001 From: CreeperFace <165158232+dy-tea@users.noreply.github.com> Date: Sat, 6 Dec 2025 09:11:10 +0000 Subject: [PATCH] ast,cgen: fallback to field type when default_expr_typ is 0 (fix #25891) (#25903) --- vlib/v/ast/table.v | 15 +++++++++++++++ vlib/v/gen/c/cgen.v | 11 +++++++++-- vlib/v/tests/global_generic_sumtype_test.v | 15 +++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/global_generic_sumtype_test.v diff --git a/vlib/v/ast/table.v b/vlib/v/ast/table.v index 142cb810e..6a5434418 100644 --- a/vlib/v/ast/table.v +++ b/vlib/v/ast/table.v @@ -2219,6 +2219,21 @@ pub fn (mut t Table) unwrap_generic_type_ex(typ Type, generic_names []string, co } } } + if fields[i].has_default_expr { + if fields[i].default_expr_typ.has_flag(.generic) { + if t_typ := t.convert_generic_type(fields[i].default_expr_typ, + t_generic_names, t_concrete_types) + { + fields[i].default_expr_typ = t_typ + } + } else if fields[i].default_expr_typ == 0 + || fields[i].default_expr_typ == nil_type { + if fields[i].default_expr.is_nil() + && fields[i].typ.is_any_kind_of_pointer() { + fields[i].default_expr_typ = fields[i].typ + } + } + } } // update concrete types for i in 0 .. ts.info.generic_types.len { diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index eaf59806d..af4911b78 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -7689,8 +7689,15 @@ fn (mut g Gen) type_default_impl(typ_ ast.Type, decode_sumtype bool) string { if field.has_default_expr { mut expr_str := '' if field_sym.kind in [.sum_type, .interface] { + default_expr_typ := if field.default_expr_typ == 0 + && field.default_expr.is_nil() + && field.typ.is_any_kind_of_pointer() { + field.typ + } else { + field.default_expr_typ + } expr_str = g.expr_string_with_cast(field.default_expr, - field.default_expr_typ, field.typ) + default_expr_typ, field.typ) } else if field_sym.is_array_fixed() && g.inside_global_decl { array_info := field_sym.array_fixed_info() match field.default_expr { @@ -7739,7 +7746,7 @@ fn (mut g Gen) type_default_impl(typ_ ast.Type, decode_sumtype bool) string { zero_str := if field_sym.language == .v && field_sym.info is ast.Struct && field_sym.info.is_empty_struct() { '{E_STRUCT}' - } else if field_sym.kind == .sum_type { + } else if field_sym.kind == .sum_type && !field.typ.is_ptr() { if decode_sumtype { g.type_default_sumtype(field.typ, field_sym) } else { diff --git a/vlib/v/tests/global_generic_sumtype_test.v b/vlib/v/tests/global_generic_sumtype_test.v new file mode 100644 index 000000000..965cfbfc5 --- /dev/null +++ b/vlib/v/tests/global_generic_sumtype_test.v @@ -0,0 +1,15 @@ +@[has_globals] +module main + +__global queue2 Queue[Event] + +type Event = int | u32 + +struct Queue[T] { +mut: + data &T +} + +fn test_main() { + assert queue2.data == unsafe { nil } +} -- 2.39.5