From 28f85371b153c22dccbc66506dc9253c7ae86c64 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Wed, 26 Apr 2023 14:40:28 -0300 Subject: [PATCH] cgen: fix comptime ptr comparison generated code (#18048) --- vlib/v/gen/c/infix.v | 4 ++- .../v/tests/comptime_indirection_check_test.v | 35 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/comptime_indirection_check_test.v diff --git a/vlib/v/gen/c/infix.v b/vlib/v/gen/c/infix.v index 95d140dfa6..12c816588b 100644 --- a/vlib/v/gen/c/infix.v +++ b/vlib/v/gen/c/infix.v @@ -100,7 +100,9 @@ fn (mut g Gen) infix_expr_eq_op(node ast.InfixExpr) { is_none_check := node.left_type.has_flag(.option) && node.right is ast.None if is_none_check { g.gen_is_none_check(node) - } else if (left.typ.is_ptr() && right.typ.is_int()) || (right.typ.is_ptr() && left.typ.is_int()) { + } else if (left.typ.is_ptr() && right.typ.is_int()) + || (right.typ.is_ptr() && left.typ.is_int()) + || (left.typ.is_ptr() && right.typ == ast.nil_type) { g.gen_plain_infix_expr(node) } else if (left.typ.idx() == ast.string_type_idx || (!has_defined_eq_operator && left.unaliased.idx() == ast.string_type_idx)) && node.right is ast.StringLiteral diff --git a/vlib/v/tests/comptime_indirection_check_test.v b/vlib/v/tests/comptime_indirection_check_test.v new file mode 100644 index 0000000000..b4bc140ab0 --- /dev/null +++ b/vlib/v/tests/comptime_indirection_check_test.v @@ -0,0 +1,35 @@ +struct Encoder {} + +struct Writer {} + +struct StructTypePointer[T] { +mut: + val &T +} + +pub fn (e &Encoder) encode_value[T](val T, mut wr Writer) ! { + assert e.encode_struct[T](val, 1, mut wr)! == 'a' +} + +fn (e &Encoder) encode_struct[U](val U, level int, mut wr Writer) !string { + $for field in U.fields { + if val.$(field.name) != unsafe { nil } { + $if field.indirections > 0 { + assert field.indirections == 1 + return 'a' + } $else { + return 'b' + } + } + } + return 'z' +} + +fn test_check() { + e := Encoder{} + mut sb := Writer{} + + mut string_initialized_with_reference := 'ads' + e.encode_value(StructTypePointer[string]{ val: &string_initialized_with_reference }, mut + sb) or {} +}