From 16ead4e63ceded9c3184bf3dcc8423bdc0bdcf36 Mon Sep 17 00:00:00 2001 From: Julien de Carufel Date: Sat, 16 Apr 2022 06:23:19 -0400 Subject: [PATCH] cgen: fix infix generics bug (#14048) --- vlib/v/gen/c/infix_expr.v | 12 ++++++--- .../generic_empty_interface_to_struct_test.v | 25 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/generic_empty_interface_to_struct_test.v diff --git a/vlib/v/gen/c/infix_expr.v b/vlib/v/gen/c/infix_expr.v index 449c28ed52..88bb1f8bdc 100644 --- a/vlib/v/gen/c/infix_expr.v +++ b/vlib/v/gen/c/infix_expr.v @@ -515,9 +515,15 @@ fn (mut g Gen) infix_expr_is_op(node ast.InfixExpr) { g.write('_typ $cmp_op ') // `_Animal_Dog_index` sub_type := match node.right { - ast.TypeNode { node.right.typ } - ast.None { g.table.type_idxs['None__'] } - else { ast.Type(0) } + ast.TypeNode { + g.unwrap_generic(node.right.typ) + } + ast.None { + g.table.type_idxs['None__'] + } + else { + ast.Type(0) + } } sub_sym := g.table.sym(sub_type) g.write('_${sym.cname}_${sub_sym.cname}_index') diff --git a/vlib/v/tests/generic_empty_interface_to_struct_test.v b/vlib/v/tests/generic_empty_interface_to_struct_test.v new file mode 100644 index 0000000000..783da30bbe --- /dev/null +++ b/vlib/v/tests/generic_empty_interface_to_struct_test.v @@ -0,0 +1,25 @@ +interface Any {} + +struct Concrete { + a int +} + +struct Container { + concrete Any +} + +fn (container &Container) get_first_struct() ?&T { + concrete := container.concrete + if concrete is T { + println(concrete.a) + return concrete + } + return error("can't cast") +} + +fn test_generic_empty_interface_to_struct() { + concrete := Concrete{12345} + container := Container{concrete} + cast_concrete := container.get_first_struct() or { &Concrete{} } + assert 12345 == cast_concrete.a +}