From 740a862dcd1b75bf68ceec345ee7e2ba358e77f9 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 27 May 2022 23:51:40 +0800 Subject: [PATCH] parser: fix match expr case with struct init (#14538) --- vlib/v/parser/parser.v | 7 +++-- .../tests/match_case_with_struct_init_test.v | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/match_case_with_struct_init_test.v diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 8e216c2776..906d672c2f 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -2381,9 +2381,10 @@ pub fn (mut p Parser) name_expr() ast.Expr { && !p.inside_match_case && (!p.inside_if || p.inside_select) && (!p.inside_for || p.inside_select) && !known_var { return p.struct_init(p.mod + '.' + p.tok.lit, false) // short_syntax: false - } else if p.peek_tok.kind == .lcbr && p.inside_if && lit0_is_capital && !known_var - && language == .v { - // if a == Foo{} {...} + } else if p.peek_tok.kind == .lcbr + && ((p.inside_if && lit0_is_capital && !known_var && language == .v) + || (p.inside_match_case && p.tok.kind == .name && p.peek_tok.pos - p.tok.pos == p.tok.len)) { + // `if a == Foo{} {...}` or `match foo { Foo{} {...} }` return p.struct_init(p.mod + '.' + p.tok.lit, false) } else if p.peek_tok.kind == .dot && (lit0_is_capital && !known_var && language == .v) { // T.name diff --git a/vlib/v/tests/match_case_with_struct_init_test.v b/vlib/v/tests/match_case_with_struct_init_test.v new file mode 100644 index 0000000000..77c232c948 --- /dev/null +++ b/vlib/v/tests/match_case_with_struct_init_test.v @@ -0,0 +1,29 @@ +struct Get {} + +struct Post {} + +struct Part { + value string +} + +type RoutePart = Get | Part | Post + +fn test_match_case_with_struct_init() { + route := [RoutePart(Get{}), RoutePart(Part{ + value: '/' + })] + + status_code := match route { + [RoutePart(Get{}), RoutePart(Part{ + value: '/' + })] { + '200' + } + else { + '404' + } + } + + print(status_code) + assert status_code == '200' +}