From 41b782c0965b13b9d43e5dbb4ab481755a9dffa9 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 8 Sep 2024 10:30:44 +0800 Subject: [PATCH] parser: fix parsing map value inside or expr --- vlib/v/parser/parser.v | 19 +++++++++++----- .../printing_option_or_expr_with_map_val.out | 1 + .../printing_option_or_expr_with_map_val.vv | 22 +++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.out create mode 100644 vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.vv diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 86a00278bb17a5..18754c77b770b9 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -950,11 +950,20 @@ fn (mut p Parser) stmt(is_top_level bool) ast.Stmt { match p.tok.kind { .lcbr { mut pos := p.tok.pos() - stmts := p.parse_block() - pos.last_line = p.prev_tok.line_nr - return ast.Block{ - stmts: stmts - pos: pos + if p.peek_token(2).kind == .colon { + expr := p.expr(0) + // `{ 'abc' : 22 }` + return ast.ExprStmt{ + expr: expr + pos: pos + } + } else { + stmts := p.parse_block() + pos.last_line = p.prev_tok.line_nr + return ast.Block{ + stmts: stmts + pos: pos + } } } .key_assert { diff --git a/vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.out b/vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.out new file mode 100644 index 00000000000000..71e24d60d74e3d --- /dev/null +++ b/vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.out @@ -0,0 +1 @@ +MapString({'abc': 'String Error'}) diff --git a/vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.vv b/vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.vv new file mode 100644 index 00000000000000..3fb3e93686ece8 --- /dev/null +++ b/vlib/v/slow_tests/inout/printing_option_or_expr_with_map_val.vv @@ -0,0 +1,22 @@ +struct MyError { + msg string + code int +} + +fn (my MyError) msg() string { + return my.msg +} + +fn (my MyError) code() int { + return my.code +} + +type MapString = map[string]string | int + +fn f() ?MapString { + return MyError{msg: 'String Error'} +} + +fn main() { + println(f() or { { 'abc': err.msg() } }) +}