From 066f825dea7b10c4588a17da727d9af39c3c5721 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 15 Dec 2024 17:44:56 -0300 Subject: [PATCH] cgen: fix fixed array option cast with `none` (fix #23164) (#23168) --- vlib/v/gen/c/cgen.v | 10 +++++--- vlib/v/tests/alias_cast_to_fixed_array_test.v | 24 +++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/alias_cast_to_fixed_array_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 7b5a03e07d..909660238b 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -5364,10 +5364,14 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) { g.expr(node.expr) g.write('))') } else if sym.kind == .alias && g.table.final_sym(node.typ).kind == .array_fixed { - if node.expr is ast.ArrayInit && g.assign_op != .decl_assign { - g.write('(${g.styp(node.expr.typ)})') + if node.typ.has_flag(.option) { + g.expr_with_opt(node.expr, expr_type, node.typ) + } else { + if node.expr is ast.ArrayInit && g.assign_op != .decl_assign { + g.write('(${g.styp(node.expr.typ)})') + } + g.expr(node.expr) } - g.expr(node.expr) } else if expr_type == ast.bool_type && node.typ.is_int() { styp := g.styp(node_typ) g.write('(${styp}[]){(') diff --git a/vlib/v/tests/alias_cast_to_fixed_array_test.v b/vlib/v/tests/alias_cast_to_fixed_array_test.v new file mode 100644 index 0000000000..fc3e0eefa3 --- /dev/null +++ b/vlib/v/tests/alias_cast_to_fixed_array_test.v @@ -0,0 +1,24 @@ +type Bytes = [3]u8 +type Strs = [3]string + +fn test_none() { + b := ?Bytes(none) + println(b) + assert b == none + + c := ?Strs(none) + println(c) + assert c == none +} + +fn test_non_none() { + b := ?Bytes([u8(1), 2, 3]!) + println(b) + assert b != none + assert b?[2] == 3 + + c := ?Strs(['a', 'b', 'c']!) + println(c) + assert c != none + assert c?[2] == 'c' +}