From e80487b35c1837ab93ca3088774616d82c1eee96 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 5 Nov 2020 18:49:52 +0200 Subject: [PATCH] vfmt: support inline comments before fields in struct initializations --- vlib/v/ast/ast.v | 9 +++++---- vlib/v/fmt/fmt.v | 5 +++++ .../tests/struct_init_with_comments_keep.vv | 20 +++++++++++++++++++ vlib/v/parser/struct.v | 2 ++ 4 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 vlib/v/fmt/tests/struct_init_with_comments_keep.vv diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index f9177e7654..baa9c245c7 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -211,11 +211,12 @@ pub mut: pub struct StructInit { pub: - pos token.Position - is_short bool + pos token.Position + is_short bool + pre_comments []Comment pub mut: - typ table.Type - fields []StructInitField + typ table.Type + fields []StructInitField } // import statement diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index e56f8675f9..5463b543e9 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -1806,6 +1806,11 @@ pub fn (mut f Fmt) struct_init(it ast.StructInit) { } else { f.writeln('$name{') } + f.comments(it.pre_comments, { + inline: true + has_nl: true + level: .indent + }) f.indent++ for field in it.fields { f.write('$field.name: ') diff --git a/vlib/v/fmt/tests/struct_init_with_comments_keep.vv b/vlib/v/fmt/tests/struct_init_with_comments_keep.vv new file mode 100644 index 0000000000..f2341e847a --- /dev/null +++ b/vlib/v/fmt/tests/struct_init_with_comments_keep.vv @@ -0,0 +1,20 @@ +module abcde + +pub struct Builder { +pub mut: + // TODO + buf []byte + str_calls int + len int + initial_size int = 1 +} + +pub fn new_builder(initial_size int) Builder { + return Builder{ + // buf: make(0, initial_size) + buf: []byte{cap: initial_size} + str_calls: 0 // after str_calls + len: 0 // after len + initial_size: initial_size // final + } +} diff --git a/vlib/v/parser/struct.v b/vlib/v/parser/struct.v index 0de2412c79..687d470018 100644 --- a/vlib/v/parser/struct.v +++ b/vlib/v/parser/struct.v @@ -299,6 +299,7 @@ fn (mut p Parser) struct_init(short_syntax bool) ast.StructInit { if !short_syntax { p.check(.lcbr) } + pre_comments := p.eat_comments() mut fields := []ast.StructInitField{} mut i := 0 no_keys := p.peek_tok.kind != .colon && p.tok.kind != .rcbr // `Vec{a,b,c} @@ -354,6 +355,7 @@ fn (mut p Parser) struct_init(short_syntax bool) ast.StructInit { len: last_pos.pos - first_pos.pos + last_pos.len } is_short: no_keys + pre_comments: pre_comments } return node }