From 8dbde185ef05fc07f0e8bdb119c43c58387b533d Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Fri, 28 Feb 2025 17:36:28 -0300 Subject: [PATCH] checker: add option type inference on if expr (implement most of #23827, except the error for `v := if c { none } else { none }`) (#23829) --- vlib/v/checker/if.v | 9 +++++++++ vlib/v/tests/options/option_if_infer_test.v | 8 ++++++++ 2 files changed, 17 insertions(+) create mode 100644 vlib/v/tests/options/option_if_infer_test.v diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index 3ae6d391a6..b3f3ac78f5 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -510,6 +510,15 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { stmt.typ = ast.error_type continue } + if (node.typ == ast.none_type && stmt.typ != ast.none_type) + || (stmt.typ == ast.none_type && node.typ != ast.none_type) { + node.typ = if stmt.typ != ast.none_type { + stmt.typ.set_flag(.option) + } else { + node.typ.set_flag(.option) + } + continue + } c.error('mismatched types `${c.table.type_to_str(node.typ)}` and `${c.table.type_to_str(stmt.typ)}`', node.pos) } else { diff --git a/vlib/v/tests/options/option_if_infer_test.v b/vlib/v/tests/options/option_if_infer_test.v new file mode 100644 index 0000000000..f577cc7d3d --- /dev/null +++ b/vlib/v/tests/options/option_if_infer_test.v @@ -0,0 +1,8 @@ +fn test_main() { + v := if true { none } else { 1 } + assert '${v}' == 'Option(none)' + v2 := if false { 1 } else { none } + assert '${v2}' == 'Option(none)' + v3 := if true { 1 } else { none } + assert '${v3}' == 'Option(1)' +}