From e711e8634eacdaace719e7486b443509f3ee3f62 Mon Sep 17 00:00:00 2001 From: Lukas Neubert Date: Thu, 29 Apr 2021 07:28:44 +0200 Subject: [PATCH] fmt: prevent rare code corruption with array pre comments (#9908) --- cmd/tools/vtest-cleancode.v | 1 - vlib/v/fmt/fmt.v | 7 ++++++- vlib/v/fmt/tests/comments_array_keep.vv | 3 +++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/cmd/tools/vtest-cleancode.v b/cmd/tools/vtest-cleancode.v index a347c604d8..25df7972c0 100644 --- a/cmd/tools/vtest-cleancode.v +++ b/cmd/tools/vtest-cleancode.v @@ -38,7 +38,6 @@ const ( 'vlib/v/tests/string_interpolation_test.v' /* TODO byteptr: &byte.str() behaves differently than byteptr.str() */, 'vlib/v/gen/js/tests/js.v', /* local `hello` fn, gets replaced with module `hello` aliased as `hl` */ 'examples/c_interop_wkhtmltopdf.v', /* &charptr --> &&char */ - 'examples/path_tracing.v', /* block --> line comments corrupts code */ 'vlib/v/gen/c/cheaders.v' /* infix wrapping error */, ] vfmt_verify_list = [ diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index e542cb35a3..f064f77529 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -1428,7 +1428,12 @@ pub fn (mut f Fmt) array_init(node ast.ArrayInit) { f.write(' ') } } else { - if c.pos.last_line < node.pos.last_line { + next_line := if node.exprs.len > 0 { + node.exprs[0].position().line_nr + } else { + node.pos.last_line + } + if c.pos.last_line < next_line { f.comment(c, level: .indent) if node.exprs.len == 0 { f.writeln('') diff --git a/vlib/v/fmt/tests/comments_array_keep.vv b/vlib/v/fmt/tests/comments_array_keep.vv index 2ff6c13c52..74632ed849 100644 --- a/vlib/v/fmt/tests/comments_array_keep.vv +++ b/vlib/v/fmt/tests/comments_array_keep.vv @@ -73,4 +73,7 @@ fn comment_at_line_start_with_expressions_after() { arr := [123456789012345, 234567890123456, 678901234567890, 789012345678901, /* at the end */ 345678901234567, /* in between */ 456789012345678, /* line start */ 567890123456789, 890123456789012] + arr2 := [/* same line pre comment */ Foo{ + a: 123 + }] }