From bb2ddb98a35eccc9365264191942adf41bfa6204 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 18 Mar 2022 22:49:20 +0800 Subject: [PATCH] parser: check if guard condition (#13765) --- vlib/v/parser/if_match.v | 4 ++++ vlib/v/parser/tests/if_guard_cond_err.out | 7 ++++++ vlib/v/parser/tests/if_guard_cond_err.vv | 28 +++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 vlib/v/parser/tests/if_guard_cond_err.out create mode 100644 vlib/v/parser/tests/if_guard_cond_err.vv diff --git a/vlib/v/parser/if_match.v b/vlib/v/parser/if_match.v index 0bad3f9a63..0a993d033f 100644 --- a/vlib/v/parser/if_match.v +++ b/vlib/v/parser/if_match.v @@ -107,6 +107,10 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr { p.check(.decl_assign) comments << p.eat_comments() expr := p.expr(0) + if expr !in [ast.CallExpr, ast.IndexExpr, ast.PrefixExpr] { + p.error_with_pos('if guard condition expression is illegal, it should return optional', + expr.pos()) + } cond = ast.IfGuardExpr{ vars: vars diff --git a/vlib/v/parser/tests/if_guard_cond_err.out b/vlib/v/parser/tests/if_guard_cond_err.out new file mode 100644 index 0000000000..70a11b41f5 --- /dev/null +++ b/vlib/v/parser/tests/if_guard_cond_err.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/if_guard_cond_err.vv:16:16: error: if guard condition expression is illegal, it should return optional + 14 | fp.usage_example('GOOG AAPL') + 15 | _ := fp.bool('version', `v`, false, 'version information.') + 16 | if args := fp.finalize() && args.len > 0 { + | ~~~~~~~~~~~~~~~~~~~~~~~~~~ + 17 | return args + 18 | } else { diff --git a/vlib/v/parser/tests/if_guard_cond_err.vv b/vlib/v/parser/tests/if_guard_cond_err.vv new file mode 100644 index 0000000000..69de3f19ec --- /dev/null +++ b/vlib/v/parser/tests/if_guard_cond_err.vv @@ -0,0 +1,28 @@ +import os +import flag + +const version = "v0.1.0" + +// getting command line options and arguments +// returns the arguments +fn get_args() ?[]string { + mut fp := flag.new_flag_parser(os.args) + fp.application('ticker') + fp.version(version) + fp.description('A CLI yahoo ticker app') + fp.skip_executable() + fp.usage_example('GOOG AAPL') + _ := fp.bool('version', `v`, false, 'version information.') + if args := fp.finalize() && args.len > 0 { + return args + } else { + eprintln(err.msg()) + println(fp.usage()) + return none + } +} + +fn main() { + tickers := get_args() or { return } + println(tickers) +}