From ba036ebf14bd4b6bafd0cc221cb759b465ab72bd Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Tue, 24 Dec 2024 14:57:19 -0300 Subject: [PATCH] cgen: fix casting aliased fixed array to sumtype array (fix #23009) (#23248) --- vlib/v/gen/c/cgen.v | 6 ++++-- .../v/tests/aliases/alias_array_fixed_sumtype_test.v | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/aliases/alias_array_fixed_sumtype_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index fb698b0e559a60..a2f6f8784f1bd7 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2695,8 +2695,10 @@ fn (mut g Gen) call_cfn_for_casting_expr(fname string, expr ast.Expr, exp_is_ptr } g.write('${fname}(') if !got_is_ptr && !got_is_fn { - if is_comptime_variant || !expr.is_lvalue() - || (expr is ast.Ident && expr.obj.is_simple_define_const()) { + is_cast_fixed_array_init := expr is ast.CastExpr + && (expr.expr is ast.ArrayInit && expr.expr.is_fixed) + if !is_cast_fixed_array_init && (is_comptime_variant || !expr.is_lvalue() + || (expr is ast.Ident && expr.obj.is_simple_define_const())) { // Note: the `_to_sumtype_` family of functions do call memdup internally, making // another duplicate with the HEAP macro is redundant, so use ADDR instead: if expr.is_as_cast() { diff --git a/vlib/v/tests/aliases/alias_array_fixed_sumtype_test.v b/vlib/v/tests/aliases/alias_array_fixed_sumtype_test.v new file mode 100644 index 00000000000000..2058bfe0ea0423 --- /dev/null +++ b/vlib/v/tests/aliases/alias_array_fixed_sumtype_test.v @@ -0,0 +1,12 @@ +module main + +type IPv4 = [4]u8 +type IPv6 = [16]u8 +type IP = IPv4 | IPv6 + +fn test_main() { + mut arr := []IP{} + arr << IP(IPv4([4]u8{})) + arr << IP(IPv6([16]u8{})) + assert arr.str() == '[IP(IPv4([0, 0, 0, 0])), IP(IPv6([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]))]' +}