From 621cb7b914a66a0823fab15974b4be85601b25f9 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Tue, 5 May 2020 02:12:40 +0200 Subject: [PATCH] parser: short struct init syntax --- vlib/v/parser/parser.v | 3 +++ vlib/v/parser/struct.v | 8 ++++---- vlib/v/tests/struct_test.v | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index bf0af37977..b3b9bf54a2 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -704,6 +704,9 @@ pub fn (mut p Parser) name_expr() ast.Expr { pos: p.tok.position() mod: mod } + } else if p.peek_tok.kind == .colon && p.prev_tok.kind != .str_dollar { + // `foo(key:val, key2:val2)` + return p.struct_init(true) // short_syntax:true } else { node = p.parse_ident(is_c, is_js) } diff --git a/vlib/v/parser/struct.v b/vlib/v/parser/struct.v index 1b3e097cb1..178ad5d6c4 100644 --- a/vlib/v/parser/struct.v +++ b/vlib/v/parser/struct.v @@ -200,12 +200,12 @@ fn (mut p Parser) struct_init(short_syntax bool) ast.StructInit { } mut fields := []ast.StructInitField{} mut i := 0 - is_short_syntax := p.peek_tok.kind != .colon && p.tok.kind != .rcbr // `Vec{a,b,c} + no_keys := p.peek_tok.kind != .colon && p.tok.kind != .rcbr // `Vec{a,b,c} // p.warn(is_short_syntax.str()) - for p.tok.kind != .rcbr { + for p.tok.kind != .rcbr && p.tok.kind != .rpar { p.check_comment() mut field_name := '' - if is_short_syntax { + if no_keys { expr := p.expr(0) // name will be set later in checker fields << ast.StructInitField{ @@ -247,7 +247,7 @@ fn (mut p Parser) struct_init(short_syntax bool) ast.StructInit { pos: first_pos.pos len: last_pos.pos - first_pos.pos + last_pos.len } - is_short: is_short_syntax + is_short: no_keys } return node } diff --git a/vlib/v/tests/struct_test.v b/vlib/v/tests/struct_test.v index b72db070f0..468bdf6d5c 100644 --- a/vlib/v/tests/struct_test.v +++ b/vlib/v/tests/struct_test.v @@ -244,6 +244,7 @@ fn test_config() { foo2({ name: 'Peter' }) + foo2(name: 'Peter') } struct City {