diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 932e30534f..4ea7175e6d 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -942,6 +942,7 @@ pub: elem_type_pos token.Position // `Type` in []Type{} position exprs []Expr // `[expr, expr]` or `[expr]Type{}` for fixed array ecmnts [][]Comment // optional iembed comments after each expr + pre_cmnts []Comment is_fixed bool has_val bool // fixed size literal `[expr, expr]!` mod string diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 362d9aaf55..f86007c1cd 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -1961,6 +1961,18 @@ pub fn (mut f Fmt) array_init(it ast.ArrayInit) { mut inc_indent := false mut last_line_nr := it.pos.line_nr // to have the same newlines between array elements f.array_init_depth++ + for i, c in it.pre_cmnts { + if c.pos.line_nr > last_line_nr { + f.writeln('') + } else if i > 0 { + f.write(' ') + } + f.comment(c, level: .indent, iembed: true) + last_line_nr = c.pos.last_line + } + if it.exprs.len == 0 && it.pre_cmnts.len > 0 && it.pre_cmnts[0].pos.line_nr != it.pos.line_nr { + f.writeln('') + } for i, expr in it.exprs { line_nr := expr.position().line_nr if i == 0 { diff --git a/vlib/v/fmt/tests/comments_embedded_keep.vv b/vlib/v/fmt/tests/comments_embedded_keep.vv index 8a6554f89a..72ea53a94e 100644 --- a/vlib/v/fmt/tests/comments_embedded_keep.vv +++ b/vlib/v/fmt/tests/comments_embedded_keep.vv @@ -6,7 +6,7 @@ fn only_comments_array() { /* 4, */ ] arr2 := [ - /* 1, */ /* 2, *//* 3, */ + /* 1, */ /* 2, */ /* 3, */ /* 4, */ ] } diff --git a/vlib/v/parser/containers.v b/vlib/v/parser/containers.v index b487d1480e..036e76aa47 100644 --- a/vlib/v/parser/containers.v +++ b/vlib/v/parser/containers.v @@ -16,6 +16,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { mut elem_type_pos := first_pos mut exprs := []ast.Expr{} mut ecmnts := [][]ast.Comment{} + mut pre_cmnts := []ast.Comment{} mut is_fixed := false mut has_val := false mut has_type := false @@ -39,6 +40,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { last_pos = p.tok.position() } else { // [1,2,3] or [const]byte + pre_cmnts = p.eat_comments({}) for i := 0; p.tok.kind !in [.rsbr, .eof]; i++ { exprs << p.expr(0) ecmnts << p.eat_comments({}) @@ -141,6 +143,7 @@ fn (mut p Parser) array_init() ast.ArrayInit { typ: array_type exprs: exprs ecmnts: ecmnts + pre_cmnts: pre_cmnts pos: pos elem_type_pos: elem_type_pos has_len: has_len