From 1937cdd8419fe75a50a8c670ba01f0c1021ac7e2 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 2 Nov 2024 09:09:55 -0300 Subject: [PATCH] checker: fix none check for match expr with option (fix #22728) (#22732) --- vlib/v/checker/match.v | 2 +- .../tests/match_option_without_none_err.out | 7 +++++++ .../tests/match_option_without_none_err.vv | 19 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/match_option_without_none_err.out create mode 100644 vlib/v/checker/tests/match_option_without_none_err.vv diff --git a/vlib/v/checker/match.v b/vlib/v/checker/match.v index 68c91946a..191d002f4 100644 --- a/vlib/v/checker/match.v +++ b/vlib/v/checker/match.v @@ -55,7 +55,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type { branch.branch_pos) } } - if !branch.is_else && cond_is_option && branch.exprs[0] !is ast.None { + if !branch.is_else && cond_is_option && branch.exprs.any(it !is ast.None) { c.error('`match` expression with Option type only checks against `none`, to match its value you must unwrap it first `var?`', branch.pos) } diff --git a/vlib/v/checker/tests/match_option_without_none_err.out b/vlib/v/checker/tests/match_option_without_none_err.out new file mode 100644 index 000000000..32b1524ba --- /dev/null +++ b/vlib/v/checker/tests/match_option_without_none_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/match_option_without_none_err.vv:16:3: error: `match` expression with Option type only checks against `none`, to match its value you must unwrap it first `var?` + 14 | match p.part { + 15 | // Next weird line crashes compiler before sugesting 'unwrap' var? + 16 | none, 1 { return '' } + | ~~~~~~~ + 17 | else { return '${p.part}' } + 18 | } diff --git a/vlib/v/checker/tests/match_option_without_none_err.vv b/vlib/v/checker/tests/match_option_without_none_err.vv new file mode 100644 index 000000000..9cb43570b --- /dev/null +++ b/vlib/v/checker/tests/match_option_without_none_err.vv @@ -0,0 +1,19 @@ +pub struct Post { + part ?u8 +} + +fn (p Post) get_part_1() string { + part := p.part or { return '' } + match part { + 0 { return '' } + else { return '${part}' } + } +} + +fn (p Post) get_part_2() string { + match p.part { + // Next weird line crashes compiler before sugesting 'unwrap' var? + none, 1 { return '' } + else { return '${p.part}' } + } +} -- 2.39.5