From fe9f97074bf0ad936d981940d6a734af1b7a20a8 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 14 May 2022 22:49:42 +0800 Subject: [PATCH] cgen: fix appending struct to interface array (#14388) --- vlib/v/gen/c/struct.v | 4 ++ .../append_struct_to_interface_array_test.v | 43 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 vlib/v/tests/append_struct_to_interface_array_test.v diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index 29fb490bbd..babf7fc7b3 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -183,6 +183,9 @@ fn (mut g Gen) struct_init(node ast.StructInit) { } } if !cloned { + inside_cast_in_heap := g.inside_cast_in_heap + g.inside_cast_in_heap = 0 // prevent use of pointers in child structs + if field_type_sym.kind == .array_fixed && sfield.expr is ast.Ident { fixed_array_info := field_type_sym.info as ast.ArrayFixed g.write('{') @@ -202,6 +205,7 @@ fn (mut g Gen) struct_init(node ast.StructInit) { } g.expr_with_cast(sfield.expr, sfield.typ, sfield.expected_type) } + g.inside_cast_in_heap = inside_cast_in_heap // restore value for further struct inits } if is_multiline { g.writeln(',') diff --git a/vlib/v/tests/append_struct_to_interface_array_test.v b/vlib/v/tests/append_struct_to_interface_array_test.v new file mode 100644 index 0000000000..946b03388f --- /dev/null +++ b/vlib/v/tests/append_struct_to_interface_array_test.v @@ -0,0 +1,43 @@ +struct Vec { +mut: + x f64 + y f64 + z f64 +} + +struct Plane { + position Vec + normal Vec +} + +struct Sphere { + position Vec + radius f64 +} + +interface Object { + position Vec +} + +fn test_append_struct_to_interface_array() { + mut scene := []Object{} + + scene << Plane{ + position: Vec{0, -10, 0} + normal: Vec{0, -1, 0} + } + scene << Sphere{ + position: Vec{0, 0, -20} + radius: 7 + } + + println(scene) + + assert scene.len == 2 + assert scene[0].position.x == 0 + assert scene[0].position.y == -10 + assert scene[0].position.z == 0 + assert scene[1].position.x == 0 + assert scene[1].position.y == 0 + assert scene[1].position.z == -20 +}