From d7501cc9a128fb736193ef5b318927d6b5e77663 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 22 Aug 2022 18:32:27 +0800 Subject: [PATCH] cgen: fix if sumtype var is none (#15496) --- vlib/v/gen/c/infix.v | 6 +++- .../inout/printing_sumtype_with_none.out | 3 ++ .../tests/inout/printing_sumtype_with_none.vv | 35 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/inout/printing_sumtype_with_none.out create mode 100644 vlib/v/tests/inout/printing_sumtype_with_none.vv diff --git a/vlib/v/gen/c/infix.v b/vlib/v/gen/c/infix.v index 764c5519ba..6bfc783dc5 100644 --- a/vlib/v/gen/c/infix.v +++ b/vlib/v/gen/c/infix.v @@ -619,7 +619,11 @@ fn (mut g Gen) infix_expr_is_op(node ast.InfixExpr) { } else if left_sym.kind == .sum_type { g.write('_typ $cmp_op ') } - g.expr(node.right) + if node.right is ast.None { + g.write('$ast.none_type.idx() /* none */') + } else { + g.expr(node.right) + } } fn (mut g Gen) gen_interface_is_op(node ast.InfixExpr) { diff --git a/vlib/v/tests/inout/printing_sumtype_with_none.out b/vlib/v/tests/inout/printing_sumtype_with_none.out new file mode 100644 index 0000000000..44c82a78e8 --- /dev/null +++ b/vlib/v/tests/inout/printing_sumtype_with_none.out @@ -0,0 +1,3 @@ +first field is a string +second field is none +third field is None diff --git a/vlib/v/tests/inout/printing_sumtype_with_none.vv b/vlib/v/tests/inout/printing_sumtype_with_none.vv new file mode 100644 index 0000000000..0ff2db2551 --- /dev/null +++ b/vlib/v/tests/inout/printing_sumtype_with_none.vv @@ -0,0 +1,35 @@ +module main + +struct None {} + +struct MyStruct { + my_first_field string|none + my_second_field string|none + my_third_field string|None +} + +fn main() { + s := MyStruct{ + my_first_field: 'blah' + my_second_field: none + my_third_field: None{} + } + + println(if s.my_first_field is string { + 'first field is a string' + } else { + 'first field is none' + }) + + println(if s.my_second_field is none { + 'second field is none' + } else { + 'second field is a string' + }) + + println(if s.my_third_field is None { + 'third field is None' + } else { + 'third field is a string' + }) +}