From ef9bb8e628f3421447920d871b5f01c34af00f6b Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 18 May 2025 02:38:02 -0300 Subject: [PATCH] cgen: fix codegen for assigning `nil` or `0` to option ptr field (fix #24447) (fix #24500) (#24502) --- vlib/v/gen/c/cgen.v | 3 ++- vlib/v/tests/options/option_ptr_nil_test.v | 21 ++++++++++++++++ vlib/v/tests/options/option_ptr_zero_test.v | 28 +++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/options/option_ptr_nil_test.v create mode 100644 vlib/v/tests/options/option_ptr_zero_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index f819c3795..becea50fb 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2333,7 +2333,8 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T } } } - if ret_typ.nr_muls() > expr_typ.nr_muls() { + if !expr.is_literal() && expr_typ != ast.nil_type + && ret_typ.nr_muls() > expr_typ.nr_muls() { g.write('&'.repeat(ret_typ.nr_muls() - expr_typ.nr_muls())) } } diff --git a/vlib/v/tests/options/option_ptr_nil_test.v b/vlib/v/tests/options/option_ptr_nil_test.v new file mode 100644 index 000000000..f27280f88 --- /dev/null +++ b/vlib/v/tests/options/option_ptr_nil_test.v @@ -0,0 +1,21 @@ +struct Foo { + name ?&string +} + +struct Foo2 { +mut: + name ?&string +} + +fn test_1() { + _ := Foo{ + name: unsafe { nil } + } +} + +fn test_2() { + mut foo := Foo2{} + unsafe { + foo.name = nil + } +} diff --git a/vlib/v/tests/options/option_ptr_zero_test.v b/vlib/v/tests/options/option_ptr_zero_test.v new file mode 100644 index 000000000..a05955909 --- /dev/null +++ b/vlib/v/tests/options/option_ptr_zero_test.v @@ -0,0 +1,28 @@ +// Simple arena allocator +struct ArenaChunk { +mut: + next ?&ArenaChunk + used int + cap int + data byteptr +} + +struct Arena { +mut: + head ?&ArenaChunk +} + +fn arena_init(mut arena Arena, first_capacity int) { + chunk := &ArenaChunk{ + next: 0 + used: 0 + cap: first_capacity + data: unsafe { malloc(first_capacity) } + } + arena.head = chunk +} + +fn test_main() { + mut green_arena := Arena{} + arena_init(mut green_arena, 64 * 1024) +} -- 2.39.5